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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a1e12a386d12cf37b9a03ad930a6ac345005ad0 | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /small_algebraic_closure_is_integral.lean | 91859741cf9108632623cc8eb2b18deead2b4fb9 | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,561 | lean | import ring_theory.adjoin_root data.equiv.algebra algebra.direct_limit
import set_theory.schroeder_bernstein field_theory.subfield
import ring_theory.integral_closure ring_theory.algebra
universes u v w
open polynomial zorn set function
variables {K : Type u} [discrete_field K]
noncomputable theory
instance equiv.is_ring_hom {α β : Type*} [ring β] (e : α ≃ β) :
@is_ring_hom α β (equiv.ring e) _ e :=
by split; simp [equiv.mul_def, equiv.add_def, equiv.one_def]
instance equiv.is_ring_hom.symm {α β : Type*} [ring β] (e : α ≃ β) :
@is_ring_hom β α _ (equiv.ring e) e.symm :=
by letI := equiv.ring e; exact (show α ≃r β, from ⟨e, equiv.is_ring_hom e⟩).symm.2
namespace algebraic_closure
section map
local attribute [instance] classical.dec
lemma map_aux {X : Type u} {Y : Type v} {Z : Type w} (fxy : X ↪ Y) (fxz : X ↪ Z)
(hYZ : (Z ↪ Y) → false) : ↥-range fxy.1 ↪ ↥-range fxz.1 :=
classical.choice $ or.resolve_left embedding.total $
λ ⟨f⟩, hYZ $
calc Z ↪ range fxz ⊕ ↥-range fxz :
(equiv.set.sum_compl _).symm.to_embedding
... ↪ range fxy ⊕ ↥-range fxy :
embedding.sum_congr
(((equiv.set.range _ fxz.2).symm.to_embedding).trans
(equiv.set.range _ fxy.2).to_embedding)
f
... ↪ Y : (equiv.set.sum_compl _).to_embedding
def map {X : Type u} {Y : Type v} {Z : Type w} (fxy : X ↪ Y) (fxz : X ↪ Z)
(hYZ : (Z ↪ Y) → false) : Y ↪ Z :=
calc Y ↪ range fxy ⊕ ↥-range fxy : (equiv.set.sum_compl _).symm.to_embedding
... ↪ range fxz ⊕ ↥-range fxz : embedding.sum_congr
((equiv.set.range _ fxy.2).symm.to_embedding.trans
(equiv.set.range _ fxz.2).to_embedding)
(map_aux fxy fxz hYZ)
... ↪ Z : (equiv.set.sum_compl _).to_embedding
lemma map_commutes {X : Type u} {Y : Type v} {Z : Type w} (fxy : X ↪ Y) (fxz : X ↪ Z)
(hYZ : (Z ↪ Y) → false) (x : X) : map fxy fxz hYZ (fxy x) = fxz x :=
have (⟨fxy x, mem_range_self _⟩ : range fxy) = equiv.set.range _ fxy.2 x, from rfl,
begin
dsimp only [map, embedding.trans_apply, equiv.trans_apply, function.comp,
equiv.to_embedding_coe_fn],
simp only [equiv.set.sum_compl_symm_apply_of_mem (mem_range_self _),
embedding.sum_congr_apply_inl, equiv.set.sum_compl_apply_inl,
embedding.trans_apply, equiv.to_embedding_coe_fn, this, equiv.symm_apply_apply],
refl
end
end map
end algebraic_closure
class is_algebraically_closed (K : Type u) [nonzero_comm_ring K] [decidable_eq K] :=
(exists_root : ∀ f : polynomial K, 0 < degree f → ∃ x, is_root f x)
-- lemma algebraic_comp {L M : Type*} [comm_ring L] [decidable_eq L] [comm_ring M] [decidable_eq M]
-- (i : K → L) (j : L → M) [is_ring_hom i] [is_ring_hom j] {x : L} :
-- algebraic K i x → algebraic K (j ∘ i) (j x) :=
-- λ ⟨f, hf⟩, ⟨f, hf.1, by rw [← eval_map, function.comp, ← polynomial.map_map i j, eval_map,
-- eval₂_hom, eval_map, hf.2, is_ring_hom.map_zero j]⟩
-- lemma algebraic_id (x : K) : algebraic K id x :=
-- ⟨X - C x, ne_zero_of_monic (monic_X_sub_C _), by simp⟩
-- lemma algebraic_equiv {L : Type*} [discrete_field L] (e : K ≃ L) [is_ring_hom e] (x : L) :
-- algebraic K e x :=
-- ⟨X - C (e.symm x), ne_zero_of_monic (monic_X_sub_C _),
-- by rw [← eval_map, map_sub, map_X, map_C, equiv.apply_symm_apply,
-- eval_sub, eval_X, eval_C, sub_self]⟩
-- lemma algebraic_adjoin_root (f : polynomial K) [irreducible f] :
-- ∀ x, algebraic K (adjoin_root.of : K → adjoin_root f) x := sorry
-- lemma algebraic_comp' {L M : Type*} [discrete_field L] [discrete_field M]
-- (i : K → L) (j : L → M) [is_field_hom i] [is_field_hom j] :
-- (∀ x, algebraic K i x) → (∀ x, algebraic L j x) → ∀ x, algebraic K (j ∘ i) x := sorry
section classical
local attribute [instance, priority 1] classical.dec
/-- The `big_type` with cardinality strictly larger than any algebraic extension -/
def big_type (K : Type u) [discrete_field K] := set (ℕ × polynomial K)
def algebraic_embedding_aux {L : Type*} [discrete_field L] [algebra K L]
(h : ∀ l : L, is_integral K l) (x : L) : ℕ × polynomial K :=
let f := classical.some (h x) in
⟨list.index_of x (quotient.out ((f.map (algebra_map L)).roots.1)), f⟩
lemma algebraic_embedding_aux_injective
{L : Type*} [discrete_field L] [algebra K L]
(h : ∀ l : L, is_integral K l) : injective (algebraic_embedding_aux h) :=
λ x y hxy,
let f := classical.some (h x) in
let g := classical.some (h y) in
have hf : monic f ∧ aeval K L x f = 0, from classical.some_spec (h x),
have hg : monic g ∧ aeval K L y g = 0, from classical.some_spec (h y),
have hfg : f = g, from (prod.ext_iff.1 hxy).2,
have hfg' : list.index_of x (quotient.out ((f.map (algebra_map L)).roots.1)) =
list.index_of y (quotient.out ((f.map (algebra_map L)).roots.1)),
from (prod.ext_iff.1 hxy).1.trans (hfg.symm ▸ rfl),
have hx : x ∈ quotient.out ((f.map (algebra_map L)).roots.1),
from multiset.mem_coe.1 begin
show x ∈ quotient.mk _,
rw [quotient.out_eq, ← finset.mem_def, mem_roots (mt (map_eq_zero (algebra_map L)).1
(ne_zero_of_monic hf.1)), is_root.def, eval_map, ← aeval_def, hf.2],
end,
have hy : y ∈ quotient.out ((g.map (algebra_map L)).roots.1),
from multiset.mem_coe.1 begin
show y ∈ quotient.mk _,
rw [quotient.out_eq, ← finset.mem_def, mem_roots (mt (map_eq_zero (algebra_map L)).1
(ne_zero_of_monic hg.1)), is_root.def, eval_map, ← aeval_def, hg.2],
end,
(list.index_of_inj hx (by rwa hfg)).1 hfg'
lemma injective_eq {α : Sort*} : injective (eq : α → α → Prop) :=
λ _ _ h, h.symm ▸ rfl
def algebraic_embedding_big_type {L : Type*} [discrete_field L] [algebra K L]
(h : ∀ l : L, is_integral K l) : L ↪ big_type K :=
⟨_, injective_comp injective_eq $ algebraic_embedding_aux_injective h⟩
def algebraic_embedding {L : Type*} [discrete_field L] [algebra K L]
(h : ∀ l : L, is_integral K l) : L ↪ ℕ × polynomial K :=
⟨_, algebraic_embedding_aux_injective h⟩
def bembedding (K : Type u) [discrete_field K] : K ↪ big_type K :=
⟨λ a, show set _, from {(0, X - C a)}, λ a b, by simp [C_inj]⟩
instance : discrete_field (set.range (bembedding K)) :=
equiv.discrete_field (equiv.set.range _ (bembedding K).2).symm
structure extension (K : Type u) [discrete_field K] : Type u :=
(carrier : set (big_type K))
[field : discrete_field ↥carrier]
[algebra : algebra K ↥carrier]
--(algebraic : ∀ x : carrier, is_integral K x)
local attribute [instance] extension.field extension.algebra
def base_extension (K : Type u) [discrete_field K] : extension K :=
{ carrier := set.range (bembedding K),
algebra := algebra.of_ring_hom (equiv.set.range _ (bembedding K).2).symm.symm
(equiv.is_ring_hom.symm _) }
-- instance : preorder (extension K) :=
-- { le := λ L M, ∃ hLM : L.carrier ⊆ M.carrier, is_ring_hom (inclusion hLM)
-- ∧ ∀ x : K, inclusion hLM (algebra_map L.carrier x) = algebra_map M.carrier x,
-- le_refl := λ _, ⟨set.subset.refl _, by convert is_ring_hom.id; ext; simp, by simp⟩,
-- le_trans := λ L M N ⟨hLM₁, hLM₂, hLM₃⟩ ⟨hMN₁, hMN₂, hMN₃⟩, ⟨set.subset.trans hLM₁ hMN₁,
-- by resetI; convert is_ring_hom.comp (inclusion hLM₁) (inclusion hMN₁),
-- λ _, by rw [← hMN₃, ← hLM₃, inclusion_inclusion]⟩ }
instance : preorder (extension K) :=
{ le := λ L M, ∃ hLM : L.carrier ⊆ M.carrier, is_ring_hom (inclusion hLM),
le_refl := λ _, ⟨set.subset.refl _, by convert is_ring_hom.id; ext; simp⟩,
le_trans := λ L M N ⟨hLM₁, hLM₂⟩ ⟨hMN₁, hMN₂⟩, ⟨set.subset.trans hLM₁ hMN₁,
by resetI; convert is_ring_hom.comp (inclusion hLM₁) (inclusion hMN₁)⟩ }
-- def hom_of_le {L M : extension K} (h : L ≤ M) : L.carrier →ₐ[K] M.carrier :=
-- { to_fun := inclusion (classical.some h),
-- hom := (classical.some_spec h).1,
-- commutes' := (classical.some_spec h).2 }
private structure chain' (c : set (extension K)) : Prop :=
(chain : chain (≤) c)
local attribute [class] chain'
lemma is_chain (c : set (extension K)) [chain' c]: chain (≤) c :=
chain'.chain (by apply_instance)
section chain
variables (c : set (extension K)) [hcn : nonempty c]
include c hcn
variable [hcn' : chain' c]
include hcn'
instance chain_directed_order : directed_preorder c :=
⟨λ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hkc, hk⟩ := chain.directed_on
(is_chain c) i hi j hj in ⟨⟨k, hkc⟩, hk⟩⟩
def chain_map (i j : c) (hij : i ≤ j) : i.1.carrier → j.1.carrier :=
inclusion (exists.elim hij (λ h _, h))
instance chain_field_hom (i j : c) (hij : i ≤ j) : is_field_hom (chain_map c i j hij) :=
exists.elim hij (λ _, id)
instance chain_directed_system : directed_system (λ i : c, i.1.carrier) (chain_map c) :=
by split; intros; simp [chain_map]
def chain_limit : Type u := ring.direct_limit (λ i : c, i.1.carrier) (chain_map c)
lemma of_eq_of (x : big_type K) (i j : c) (hi : x ∈ i.1.carrier) (hj : x ∈ j.1.carrier) :
ring.direct_limit.of (λ i : c, i.1.carrier) (chain_map c) i ⟨x, hi⟩ =
ring.direct_limit.of (λ i : c, i.1.carrier) (chain_map c) j ⟨x, hj⟩ :=
have hij : i ≤ j ∨ j ≤ i,
from show i.1 ≤ j.1 ∨ j.1 ≤ i.1, from chain.total (is_chain c) i.2 j.2,
hij.elim
(λ hij, begin
rw ← @ring.direct_limit.of_f c _ _ _ (λ i : c, i.1.carrier) _ _ (chain_map c) _
_ _ _ hij,
simp [chain_map, inclusion]
end)
(λ hij, begin
rw ← @ring.direct_limit.of_f c _ _ _ (λ i : c, i.1.carrier) _ _ (chain_map c) _
_ _ _ hij,
simp [chain_map, inclusion]
end)
lemma injective_aux (i j : c)
(x y : ⋃ i : c, i.1.carrier) (hx : x.1 ∈ i.1.carrier) (hy : y.1 ∈ j.1.carrier) :
ring.direct_limit.of (λ i : c, i.1.carrier) (chain_map c) i ⟨x, hx⟩ =
ring.direct_limit.of (λ i : c, i.1.carrier) (chain_map c) j ⟨y, hy⟩ →
x = y :=
have hij : i ≤ j ∨ j ≤ i,
from show i.1 ≤ j.1 ∨ j.1 ≤ i.1, from chain.total (is_chain c) i.2 j.2,
have hinj : ∀ (i j : c) (hij : i ≤ j), injective (chain_map c i j hij),
from λ _ _ _, is_field_hom.injective _,
hij.elim
(λ hij h, begin
rw ← @ring.direct_limit.of_f c _ _ _ (λ i : c, i.1.carrier) _ _ (chain_map c) _
_ _ _ hij at h,
simpa [chain_map, inclusion, subtype.coe_ext.symm] using ring.direct_limit.of_inj hinj j h,
end)
(λ hji h, begin
rw ← @ring.direct_limit.of_f c _ _ _ (λ i : c, i.1.carrier) _ _ (chain_map c) _
_ _ _ hji at h,
simpa [chain_map, inclusion, subtype.coe_ext.symm] using ring.direct_limit.of_inj hinj i h,
end)
def equiv_direct_limit : (⋃ (i : c), i.1.carrier) ≃
ring.direct_limit (λ i : c, i.1.carrier) (chain_map c) :=
@equiv.of_bijective (⋃ i : c, i.1.carrier)
(ring.direct_limit (λ i : c, i.1.carrier) (chain_map c))
(λ x, ring.direct_limit.of _ _ (classical.some (set.mem_Union.1 x.2))
⟨_, classical.some_spec (set.mem_Union.1 x.2)⟩)
⟨λ x y, injective_aux _ _ _ _ _ _ _,
λ x, let ⟨i, ⟨y, hy⟩, hy'⟩ := ring.direct_limit.exists_of x in
⟨⟨y, _, ⟨i, rfl⟩, hy⟩, begin
convert hy',
exact of_eq_of _ _ _ _ _ _
end⟩⟩
instance Union_field : discrete_field (⋃ i : c, i.1.carrier) :=
@equiv.discrete_field _ _ (equiv_direct_limit c)
(field.direct_limit.discrete_field _ _)
instance is_field_hom_Union (i : c) : is_field_hom
(inclusion (set.subset_Union (λ i : c, i.1.carrier) i)) :=
suffices inclusion (set.subset_Union (λ i : c, i.1.carrier) i) =
((equiv_direct_limit c).symm ∘
ring.direct_limit.of (λ i : c, i.1.carrier) (chain_map c) i),
by rw this; exact is_ring_hom.comp _ _,
funext $ λ ⟨_, _⟩,
(equiv_direct_limit c).injective $
by rw [function.comp_app, equiv.apply_symm_apply];
exact of_eq_of _ _ _ _ _ _
-- instance is_field_hom_range_Union [hc : nonempty c]
-- (h : set.range (bembedding K) ⊆ ⋃ i : c, i.1.carrier) :
-- is_field_hom (inclusion h) :=
-- let ⟨i⟩ := hc in
-- have h₁ : i.1.carrier ⊆ ⋃ i : c, i.1.carrier, from set.subset_Union _ i,
-- have h₂ : set.range (bembedding K) ⊆ i.1.carrier, from i.1.range_subset,
-- have inclusion h = inclusion h₁ ∘ inclusion h₂, by simp [function.comp],
-- by rw this; exact is_ring_hom.comp _ _
-- def chain_lift [nonempty c] (α : Type u) [discrete_field α] (i : set.range (bembedding K) → α)
-- [is_field_hom i] [is_algebraically_closed α] :
-- (⋃ i : c, i.1.carrier) → α :=
-- (ring.direct_limit.lift (λ j : c, j.1.carrier) (chain_map _ c) _
-- (λ j : c, j.1.lift i) (λ i j ⟨_, _, h⟩, by introsI; rw [h, chain_map])) ∘
-- (equiv_direct_limit K c)
-- def is_field_hom_chain_lift [nonempty c] (α : Type u) [discrete_field α]
-- (i : set.range (bembedding K) → α) [is_field_hom i]
-- [is_algebraically_closed α] : is_field_hom (chain_lift K c α i) :=
-- is_ring_hom.comp _ _
end chain
--def maximal_extension (c : set (extension K)) (hc : chain (≤) c) : extension K :=
def maximal_extension (c : set (extension K)) (hc : chain (≤) c) :
{ ub : extension K // ∀ L, L ∈ c → L ≤ ub } :=
if h : nonempty c
then by letI : chain' c := ⟨hc⟩; exact
⟨{ carrier := ⋃ (i : c), i.1.carrier,
/- The union is isomorphic to the direct limit. Suffices to prove the direct limit
is an algebraic extension -/
-- algebraic := sorry,
algebra := sorry },
λ e he, ⟨by convert subset_Union _ (⟨e, he⟩ : c); refl,
is_field_hom_Union c ⟨e, he⟩⟩⟩
else ⟨base_extension K, λ a ha, (h ⟨⟨a, ha⟩⟩).elim⟩
set_option old_structure_cmd true
structure algebraic_extension (K : Type u) [discrete_field K] extends extension K :=
(algebraic : ∀ x : carrier, is_integral K x)
open algebraic_extension
instance : preorder (algebraic_extension K) :=
preorder.lift algebraic_extension.to_extension (by apply_instance)
def maximal_algebraic_extension (c : set (algebraic_extension K)) (hc : chain (≤) c) :
{ ub : algebraic_extension K // ∀ L, L ∈ c → L ≤ ub } :=
let M := (maximal_extension (to_extension '' c) (chain.image (≤) _ _ (λ _ _, id) hc)) in
⟨{ algebraic := sorry, -- Field is isomorphic to direct limit of some algebraic extensions
..M.1 },
λ L hL, M.2 _ (mem_image_of_mem _ hL)⟩
lemma exists_algebraic_closure (K : Type u) [discrete_field K] :
∃ m : algebraic_extension K, ∀ a, m ≤ a → a ≤ m :=
zorn (λ c hc, (maximal_algebraic_extension c hc).exists_of_subtype) (λ _ _ _, le_trans)
def closed_extension (K : Type u) [discrete_field K] :=
classical.some (exists_algebraic_closure K)
def algebraic_closure (K : Type u) [discrete_field K] : Type u :=
((classical.some (exists_algebraic_closure K))).carrier
end classical
namespace algebraic_closure
instance : discrete_field (algebraic_closure K) :=
{ has_decidable_eq := classical.dec_eq _,
..(classical.some (exists_algebraic_closure K)).field }
instance : algebra K (algebraic_closure K) :=
(classical.some (exists_algebraic_closure K)).algebra
def of : K → algebraic_closure K := algebra_map _
instance : is_ring_hom (@of K _) := by dunfold of; apply_instance
protected lemma is_integral (x : algebraic_closure K) : is_integral K x :=
(classical.some (exists_algebraic_closure K)).algebraic x
section lift
/- In this section, the homomorphism from any algebraic extension into an algebraic
closure is proven to exist. -/
variables {L : Type v} {M : Type w} [discrete_field L] [algebra K L]
[discrete_field M] [algebra K M] [is_algebraically_closed M] (hL : ∀ x : L, is_integral K x)
/-- This structure is used to prove the existence of a homomorphism from any algebraic extension
into an algebraic closure -/
structure subfield_and_hom (K : Type u) (L : Type v) (M : Type w)
[discrete_field K] [discrete_field L] [algebra K L] (hL : ∀ x : L, is_integral K x)
[discrete_field M] [algebra K M] [is_algebraically_closed M] extends extension K :=
( to_algebraically_closed : carrier →ₐ[K] M )
( to_field : carrier → L )
( is_ring_hom_to_field : is_ring_hom to_field )
open subfield_and_hom
instance : preorder (subfield_and_hom K L M hL) :=
preorder.lift to_extension (by apply_instance)
def maximal_subfield_and_hom (c : set (subfield_and_hom K L M hL)) (hc : chain (≤) c) :
{ ub : subfield_and_hom K L M hL // ∀ N, N ∈ c → N ≤ ub } :=
let ub := (maximal_extension (to_extension '' c) (chain.image (≤) _ _ (λ _ _, id) hc)) in
⟨{ to_algebraically_closed := sorry, --field in question is direct limit of a bunch of fields with
--algebra homs into M
to_field := sorry, -- direct limit of a bunch of subfields is also a subfield
is_ring_hom_to_field := sorry,
..ub.1 },
λ n hN, ub.2 _ (mem_image_of_mem _ hN)⟩
end lift
section adjoin_root
variables {L : Type v} [discrete_field L] [algebra K L] (hL : ∀ x : L, is_integral K x)
(f : polynomial L) [hif : irreducible f]
include hif
instance adjoin_root_algebraic_closure.field :
discrete_field (adjoin_root f) := by apply_instance
instance adjoin_root_algebraic_closure.is_ring_hom :
is_ring_hom (@adjoin_root.of _ _ _ f) := by apply_instance
def adjoin_root.of_embedding : L ↪ adjoin_root f :=
⟨adjoin_root.of, is_field_hom.injective _⟩
/-- TODO: move -/
instance adjoin_root.algebra : algebra K (adjoin_root f) :=
algebra.of_ring_hom (adjoin_root.of ∘ algebra_map _) (is_ring_hom.comp _ _)
def adjoin_root_extension_map : adjoin_root f ↪ big_type K :=
map (adjoin_root.of_embedding f) (algebraic_embedding_big_type hL)
(λ i, let e : big_type K ↪ ℕ × polynomial K := i.trans
(algebraic_embedding sorry) in --adjoining a root to an algebraic extension gives an algebraic extension
cantor_injective e.1 e.2)
instance afhk : discrete_field (set.range (@adjoin_root_extension_map K _ _ _ _ hL f _)) :=
equiv.discrete_field (equiv.set.range _ (embedding.inj _)).symm
def adjoin_root_extension : extension K :=
{ carrier := set.range (@adjoin_root_extension_map K _ _ _ _ hL f _),
algebra := algebra.of_ring_hom
((equiv.set.range _ (embedding.inj' (adjoin_root_extension_map hL f))).symm.symm ∘
algebra_map _) (is_ring_hom.comp _ _) }
-- instance algebraic_closure_adjoin_root_comp.is_ring_hom :
-- is_ring_hom (@adjoin_root.of _ _ _ f ∘ of K) := is_ring_hom.comp _ _
-- lemma adjoin_root_extension_map_apply (x : algebraic_closure K) :
-- (adjoin_root_extension_map K f) (@adjoin_root.of _ _ _ f x) = x.val :=
-- map_commutes _ _ _ _
-- lemma closure_subset_adjoin_root :
-- (closed_extension K).carrier ⊆ set.range (adjoin_root_extension_map K f) :=
-- (λ x h, ⟨adjoin_root.of_embedding K f ⟨x, h⟩,
-- show (adjoin_root_extension_map K f)
-- (adjoin_root.of_embedding K f ⟨x, h⟩) =
-- (⟨x, h⟩ : algebraic_closure K).val,
-- from map_commutes _ _ _ _⟩)
-- lemma adjoin_root_range_subset :
-- (set.range (bembedding K)) ⊆ set.range (adjoin_root_extension_map K f) :=
-- set.subset.trans
-- (classical.some (exists_algebraic_closure K)).range_subset
-- (closure_subset_adjoin_root K f)
-- lemma adjoin_root_inclusion_eq :
-- inclusion (adjoin_root_range_subset K f) =
-- (equiv.set.range _ (adjoin_root_extension_map K f).2) ∘
-- (@adjoin_root.of (algebraic_closure K) _ _ f) ∘
-- inclusion (classical.some (exists_algebraic_closure K)).range_subset :=
-- funext $ λ x, subtype.eq $
-- by simp [inclusion, function.comp, adjoin_root_extension_map_apply]
-- lemma adjoin_root_inclusion_eq' :
-- inclusion (closure_subset_adjoin_root K f) =
-- (equiv.set.range _ (adjoin_root_extension_map K f).2) ∘
-- (@adjoin_root.of (algebraic_closure K) _ _ f) :=
-- funext $ λ x, subtype.eq $
-- by simp [inclusion, function.comp, adjoin_root_extension_map_apply]; refl
-- instance adjoin_root_range.discrete_field :
-- discrete_field (set.range (adjoin_root_extension_map K f)) :=
-- equiv.discrete_field (equiv.set.range _ (embedding.inj _)).symm
-- instance adjoin_root_inclusion.is_ring_hom :
-- is_ring_hom (inclusion (adjoin_root_range_subset K f)) :=
-- begin
-- letI := (classical.some (exists_algebraic_closure K)).is_field_hom,
-- rw [adjoin_root_inclusion_eq, ← equiv.symm_symm (equiv.set.range _ _)],
-- exact @is_ring_hom.comp _ _ _ _ _ (is_ring_hom.comp _ _) _ _ _
-- (equiv.is_ring_hom.symm _)
-- end
-- --set_option eqn_compiler.zeta true
-- def adjoin_root_lift {α : Type u} [_inst_2_1 : discrete_field α] (i : (range ⇑(bembedding K)) → α)
-- [is_field_hom i] [is_algebraically_closed α] :
-- (range ⇑(adjoin_root_extension_map K f)) → α :=
-- begin
-- have h : _ := is_algebraically_closed.exists_root
-- (f.map (lift_aux K i))
-- (by rw degree_map; exact degree_pos_of_ne_zero_of_nonunit
-- (ne_zero_of_irreducible hif) hif.1),
-- exact adjoin_root.lift (lift_aux K i) (classical.some h) (by rw [← eval_map];
-- exact (classical.some_spec h)) ∘
-- (equiv.set.range _ (adjoin_root_extension_map K f).2).symm
-- end
-- lemma adjoin_root_lift.is_ring_hom {α : Type u} [_inst_2_1 : discrete_field α]
-- (i : (range ⇑(bembedding K)) → α) [is_field_hom i] [is_algebraically_closed α] :
-- is_field_hom (adjoin_root_lift _ f i) :=
-- begin
-- letI := equiv.is_ring_hom.symm (equiv.set.range _ (adjoin_root_extension_map K f).2),
-- dsimp [adjoin_root_lift],
-- rw [← equiv.symm_symm (equiv.set.range _ _)],
-- exact is_ring_hom.comp _ _
-- end
instance adjoin_root_extension.field : discrete_field (adjoin_root_extension K f).carrier :=
extension.field _
local attribute [instance] extension.field extension.is_field_hom extension.lift_is_field_hom
lemma closed_extension_le_adjoin_root_extension :
closed_extension K ≤ adjoin_root_extension K f :=
by letI : discrete_field (closed_extension K).carrier := extension.field _; exact
⟨closure_subset_adjoin_root K f, by rw [adjoin_root_inclusion_eq'];
exact is_ring_hom.comp _ _, begin
introsI,
end⟩
instance : is_algebraically_closed (algebraic_closure K) :=
⟨λ f hf0, let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor
(show ¬ is_unit f, from λ h, by rw [is_unit_iff_degree_eq_zero] at h;
rw h at hf0; exact lt_irrefl _ hf0)
(λ h, by rw [← degree_eq_bot] at h;
rw h at hf0; exact absurd hf0 dec_trivial) in
begin
letI := hg.1,
have := classical.some_spec (exists_algebraic_closure K)
(adjoin_root_extension K g),
end⟩
end adjoin_root
end algebraic_closure
|
9a8deab9fefe3a664dde9c1ba088d35faf883891 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/group/ext.lean | bdb05f1d5cc5ec326b6b28eed8743917886aada8 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,014 | lean | /-
Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen, Yury Kudryashov
-/
import algebra.hom.group
/-!
# Extensionality lemmas for monoid and group structures
In this file we prove extensionality lemmas for `monoid` and higher algebraic structures with one
binary operation. Extensionality lemmas for structures that are lower in the hierarchy can be found
in `algebra.group.defs`.
## Implementation details
To get equality of `npow` etc, we define a monoid homomorphism between two monoid structures on the
same type, then apply lemmas like `monoid_hom.map_div`, `monoid_hom.map_pow` etc.
## Tags
monoid, group, extensionality
-/
universe u
@[ext, to_additive]
lemma monoid.ext {M : Type u} ⦃m₁ m₂ : monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
begin
have h₁ : (@monoid.to_mul_one_class _ m₁).one = (@monoid.to_mul_one_class _ m₂).one,
from congr_arg (@mul_one_class.one M) (mul_one_class.ext h_mul),
set f : @monoid_hom M M (@monoid.to_mul_one_class _ m₁) (@monoid.to_mul_one_class _ m₂) :=
{ to_fun := id, map_one' := h₁, map_mul' := λ x y, congr_fun (congr_fun h_mul x) y },
have hpow : m₁.npow = m₂.npow, by { ext n x, exact @monoid_hom.map_pow M M m₁ m₂ f x n },
unfreezingI { cases m₁, cases m₂ },
congr; assumption
end
@[to_additive]
lemma comm_monoid.to_monoid_injective {M : Type u} :
function.injective (@comm_monoid.to_monoid M) :=
begin
rintros ⟨⟩ ⟨⟩ h,
congr'; injection h,
end
@[ext, to_additive]
lemma comm_monoid.ext {M : Type*} ⦃m₁ m₂ : comm_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
comm_monoid.to_monoid_injective $ monoid.ext h_mul
@[to_additive]
lemma left_cancel_monoid.to_monoid_injective {M : Type u} :
function.injective (@left_cancel_monoid.to_monoid M) :=
begin
rintros ⟨⟩ ⟨⟩ h,
congr'; injection h,
end
@[ext, to_additive]
lemma left_cancel_monoid.ext {M : Type u} ⦃m₁ m₂ : left_cancel_monoid M⦄
(h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
left_cancel_monoid.to_monoid_injective $ monoid.ext h_mul
@[to_additive]
lemma right_cancel_monoid.to_monoid_injective {M : Type u} :
function.injective (@right_cancel_monoid.to_monoid M) :=
begin
rintros ⟨⟩ ⟨⟩ h,
congr'; injection h,
end
@[ext, to_additive]
lemma right_cancel_monoid.ext {M : Type u} ⦃m₁ m₂ : right_cancel_monoid M⦄
(h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
right_cancel_monoid.to_monoid_injective $ monoid.ext h_mul
@[to_additive]
lemma cancel_monoid.to_left_cancel_monoid_injective {M : Type u} :
function.injective (@cancel_monoid.to_left_cancel_monoid M) :=
begin
rintros ⟨⟩ ⟨⟩ h,
congr'; injection h,
end
@[ext, to_additive]
lemma cancel_monoid.ext {M : Type*} ⦃m₁ m₂ : cancel_monoid M⦄
(h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
cancel_monoid.to_left_cancel_monoid_injective $ left_cancel_monoid.ext h_mul
@[to_additive]
lemma cancel_comm_monoid.to_comm_monoid_injective {M : Type u} :
function.injective (@cancel_comm_monoid.to_comm_monoid M) :=
begin
rintros ⟨⟩ ⟨⟩ h,
congr'; injection h,
end
@[ext, to_additive]
lemma cancel_comm_monoid.ext {M : Type*} ⦃m₁ m₂ : cancel_comm_monoid M⦄
(h_mul : m₁.mul = m₂.mul) : m₁ = m₂ :=
cancel_comm_monoid.to_comm_monoid_injective $ comm_monoid.ext h_mul
@[ext, to_additive]
lemma div_inv_monoid.ext {M : Type*} ⦃m₁ m₂ : div_inv_monoid M⦄ (h_mul : m₁.mul = m₂.mul)
(h_inv : m₁.inv = m₂.inv) : m₁ = m₂ :=
begin
have h₁ : (@div_inv_monoid.to_monoid _ m₁).one = (@div_inv_monoid.to_monoid _ m₂).one,
from congr_arg (@monoid.one M) (monoid.ext h_mul),
set f : @monoid_hom M M (by letI := m₁; apply_instance) (by letI := m₂; apply_instance) :=
{ to_fun := id, map_one' := h₁, map_mul' := λ x y, congr_fun (congr_fun h_mul x) y },
have hpow : (@div_inv_monoid.to_monoid _ m₁).npow = (@div_inv_monoid.to_monoid _ m₂).npow :=
congr_arg (@monoid.npow M) (monoid.ext h_mul),
have hzpow : m₁.zpow = m₂.zpow,
{ ext m x,
exact @monoid_hom.map_zpow' M M m₁ m₂ f (congr_fun h_inv) x m },
have hdiv : m₁.div = m₂.div,
{ ext a b,
exact @map_div' M M _ m₁ m₂ _ f (congr_fun h_inv) a b },
unfreezingI { cases m₁, cases m₂ },
congr, exacts [h_mul, h₁, hpow, h_inv, hdiv, hzpow]
end
@[ext, to_additive]
lemma group.ext {G : Type*} ⦃g₁ g₂ : group G⦄ (h_mul : g₁.mul = g₂.mul) : g₁ = g₂ :=
begin
set f := @monoid_hom.mk' G G (by letI := g₁; apply_instance) g₂ id
(λ a b, congr_fun (congr_fun h_mul a) b),
exact group.to_div_inv_monoid_injective (div_inv_monoid.ext h_mul
(funext $ @monoid_hom.map_inv G G g₁ (@group.to_division_monoid _ g₂) f))
end
@[ext, to_additive]
lemma comm_group.ext {G : Type*} ⦃g₁ g₂ : comm_group G⦄
(h_mul : g₁.mul = g₂.mul) : g₁ = g₂ :=
comm_group.to_group_injective $ group.ext h_mul
|
348744760886c6a833018ecd5c2e2cf24baa27fd | 217bb195841a8be2d1b4edd2084d6b69ccd62f50 | /library/init/lean/kvmap.lean | 20859bf56abab517145c31bf0acbb3f8b073dc31 | [
"Apache-2.0"
] | permissive | frank-lesser/lean4 | 717f56c9bacd5bf3a67542d2f5cea721d4743a30 | 79e2abe33f73162f773ea731265e456dbfe822f9 | refs/heads/master | 1,589,741,267,933 | 1,556,424,200,000 | 1,556,424,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,526 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.lean.name init.data.option.basic init.data.int
namespace Lean
inductive DataValue
| ofString (v : String)
| ofBool (v : Bool)
| ofName (v : Name)
| ofNat (v : Nat)
| ofInt (v : Int)
def DataValue.beq : DataValue → DataValue → Bool
| (DataValue.ofString s₁) (DataValue.ofString s₂) := s₁ = s₂
| (DataValue.ofNat n₁) (DataValue.ofNat n₂) := n₂ = n₂
| (DataValue.ofBool b₁) (DataValue.ofBool b₂) := b₁ = b₂
| _ _ := false
instance DataValue.HasBeq : HasBeq DataValue := ⟨DataValue.beq⟩
instance string2DataValue : HasCoe String DataValue := ⟨DataValue.ofString⟩
instance bool2DataValue : HasCoe Bool DataValue := ⟨DataValue.ofBool⟩
instance name2DataValue : HasCoe Name DataValue := ⟨DataValue.ofName⟩
instance nat2DataValue : HasCoe Nat DataValue := ⟨DataValue.ofNat⟩
instance int2DataValue : HasCoe 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 :=
(entries : List (Name × DataValue) := [])
namespace KVMap
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 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)
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 : HasBeq KVMap := ⟨eqv⟩
class isKVMapVal (α : Type) :=
(defVal : α)
(set : KVMap → Name → α → KVMap)
(get : KVMap → Name → α → α)
export isKVMapVal (set)
@[inline] def get {α : Type} [isKVMapVal α] (m : KVMap) (k : Name) (defVal := isKVMapVal.defVal α) : α :=
isKVMapVal.get m k defVal
instance boolVal : isKVMapVal Bool :=
{ defVal := false, set := setBool, get := λ k n v, getBool k n v }
instance natVal : isKVMapVal Nat :=
{ defVal := 0, set := setNat, get := λ k n v, getNat k n v }
instance intVal : isKVMapVal Int :=
{ defVal := 0, set := setInt, get := λ k n v, getInt k n v }
instance nameVal : isKVMapVal Name :=
{ defVal := Name.anonymous, set := setName, get := λ k n v, getName k n v }
instance stringVal : isKVMapVal String :=
{ defVal := "", set := setString, get := λ k n v, getString k n v }
end KVMap
end Lean
|
839d39a8291e54f139c25a38c0bfa12b105f72c3 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/test/amc12-2000-p20.lean | dbbbfd6c157b528b5af6b383dcb3eee037dade2c | [
"Apache-2.0",
"MIT"
] | 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 | 323 | 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 (x y z : ℝ) (h₀ : 0 < x ∧ 0 < y ∧ 0 < z) (h₁ : x + 1/y = 4) (h₂ : y + 1/z = 1) (h₃ : z + 1/x = 7/3) : x*y*z = 1 :=
begin
sorry
end
|
b881532c80e3cdb1afdefe063109c7bf56fc34a6 | 0a7cf55e50e699ca449b876d32f72a58919da5b9 | /src/knights_and_knaves.lean | 42c9c739e66056d33828847a0540f4005959258f | [] | no_license | stanescuUW/LeanPuzzles | afaa0a10c8d9cb8dc5651e1287e8d901d22b9e7c | 5cd8d072ec88deb890b6cacd464bc198b7453ff8 | refs/heads/master | 1,667,707,546,355 | 1,593,179,367,000 | 1,593,179,367,000 | 273,576,407 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,996 | lean | /-
Copyright (c) 2020 Dan Stanescu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dan Stanescu.
-/
import tactic
/-!
# Knights and knaves puzzles
Two puzzles from "Knights and Knaves" by Raymond Smullyan.
For an online description of these puzzles, see: http://mesosyn.com/mental1-6.html
More information on R. Smullyan: https://en.wikipedia.org/wiki/Raymond_Smullyan
There is an island where all inhabitants are either knights or knaves.
Knights always tell the truth. Knaves always lie.
Joe and Bob are two inhabitants of this island.
-/
inductive islander
| knight
| knave
notation `y` := islander.knight
notation `n` := islander.knave
structure Q := (Joe Bob : islander)
/--
In this first puzzle, only Joe makes a statement.
He affirms that both protagonist (i.e. both Joe and Bob) are knaves.
Question: what kind of islanders are they in fact?
-/
def Q1 := Q
namespace Q1
variables (q : Q1)
-- Joe's statement
def S1 := q.Joe = n ∧ q.Bob = n
-- Stating that Joe can be a knight or a knave
def H := (q.Joe = y ∧ q.S1) ∨ (q.Joe = n ∧ ¬ q.S1)
lemma answer : q.H → q.Joe = n ∧ q.Bob = y :=
begin
rcases q with ⟨_|_,_|_⟩;
{ simp [H, S1], },
done
end
end Q1
/--
In the second puzzle, both Joe and Bob make a statement.
Joe states that he's a knave if and only if Bob is a knave.
Bob only states that they are different kinds.
Question: again, what kind of islanders are our protagonists?
-/
def Q2 := Q
namespace Q2
variables (q : Q2)
-- Joe's statement
def S1 := q.Joe = n ↔ q.Bob = n
-- Bob's statement
def S2 := q.Joe ≠ q.Bob
-- Stating that either one can be a knight or a knave
def H1 := (q.Joe = y ∧ q.S1) ∨ (q.Joe = n ∧ ¬ q.S1)
def H2 := (q.Bob = y ∧ q.S2) ∨ (q.Bob = n ∧ ¬ q.S2)
-- Again two forms here:
def H := q.H1 ∧ q.H2
lemma answer : q.H → q.Joe = n ∧ q.Bob = y :=
begin
rcases q with ⟨_|_,_|_⟩;
{ simp [H, H1, S1, H2, S2], },
done
end
end Q2
|
aef33cc6239afd7e08a1f610de9f1aecfb520ee5 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/name_resolution_with_params_bug.lean | 27f232ca870fe75999b4a2b6cf0f661d2eff81ae | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 415 | lean | section
parameters x y : nat
def z := x + y
lemma h0 : z = y + x := add_comm _ _
open tactic
theorem foo₁ : z = y + x := -- doesn't work
begin
rw h0
end
theorem foo₃ : z = y + x := -- doesn't work
by rewrite h0
theorem foo₄ : z = y + x := -- doesn't work
begin
simp [h0]
end
theorem foo₅ : z = y + x := -- doesn't work
begin [smt]
ematch_using [h0]
end
end
|
3915aaeae523292d7b977970aee9ba33cc70862b | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/algebra/category/morphism.lean | 667c7a9f05b838fffeb2ce1d9d899368a3aed361 | [
"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 | 11,981 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
-/
import .basic algebra.relation algebra.binary
open eq eq.ops category
namespace morphism
variables {ob : Type} [C : category ob] include C
variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a}
inductive is_section [class] (f : a ⟶ b) : Type
:= mk : ∀{g}, g ∘ f = id → is_section f
inductive is_retraction [class] (f : a ⟶ b) : Type
:= mk : ∀{g}, f ∘ g = id → is_retraction f
inductive is_iso [class] (f : a ⟶ b) : Type
:= mk : ∀{g}, g ∘ f = id → f ∘ g = id → is_iso f
attribute is_iso [multiple_instances]
definition retraction_of (f : a ⟶ b) [H : is_section f] : hom b a :=
is_section.rec (λg h, g) H
definition section_of (f : a ⟶ b) [H : is_retraction f] : hom b a :=
is_retraction.rec (λg h, g) H
definition inverse (f : a ⟶ b) [H : is_iso f] : hom b a :=
is_iso.rec (λg h1 h2, g) H
postfix `⁻¹` := inverse
theorem inverse_compose (f : a ⟶ b) [H : is_iso f] : f⁻¹ ∘ f = id :=
is_iso.rec (λg h1 h2, h1) H
theorem compose_inverse (f : a ⟶ b) [H : is_iso f] : f ∘ f⁻¹ = id :=
is_iso.rec (λg h1 h2, h2) H
theorem retraction_compose (f : a ⟶ b) [H : is_section f] : retraction_of f ∘ f = id :=
is_section.rec (λg h, h) H
theorem compose_section (f : a ⟶ b) [H : is_retraction f] : f ∘ section_of f = id :=
is_retraction.rec (λg h, h) H
attribute [instance]
theorem iso_imp_retraction (f : a ⟶ b) [H : is_iso f] : is_section f :=
is_section.mk !inverse_compose
attribute [instance]
theorem iso_imp_section (f : a ⟶ b) [H : is_iso f] : is_retraction f :=
is_retraction.mk !compose_inverse
attribute [instance]
theorem id_is_iso : is_iso (ID a) :=
is_iso.mk !id_compose !id_compose
attribute [instance]
theorem inverse_is_iso (f : a ⟶ b) [H : is_iso f] : is_iso (f⁻¹) :=
is_iso.mk !compose_inverse !inverse_compose
theorem left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a}
(Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' :=
calc
g = g ∘ id : by rewrite id_right
... = g ∘ f ∘ g' : by rewrite -Hr
... = (g ∘ f) ∘ g' : by rewrite assoc
... = id ∘ g' : by rewrite Hl
... = g' : by rewrite id_left
theorem retraction_eq_intro [H : is_section f] (H2 : f ∘ h = id) : retraction_of f = h :=
left_inverse_eq_right_inverse !retraction_compose H2
theorem section_eq_intro [H : is_retraction f] (H2 : h ∘ f = id) : section_of f = h :=
symm (left_inverse_eq_right_inverse H2 !compose_section)
theorem inverse_eq_intro_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h :=
left_inverse_eq_right_inverse !inverse_compose H2
theorem inverse_eq_intro_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h :=
symm (left_inverse_eq_right_inverse H2 !compose_inverse)
theorem section_eq_retraction (f : a ⟶ b) [Hl : is_section f] [Hr : is_retraction f] :
retraction_of f = section_of f :=
retraction_eq_intro !compose_section
theorem section_retraction_imp_iso (f : a ⟶ b) [Hl : is_section f] [Hr : is_retraction f]
: is_iso f :=
is_iso.mk (subst (section_eq_retraction f) (retraction_compose f)) (compose_section f)
theorem inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' :=
inverse_eq_intro_left !inverse_compose
theorem inverse_involutive (f : a ⟶ b) [H : is_iso f] : (f⁻¹)⁻¹ = f :=
inverse_eq_intro_right !inverse_compose
theorem retraction_of_id : retraction_of (ID a) = id :=
retraction_eq_intro !id_compose
theorem section_of_id : section_of (ID a) = id :=
section_eq_intro !id_compose
theorem iso_of_id : (ID a)⁻¹ = id :=
inverse_eq_intro_left !id_compose
attribute [instance]
theorem composition_is_section [Hf : is_section f] [Hg : is_section g]
: is_section (g ∘ f) :=
is_section.mk
(calc
(retraction_of f ∘ retraction_of g) ∘ g ∘ f
= retraction_of f ∘ retraction_of g ∘ g ∘ f : by rewrite -assoc
... = retraction_of f ∘ (retraction_of g ∘ g) ∘ f : by rewrite (assoc _ g f)
... = retraction_of f ∘ id ∘ f : by rewrite retraction_compose
... = retraction_of f ∘ f : by rewrite id_left
... = id : by rewrite retraction_compose)
attribute [instance]
theorem composition_is_retraction [Hf : is_retraction f] [Hg : is_retraction g]
: is_retraction (g ∘ f) :=
is_retraction.mk
(calc
(g ∘ f) ∘ section_of f ∘ section_of g
= g ∘ f ∘ section_of f ∘ section_of g : by rewrite -assoc
... = g ∘ (f ∘ section_of f) ∘ section_of g : by rewrite -assoc
... = g ∘ id ∘ section_of g : by rewrite compose_section
... = g ∘ section_of g : by rewrite id_left
... = id : by rewrite compose_section)
attribute [instance]
theorem composition_is_inverse [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) :=
!section_retraction_imp_iso
structure isomorphic (a b : ob) :=
(iso : a ⟶ b)
[is_iso : is_iso iso]
infix `≅`:50 := morphism.isomorphic
namespace isomorphic
open relation
attribute is_iso [instance]
theorem refl (a : ob) : a ≅ a := mk id
theorem symm ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (inverse (iso H))
theorem trans ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (iso H2 ∘ iso H1)
attribute [instance]
theorem is_equivalence_eq (T : Type) : is_equivalence (isomorphic : ob → ob → Type) :=
is_equivalence.mk refl symm trans
end isomorphic
inductive is_mono [class] (f : a ⟶ b) : Prop :=
mk : (∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) → is_mono f
inductive is_epi [class] (f : a ⟶ b) : Prop :=
mk : (∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) → is_epi f
theorem mono_elim [H : is_mono f] {g h : c ⟶ a} (H2 : f ∘ g = f ∘ h) : g = h :=
match H with
is_mono.mk H3 := H3 c g h H2
end
theorem epi_elim [H : is_epi f] {g h : b ⟶ c} (H2 : g ∘ f = h ∘ f) : g = h :=
match H with
is_epi.mk H3 := H3 c g h H2
end
attribute [instance]
theorem section_is_mono (f : a ⟶ b) [H : is_section f] : is_mono f :=
is_mono.mk
(λ c g h H, calc
g = id ∘ g : by rewrite id_left
... = (retraction_of f ∘ f) ∘ g : by rewrite -(retraction_compose f)
... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc]
... = id ∘ h : by rewrite retraction_compose
... = h : by rewrite id_left)
attribute [instance]
theorem retraction_is_epi (f : a ⟶ b) [H : is_retraction f] : is_epi f :=
is_epi.mk
(λ c g h H, calc
g = g ∘ id : by rewrite id_right
... = g ∘ f ∘ section_of f : by rewrite -(compose_section f)
... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc]
... = h ∘ id : by rewrite compose_section
... = h : by rewrite id_right)
--these theorems are now proven automatically using type classes
--should they be instances?
theorem id_is_mono : is_mono (ID a)
theorem id_is_epi : is_epi (ID a)
attribute [instance]
theorem composition_is_mono [Hf : is_mono f] [Hg : is_mono g] : is_mono (g ∘ f) :=
is_mono.mk
(λ d h₁ h₂ H,
have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂),
begin
rewrite *assoc, exact H
end,
mono_elim (mono_elim H2))
attribute [instance]
theorem composition_is_epi [Hf : is_epi f] [Hg : is_epi g] : is_epi (g ∘ f) :=
is_epi.mk
(λ d h₁ h₂ H,
have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f,
begin
rewrite -*assoc, exact H
end,
epi_elim (epi_elim H2))
end morphism
namespace morphism
--rewrite lemmas for inverses, modified from
--https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v
namespace iso
section
variables {ob : Type} [C : category ob] include C
variables {a b c d : ob}
variables (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b)
variables (g : d ⟶ c)
variable [Hq : is_iso q] include Hq
theorem compose_pV : q ∘ q⁻¹ = id := !compose_inverse
theorem compose_Vp : q⁻¹ ∘ q = id := !inverse_compose
theorem compose_V_pp : q⁻¹ ∘ (q ∘ p) = p :=
calc
q⁻¹ ∘ (q ∘ p) = (q⁻¹ ∘ q) ∘ p : by rewrite assoc
... = id ∘ p : by rewrite inverse_compose
... = p : by rewrite id_left
theorem compose_p_Vp : q ∘ (q⁻¹ ∘ g) = g :=
calc
q ∘ (q⁻¹ ∘ g) = (q ∘ q⁻¹) ∘ g : by rewrite assoc
... = id ∘ g : by rewrite compose_inverse
... = g : by rewrite id_left
theorem compose_pp_V : (r ∘ q) ∘ q⁻¹ = r :=
calc
(r ∘ q) ∘ q⁻¹ = r ∘ q ∘ q⁻¹ : by rewrite assoc
... = r ∘ id : by rewrite compose_inverse
... = r : by rewrite id_right
theorem compose_pV_p : (f ∘ q⁻¹) ∘ q = f :=
calc
(f ∘ q⁻¹) ∘ q = f ∘ q⁻¹ ∘ q : by rewrite assoc
... = f ∘ id : by rewrite inverse_compose
... = f : by rewrite id_right
theorem inv_pp [H' : is_iso p] : (q ∘ p)⁻¹ = p⁻¹ ∘ q⁻¹ :=
inverse_eq_intro_left
(show (p⁻¹ ∘ (q⁻¹)) ∘ q ∘ p = id, from
by rewrite [-assoc, compose_V_pp, inverse_compose])
theorem inv_Vp [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▸ inv_pp (q⁻¹) g
theorem inv_pV [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▸ inv_pp q (f⁻¹)
theorem inv_VV [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▸ inv_Vp q (r⁻¹)
end
section
variables {ob : Type} {C : category ob} include C
variables {d c b a : ob}
variables {i : b ⟶ c} {f : b ⟶ a}
{r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b}
{g : d ⟶ c} {h : c ⟶ b}
{x : b ⟶ d} {z : a ⟶ c}
{y : d ⟶ b} {w : c ⟶ a}
variable [Hq : is_iso q] include Hq
theorem moveR_Mp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▸ compose_p_Vp q g
theorem moveR_pM (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▸ compose_pV_p f q
theorem moveR_Vp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▸ compose_V_pp q p
theorem moveR_pV (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▸ compose_pp_V r q
theorem moveL_Mp (H : q⁻¹ ∘ g = y) : g = q ∘ y := (moveR_Mp (H⁻¹))⁻¹
theorem moveL_pM (H : f ∘ q⁻¹ = w) : f = w ∘ q := (moveR_pM (H⁻¹))⁻¹
theorem moveL_Vp (H : q ∘ p = z) : p = q⁻¹ ∘ z := (moveR_Vp (H⁻¹))⁻¹
theorem moveL_pV (H : r ∘ q = x) : r = x ∘ q⁻¹ := (moveR_pV (H⁻¹))⁻¹
theorem moveL_1V (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_intro_left H)⁻¹
theorem moveL_V1 (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_intro_right H)⁻¹
theorem moveL_1M (H : i ∘ q⁻¹ = id) : i = q := moveL_1V H ⬝ inverse_involutive q
theorem moveL_M1 (H : q⁻¹ ∘ i = id) : i = q := moveL_V1 H ⬝ inverse_involutive q
theorem moveR_1M (H : id = i ∘ q⁻¹) : q = i := (moveL_1M (H⁻¹))⁻¹
theorem moveR_M1 (H : id = q⁻¹ ∘ i) : q = i := (moveL_M1 (H⁻¹))⁻¹
theorem moveR_1V (H : id = h ∘ q) : q⁻¹ = h := (moveL_1V (H⁻¹))⁻¹
theorem moveR_V1 (H : id = q ∘ h) : q⁻¹ = h := (moveL_V1 (H⁻¹))⁻¹
end
end iso
end morphism
|
4e59cf5be5233d5ee661bbcf45ebf4297858a1eb | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/fintype.lean | 18b9be514762f73eb11bd2c2cb28226c44b01389 | [] | 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 | 575 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.associated
import Mathlib.data.fintype.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Some facts about finite rings
-/
theorem card_units_lt (R : Type u_1) [semiring R] [nontrivial R] [fintype R] : fintype.card (units R) < fintype.card R :=
card_lt_card_of_injective_of_not_mem coe units.ext not_is_unit_zero
|
136bc7a5a1365fbb2cb5e4a48b76076e489e2fca | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/special_functions/pow_deriv.lean | 8b39292431f8da2def720c9c1413cc21286cffae | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 25,236 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel,
Rémy Degenne
-/
import analysis.special_functions.pow
import analysis.special_functions.complex.log_deriv
import analysis.calculus.extend_deriv
import analysis.special_functions.log.deriv
import analysis.special_functions.trigonometric.deriv
/-!
# Derivatives of power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞`
We also prove differentiability and provide derivatives for the power functions `x ^ y`.
-/
noncomputable theory
open_locale classical real topological_space nnreal ennreal filter
open filter
namespace complex
lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) :
has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2)
((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ +
(p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p :=
begin
have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp },
have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)),
from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono
(λ p hp, cpow_def_of_ne_zero hp _),
rw [cpow_sub _ _ A, cpow_one, mul_div_left_comm, mul_smul, mul_smul, ← smul_add],
refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm,
simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm]
using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp
end
lemma has_strict_fderiv_at_cpow' {x y : ℂ} (hp : 0 < x.re ∨ x.im ≠ 0) :
has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2)
((y * x ^ (y - 1)) • continuous_linear_map.fst ℂ ℂ ℂ +
(x ^ y * log x) • continuous_linear_map.snd ℂ ℂ ℂ) (x, y) :=
@has_strict_fderiv_at_cpow (x, y) hp
lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) :
has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y :=
begin
rcases em (x = 0) with rfl|hx,
{ replace h := h.neg_resolve_left rfl,
rw [log_zero, mul_zero],
refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _,
exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) },
{ simpa only [cpow_def_of_ne_zero hx, mul_one]
using ((has_strict_deriv_at_id y).const_mul (log x)).cexp }
end
lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) :
has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2)
((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ +
(p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p :=
(has_strict_fderiv_at_cpow hp).has_fderiv_at
end complex
section fderiv
open complex
variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ}
{x : E} {s : set E} {c : ℂ}
lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x)
(hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_strict_fderiv_at (λ x, f x ^ g x)
((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x :=
by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg)
lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x :=
(has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf
lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_fderiv_at (λ x, f x ^ g x)
((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x :=
by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg)
lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x :=
(has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf
lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_fderiv_within_at (λ x, f x ^ g x)
((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x :=
by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x
(hf.prod hg)
lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x :=
(has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf
lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable_at ℂ (λ x, f x ^ g x) x :=
(hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at
lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
differentiable_at ℂ (λ x, c ^ f x) x :=
(hf.has_fderiv_at.const_cpow h0).differentiable_at
lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x)
(hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
differentiable_within_at ℂ (λ x, f x ^ g x) s x :=
(hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at
lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x)
(h0 : c ≠ 0 ∨ f x ≠ 0) :
differentiable_within_at ℂ (λ x, c ^ f x) s x :=
(hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at
end fderiv
section deriv
open complex
variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ}
/-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form
expected by lemmas like `has_deriv_at.cpow`. -/
private lemma aux :
((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' +
(f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 =
g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' :=
by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply,
continuous_linear_map.coe_smul']
lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_strict_deriv_at (λ x, f x ^ g x)
(g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x :=
by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at
lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) :
has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x :=
(has_strict_deriv_at_const_cpow h).comp x hf
lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) :
has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x :=
by simpa only [mul_zero, add_zero, mul_one]
using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h
lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x :=
(complex.has_strict_deriv_at_cpow_const h0).comp x hf
lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x :=
by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at
lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x :=
(has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf
lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x :=
(complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf
lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x)
(hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_within_at (λ x, f x ^ g x)
(g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x :=
by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at
lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) :
has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x :=
(has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf
lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x)
(h0 : 0 < (f x).re ∨ (f x).im ≠ 0) :
has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x :=
(complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf
end deriv
namespace real
variables {x y z : ℝ}
/-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/
lemma has_strict_fderiv_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) :
has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2)
((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ +
(p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℝ ℝ ℝ) p :=
begin
have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)),
from (continuous_at_fst.eventually (lt_mem_nhds hp)).mono (λ p hp, rpow_def_of_pos hp _),
refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm,
convert ((has_strict_fderiv_at_fst.log hp.ne').mul has_strict_fderiv_at_snd).exp,
rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_left_comm,
div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm]
end
/-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/
lemma has_strict_fderiv_at_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) :
has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2)
((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ +
(p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) •
continuous_linear_map.snd ℝ ℝ ℝ) p :=
begin
have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2) * cos (x.2 * π)),
from (continuous_at_fst.eventually (gt_mem_nhds hp)).mono (λ p hp, rpow_def_of_neg hp _),
refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm,
convert ((has_strict_fderiv_at_fst.log hp.ne).mul has_strict_fderiv_at_snd).exp.mul
(has_strict_fderiv_at_snd.mul_const _).cos using 1,
simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc,
mul_comm (cos _), ← rpow_def_of_neg hp],
rw [div_eq_mul_inv, add_comm], congr' 2; ring
end
/-- The function `λ (x, y), x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/
lemma cont_diff_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : ℕ∞} :
cont_diff_at ℝ n (λ p : ℝ × ℝ, p.1 ^ p.2) p :=
begin
cases hp.lt_or_lt with hneg hpos,
exacts [(((cont_diff_at_fst.log hneg.ne).mul cont_diff_at_snd).exp.mul
(cont_diff_at_snd.mul cont_diff_at_const).cos).congr_of_eventually_eq
((continuous_at_fst.eventually (gt_mem_nhds hneg)).mono (λ p hp, rpow_def_of_neg hp _)),
((cont_diff_at_fst.log hpos.ne').mul cont_diff_at_snd).exp.congr_of_eventually_eq
((continuous_at_fst.eventually (lt_mem_nhds hpos)).mono (λ p hp, rpow_def_of_pos hp _))]
end
lemma differentiable_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) :
differentiable_at ℝ (λ p : ℝ × ℝ, p.1 ^ p.2) p :=
(cont_diff_at_rpow_of_ne p hp).differentiable_at le_rfl
lemma _root_.has_strict_deriv_at.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : has_strict_deriv_at f f' x)
(hg : has_strict_deriv_at g g' x) (h : 0 < f x) :
has_strict_deriv_at (λ x, f x ^ g x)
(f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x :=
begin
convert (has_strict_fderiv_at_rpow_of_pos ((λ x, (f x, g x)) x) h).comp_has_strict_deriv_at _
(hf.prod hg) using 1,
simp [mul_assoc, mul_comm, mul_left_comm]
end
lemma has_strict_deriv_at_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) :
has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x :=
begin
cases hx.lt_or_lt with hx hx,
{ have := (has_strict_fderiv_at_rpow_of_neg (x, p) hx).comp_has_strict_deriv_at x
((has_strict_deriv_at_id x).prod (has_strict_deriv_at_const _ _)),
convert this, simp },
{ simpa using (has_strict_deriv_at_id x).rpow (has_strict_deriv_at_const x p) hx }
end
lemma has_strict_deriv_at_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) :
has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a) x :=
by simpa using (has_strict_deriv_at_const _ _).rpow (has_strict_deriv_at_id x) ha
/-- This lemma says that `λ x, a ^ x` is strictly differentiable for `a < 0`. Note that these
values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x`
for negative `a` if some other definition will be more convenient. -/
lemma has_strict_deriv_at_const_rpow_of_neg {a x : ℝ} (ha : a < 0) :
has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x :=
by simpa using (has_strict_fderiv_at_rpow_of_neg (a, x) ha).comp_has_strict_deriv_at x
((has_strict_deriv_at_const _ _).prod (has_strict_deriv_at_id _))
end real
namespace real
variables {z x y : ℝ}
lemma has_deriv_at_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) :
has_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x :=
begin
rcases ne_or_eq x 0 with hx | rfl,
{ exact (has_strict_deriv_at_rpow_const_of_ne hx _).has_deriv_at },
replace h : 1 ≤ p := h.neg_resolve_left rfl,
apply has_deriv_at_of_has_deriv_at_of_ne
(λ x hx, (has_strict_deriv_at_rpow_const_of_ne hx p).has_deriv_at),
exacts [continuous_at_id.rpow_const (or.inr (zero_le_one.trans h)),
continuous_at_const.mul (continuous_at_id.rpow_const (or.inr (sub_nonneg.2 h)))]
end
lemma differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) :
differentiable ℝ (λ x : ℝ, x ^ p) :=
λ x, (has_deriv_at_rpow_const (or.inr hp)).differentiable_at
lemma deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) :
deriv (λ x : ℝ, x ^ p) x = p * x ^ (p - 1) :=
(has_deriv_at_rpow_const h).deriv
lemma deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) :
deriv (λ x : ℝ, x ^ p) = λ x, p * x ^ (p - 1) :=
funext $ λ x, deriv_rpow_const (or.inr h)
lemma cont_diff_at_rpow_const_of_ne {x p : ℝ} {n : ℕ∞} (h : x ≠ 0) :
cont_diff_at ℝ n (λ x, x ^ p) x :=
(cont_diff_at_rpow_of_ne (x, p) h).comp x
(cont_diff_at_id.prod cont_diff_at_const)
lemma cont_diff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) :
cont_diff ℝ n (λ x : ℝ, x ^ p) :=
begin
induction n with n ihn generalizing p,
{ exact cont_diff_zero.2 (continuous_id.rpow_const (λ x, by exact_mod_cast or.inr h)) },
{ have h1 : 1 ≤ p, from le_trans (by simp) h,
rw [nat.cast_succ, ← le_sub_iff_add_le] at h,
rw [cont_diff_succ_iff_deriv, deriv_rpow_const' h1],
refine ⟨differentiable_rpow_const h1, cont_diff_const.mul (ihn h)⟩ }
end
lemma cont_diff_at_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) :
cont_diff_at ℝ n (λ x : ℝ, x ^ p) x :=
(cont_diff_rpow_const_of_le h).cont_diff_at
lemma cont_diff_at_rpow_const {x p : ℝ} {n : ℕ} (h : x ≠ 0 ∨ ↑n ≤ p) :
cont_diff_at ℝ n (λ x : ℝ, x ^ p) x :=
h.elim cont_diff_at_rpow_const_of_ne cont_diff_at_rpow_const_of_le
lemma has_strict_deriv_at_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) :
has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x :=
cont_diff_at.has_strict_deriv_at'
(cont_diff_at_rpow_const (by rwa nat.cast_one))
(has_deriv_at_rpow_const hx) le_rfl
end real
section differentiability
open real
section fderiv
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ}
{x : E} {s : set E} {c p : ℝ} {n : ℕ∞}
lemma has_fderiv_within_at.rpow (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at g g' s x) (h : 0 < f x) :
has_fderiv_within_at (λ x, f x ^ g x)
((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x :=
(has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp_has_fderiv_within_at x
(hf.prod hg)
lemma has_fderiv_at.rpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h : 0 < f x) :
has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x :=
(has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp x (hf.prod hg)
lemma has_strict_fderiv_at.rpow (hf : has_strict_fderiv_at f f' x)
(hg : has_strict_fderiv_at g g' x) (h : 0 < f x) :
has_strict_fderiv_at (λ x, f x ^ g x)
((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x :=
(has_strict_fderiv_at_rpow_of_pos (f x, g x) h).comp x (hf.prod hg)
lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x)
(hg : differentiable_within_at ℝ g s x) (h : f x ≠ 0) :
differentiable_within_at ℝ (λ x, f x ^ g x) s x :=
(differentiable_at_rpow_of_ne (f x, g x) h).comp_differentiable_within_at x (hf.prod hg)
lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x)
(h : f x ≠ 0) :
differentiable_at ℝ (λ x, f x ^ g x) x :=
(differentiable_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg)
lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s)
(h : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λ x, f x ^ g x) s :=
λ x hx, (hf x hx).rpow (hg x hx) (h x hx)
lemma differentiable.rpow (hf : differentiable ℝ f) (hg : differentiable ℝ g) (h : ∀ x, f x ≠ 0) :
differentiable ℝ (λ x, f x ^ g x) :=
λ x, (hf x).rpow (hg x) (h x)
lemma has_fderiv_within_at.rpow_const (hf : has_fderiv_within_at f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) :
has_fderiv_within_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') s x :=
(has_deriv_at_rpow_const h).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.rpow_const (hf : has_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) :
has_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x :=
(has_deriv_at_rpow_const h).comp_has_fderiv_at x hf
lemma has_strict_fderiv_at.rpow_const (hf : has_strict_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) :
has_strict_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x :=
(has_strict_deriv_at_rpow_const h).comp_has_strict_fderiv_at x hf
lemma differentiable_within_at.rpow_const (hf : differentiable_within_at ℝ f s x)
(h : f x ≠ 0 ∨ 1 ≤ p) :
differentiable_within_at ℝ (λ x, f x ^ p) s x :=
(hf.has_fderiv_within_at.rpow_const h).differentiable_within_at
@[simp] lemma differentiable_at.rpow_const (hf : differentiable_at ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) :
differentiable_at ℝ (λ x, f x ^ p) x :=
(hf.has_fderiv_at.rpow_const h).differentiable_at
lemma differentiable_on.rpow_const (hf : differentiable_on ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) :
differentiable_on ℝ (λ x, f x ^ p) s :=
λ x hx, (hf x hx).rpow_const (h x hx)
lemma differentiable.rpow_const (hf : differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) :
differentiable ℝ (λ x, f x ^ p) :=
λ x, (hf x).rpow_const (h x)
lemma has_fderiv_within_at.const_rpow (hf : has_fderiv_within_at f f' s x) (hc : 0 < c) :
has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x :=
(has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_within_at x hf
lemma has_fderiv_at.const_rpow (hf : has_fderiv_at f f' x) (hc : 0 < c) :
has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x :=
(has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_at x hf
lemma has_strict_fderiv_at.const_rpow (hf : has_strict_fderiv_at f f' x) (hc : 0 < c) :
has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x :=
(has_strict_deriv_at_const_rpow hc (f x)).comp_has_strict_fderiv_at x hf
lemma cont_diff_within_at.rpow (hf : cont_diff_within_at ℝ n f s x)
(hg : cont_diff_within_at ℝ n g s x) (h : f x ≠ 0) :
cont_diff_within_at ℝ n (λ x, f x ^ g x) s x :=
(cont_diff_at_rpow_of_ne (f x, g x) h).comp_cont_diff_within_at x (hf.prod hg)
lemma cont_diff_at.rpow (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x)
(h : f x ≠ 0) :
cont_diff_at ℝ n (λ x, f x ^ g x) x :=
(cont_diff_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg)
lemma cont_diff_on.rpow (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s)
(h : ∀ x ∈ s, f x ≠ 0) :
cont_diff_on ℝ n (λ x, f x ^ g x) s :=
λ x hx, (hf x hx).rpow (hg x hx) (h x hx)
lemma cont_diff.rpow (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g)
(h : ∀ x, f x ≠ 0) :
cont_diff ℝ n (λ x, f x ^ g x) :=
cont_diff_iff_cont_diff_at.mpr $
λ x, hf.cont_diff_at.rpow hg.cont_diff_at (h x)
lemma cont_diff_within_at.rpow_const_of_ne (hf : cont_diff_within_at ℝ n f s x)
(h : f x ≠ 0) :
cont_diff_within_at ℝ n (λ x, f x ^ p) s x :=
hf.rpow cont_diff_within_at_const h
lemma cont_diff_at.rpow_const_of_ne (hf : cont_diff_at ℝ n f x) (h : f x ≠ 0) :
cont_diff_at ℝ n (λ x, f x ^ p) x :=
hf.rpow cont_diff_at_const h
lemma cont_diff_on.rpow_const_of_ne (hf : cont_diff_on ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) :
cont_diff_on ℝ n (λ x, f x ^ p) s :=
λ x hx, (hf x hx).rpow_const_of_ne (h x hx)
lemma cont_diff.rpow_const_of_ne (hf : cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) :
cont_diff ℝ n (λ x, f x ^ p) :=
hf.rpow cont_diff_const h
variable {m : ℕ}
lemma cont_diff_within_at.rpow_const_of_le (hf : cont_diff_within_at ℝ m f s x)
(h : ↑m ≤ p) :
cont_diff_within_at ℝ m (λ x, f x ^ p) s x :=
(cont_diff_at_rpow_const_of_le h).comp_cont_diff_within_at x hf
lemma cont_diff_at.rpow_const_of_le (hf : cont_diff_at ℝ m f x) (h : ↑m ≤ p) :
cont_diff_at ℝ m (λ x, f x ^ p) x :=
by { rw ← cont_diff_within_at_univ at *, exact hf.rpow_const_of_le h }
lemma cont_diff_on.rpow_const_of_le (hf : cont_diff_on ℝ m f s) (h : ↑m ≤ p) :
cont_diff_on ℝ m (λ x, f x ^ p) s :=
λ x hx, (hf x hx).rpow_const_of_le h
lemma cont_diff.rpow_const_of_le (hf : cont_diff ℝ m f) (h : ↑m ≤ p) :
cont_diff ℝ m (λ x, f x ^ p) :=
cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow_const_of_le h
end fderiv
section deriv
variables {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : set ℝ}
lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x)
(hg : has_deriv_within_at g g' s x) (h : 0 < f x) :
has_deriv_within_at (λ x, f x ^ g x)
(f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) s x :=
begin
convert (hf.has_fderiv_within_at.rpow hg.has_fderiv_within_at h).has_deriv_within_at using 1,
dsimp, ring
end
lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h : 0 < f x) :
has_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow hg h
end
lemma has_deriv_within_at.rpow_const (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) :
has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x) ^ (p - 1)) s x :=
begin
convert (has_deriv_at_rpow_const hx).comp_has_deriv_within_at x hf using 1,
ring
end
lemma has_deriv_at.rpow_const (hf : has_deriv_at f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) :
has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow_const hx
end
lemma deriv_within_rpow_const (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, (f x) ^ p) s x = (deriv_within f s x) * p * (f x) ^ (p - 1) :=
(hf.has_deriv_within_at.rpow_const hx).deriv_within hxs
@[simp] lemma deriv_rpow_const (hf : differentiable_at ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) :
deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) :=
(hf.has_deriv_at.rpow_const hx).deriv
end deriv
end differentiability
section limits
open real filter
/-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞`. -/
lemma tendsto_one_plus_div_rpow_exp (t : ℝ) :
tendsto (λ (x : ℝ), (1 + t / x) ^ x) at_top (𝓝 (exp t)) :=
begin
apply ((real.continuous_exp.tendsto _).comp (tendsto_mul_log_one_plus_div_at_top t)).congr' _,
have h₁ : (1:ℝ)/2 < 1 := by linarith,
have h₂ : tendsto (λ x : ℝ, 1 + t / x) at_top (𝓝 1) :=
by simpa using (tendsto_inv_at_top_zero.const_mul t).const_add 1,
refine (eventually_ge_of_tendsto_gt h₁ h₂).mono (λ x hx, _),
have hx' : 0 < 1 + t / x := by linarith,
simp [mul_comm x, exp_mul, exp_log hx'],
end
/-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞` for naturals `x`. -/
lemma tendsto_one_plus_div_pow_exp (t : ℝ) :
tendsto (λ (x : ℕ), (1 + t / (x:ℝ)) ^ x) at_top (𝓝 (real.exp t)) :=
((tendsto_one_plus_div_rpow_exp t).comp tendsto_coe_nat_at_top_at_top).congr (by simp)
end limits
|
c44a4839fa47493e369aa0a81ea200094c36b56e | d1bbf1801b3dcb214451d48214589f511061da63 | /src/data/real/ennreal.lean | 944e969fe1e51a4d43ed16929f4a80d8bbff4ed7 | [
"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 | 55,661 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Yury Kudryashov
-/
import data.real.nnreal
import data.set.intervals
/-!
# Extended non-negative reals
We define `ennreal := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the
interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the
extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and
a linear order on `ennreal` and prove basic properties of these operations, order, and conversions
to/from `ℝ`, `ℝ≥0`, and `ℕ`.
## Main definitions
* `ennreal`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is
equipped with the following structures:
- coercion from `ℝ≥0` defined in the natural way;
- the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`;
- `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`;
- `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a *
∞ = ∞ * a = ∞` for `a ≠ 0`;
- `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have
`↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only
subtraction;
- `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for
`p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`.
- `a / b` is defined as `a * b⁻¹`.
The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn
`ennreal` into a canonically ordered commutative semiring of characteristic zero.
* Coercions to/from other types:
- coercion `ℝ≥0 → ennreal` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that
expects `a : ennreal`, and Lean will apply `coe` automatically;
- `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`;
- `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`;
- `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩`
- `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ennreal // a ≠ 0}` and `ℝ≥0`.
## Implementation notes
We define a `can_lift ennreal ℝ≥0` instance, so one of the ways to prove theorems about an `ennreal`
number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha`
in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the
context, or if we have `(f : α → ennreal) (hf : ∀ x, f x ≠ ∞)`.
## Notations
* `ℝ≥0`: type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`;
* `∞`: a localized notation in `ennreal` for `⊤ : ennreal`.
-/
noncomputable theory
open classical set
open_locale classical big_operators nnreal
variables {α : Type*} {β : Type*}
/-- The extended nonnegative real numbers. This is usually denoted [0, ∞],
and is relevant as the codomain of a measure. -/
@[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered,
derive nontrivial]
def ennreal := with_top ℝ≥0
localized "notation `∞` := (⊤ : ennreal)" in ennreal
namespace ennreal
variables {a b c d : ennreal} {r p q : ℝ≥0}
instance : inhabited ennreal := ⟨0⟩
instance : has_coe ℝ≥0 ennreal := ⟨ option.some ⟩
instance : can_lift ennreal ℝ≥0 :=
{ coe := coe,
cond := λ r, r ≠ ∞,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
@[simp] lemma none_eq_top : (none : ennreal) = ∞ := rfl
@[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ennreal) = (↑a : ennreal) := rfl
/-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/
protected def to_nnreal : ennreal → ℝ≥0
| (some r) := r
| none := 0
/-- `to_real x` returns `x` if it is real, `0` otherwise. -/
protected def to_real (a : ennreal) : real := coe (a.to_nnreal)
/-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/
protected def of_real (r : real) : ennreal := coe (nnreal.of_real r)
@[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl
@[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a
| (some r) h := rfl
| none h := (h rfl).elim
@[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a :=
by simp [ennreal.to_real, ennreal.of_real, h]
@[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r :=
by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h]
lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl
lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a
| (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _
| none := le_top
lemma coe_nnreal_eq (r : ℝ≥0) : (r : ennreal) = ennreal.of_real r :=
by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h }
lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) :
ennreal.of_real x = @coe ℝ≥0 ennreal _ (⟨x, h⟩ : ℝ≥0) :=
by { rw [coe_nnreal_eq], refl }
@[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm
@[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ennreal) := rfl
@[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ennreal) := rfl
@[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real]
@[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl
@[simp] lemma top_to_real : ∞.to_real = 0 := rfl
@[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl
@[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl
@[simp] lemma coe_to_real (r : ℝ≥0) : (r : ennreal).to_real = r := rfl
@[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl
@[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl
@[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 :=
by simp [ennreal.of_real]; refl
@[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) :=
by simp [ennreal.of_real]
lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a :=
if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha)
lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ :=
⟨assume h, ⟨assume r, h _, h _⟩,
assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩
lemma forall_ne_top {p : ennreal → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r :=
option.ball_ne_none
lemma exists_ne_top {p : ennreal → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r :=
option.bex_ne_none
lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ :=
⟨begin
cases x,
{ simp [none_eq_top] },
{ have A : some (0:ℝ≥0) = (0:ennreal) := rfl,
simp [ennreal.to_nnreal, A] {contextual := tt} }
end,
by intro h; cases h; simp [h]⟩
lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ :=
by simp [ennreal.to_real, to_nnreal_eq_zero_iff]
@[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top
@[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe
@[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real]
@[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top
@[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real]
@[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top
@[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe
@[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top
@[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe
@[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe
@[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe
@[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe
lemma coe_mono : monotone (coe : ℝ≥0 → ennreal) := λ _ _, coe_le_coe.2
@[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe
@[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe
@[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe
@[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe
@[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe
@[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe
@[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add
@[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul
@[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add
@[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1]
lemma coe_two : ((2:ℝ≥0) : ennreal) = 2 := by norm_cast
protected lemma zero_lt_one : 0 < (1 : ennreal) :=
canonically_ordered_semiring.zero_lt_one
@[simp] lemma one_lt_two : (1 : ennreal) < 2 :=
coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _)
@[simp] lemma zero_lt_two : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two
lemma two_ne_zero : (2:ennreal) ≠ 0 := (ne_of_lt zero_lt_two).symm
lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top
/-- The set of `ennreal` numbers that are not equal to `∞` is equivalent to `ℝ≥0`. -/
def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 :=
{ to_fun := λ x, ennreal.to_nnreal x,
inv_fun := λ x, ⟨x, coe_ne_top⟩,
left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx,
right_inv := λ x, to_nnreal_coe }
lemma cinfi_ne_top [has_Inf α] (f : ennreal → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x :=
eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl
lemma infi_ne_top [complete_lattice α] (f : ennreal → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x :=
by rw [infi_subtype', cinfi_ne_top]
lemma csupr_ne_top [has_Sup α] (f : ennreal → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x :=
@cinfi_ne_top (order_dual α) _ _
lemma supr_ne_top [complete_lattice α] (f : ennreal → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x :=
@infi_ne_top (order_dual α) _ _
lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} :
(⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ :=
le_antisymm
(le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _))
(le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩)
lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} :
(⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ :=
@infi_ennreal (order_dual α) _ _
@[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top
@[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add
/-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/
def of_nnreal_hom : ℝ≥0 →+* ennreal :=
⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩
@[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl
@[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ennreal) = s.indicator (λ x, f x) a :=
(of_nnreal_hom : ℝ≥0 →+ ennreal).map_indicator _ _ _
@[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n :=
of_nnreal_hom.map_pow r n
@[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top
@[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top
lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) :
(r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal :=
begin
rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal];
apply @ne_top_of_lt ennreal _ _ ∞,
exact h₂,
exact h₁,
exact add_lt_top.2 ⟨h₁, h₂⟩
end
/- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot
(contrary to erw). This is solved with the next lemmas -/
protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top
protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot
lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not]
lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ :=
by simpa only [lt_top_iff_ne_top] using add_lt_top
lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) :=
begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end
lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) :=
begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end
@[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top
lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ :=
nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top])
_ (nat.succ_le_of_lt h)
lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) :=
with_top.mul_eq_top_iff
lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ :=
with_top.mul_lt_top
lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ :=
by simpa only [lt_top_iff_ne_top] using mul_lt_top
lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ :=
by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 }
lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ :=
ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha
lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ :=
by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb }
lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ :=
lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha
lemma mul_lt_top_iff {a b : ennreal} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 :=
begin
split,
{ intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha,
exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ },
{ rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] }
end
@[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b :=
by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib]
lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞
| 0 := by simp
| (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left
lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ :=
mt (pow_eq_top n) h
lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ :=
by simpa only [lt_top_iff_ne_top] using pow_ne_top
@[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} :
↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) :=
of_nnreal_hom.map_sum f s
@[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} :
↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) :=
of_nnreal_hom.map_prod f s
section order
@[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl
@[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r
@[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r
lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe
@[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe
@[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe
@[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe
@[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe
@[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ennreal) = n := with_top.coe_nat n
@[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real]
@[simp] lemma nat_ne_top (n : ℕ) : (n : ennreal) ≠ ∞ := with_top.nat_ne_top n
@[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n
@[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top
lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff
lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff
lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe
@[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} :
↑(s.sup f) = s.sup (λ x, (f x : ennreal)) :=
finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl
lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
begin
cases a,
{ cases m,
{ rw eq_bot_iff.mpr h,
exact le_refl _ },
{ rw [none_eq_top, top_pow (nat.succ_pos m)],
exact le_top } },
{ rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe],
exact pow_le_pow (by simpa using ha) h }
end
@[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 :=
by simp only [nonpos_iff_eq_zero.symm, max_le_iff]
@[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a)
@[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a)
-- TODO: why this is not a `rfl`? There is some hidden diamond here.
@[simp] lemma sup_eq_max : a ⊔ b = max a b :=
eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm
protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n :=
canonically_ordered_semiring.pow_pos
protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 :=
by simpa only [pos_iff_ne_zero] using ennreal.pow_pos
@[simp] lemma not_lt_zero : ¬ a < 0 := by simp
lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) :=
with_top.add_lt_add_iff_left
lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) :=
with_top.add_lt_add_iff_right
lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b :=
by rwa [← add_lt_add_iff_left ha, add_zero] at hb
lemma le_of_forall_pos_le_add : ∀{a b : ennreal}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b
| a none h := le_top
| none (some a) h :=
have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top,
by rw [← coe_add] at this; exact (not_top_le_coe this).elim
| (some a) (some b) h :=
by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff]
at *; exact nnreal.le_of_forall_pos_le_add h
lemma lt_iff_exists_rat_btwn :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) :=
⟨λ h,
begin
rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩,
rcases exists_between h with ⟨c, pc, cb⟩,
rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩,
rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩,
exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩
end,
λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩
lemma lt_iff_exists_real_btwn :
a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) :=
⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in
⟨q, rat.cast_nonneg.2 q0, aq, qb⟩,
λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩
lemma lt_iff_exists_nnreal_btwn :
a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ennreal) < b) :=
with_top.lt_iff_exists_coe_btwn
lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) :=
begin
refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩,
cases a, { simpa using hab },
rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩,
let d : ℝ≥0 := ⟨c, c_nonneg⟩,
have ad : a < d,
{ rw of_real_eq_coe_nnreal c_nonneg at ac,
exact coe_lt_coe.1 ac },
refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩,
rw [some_eq_coe, ← coe_add],
convert cb,
have : nnreal.of_real c = d,
by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl },
rw [add_comm, this],
exact nnreal.sub_add_cancel_of_le (le_of_lt ad)
end
lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe
lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe
@[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n :=
ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt
lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top
lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2
@[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n :=
coe_nat_mono.le_iff_le
instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩
protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ∞) : ∃n:ℕ, r < n :=
begin
lift r to ℝ≥0 using h,
rcases exists_nat_gt r with ⟨n, hn⟩,
exact ⟨n, coe_lt_coe_nat.2 hn⟩,
end
lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d :=
begin
lift a to ℝ≥0 using ne_top_of_lt ac,
lift b to ℝ≥0 using ne_top_of_lt bd,
cases c, { simp }, cases d, { simp },
simp only [← coe_add, some_eq_coe, coe_lt_coe] at *,
exact add_lt_add ac bd
end
@[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ennreal) = min r p :=
coe_mono.map_min
@[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ennreal) = max r p :=
coe_mono.map_max
lemma le_of_top_imp_top_of_to_nnreal_le {a b : ennreal} (h : a = ⊤ → b = ⊤)
(h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) :
a ≤ b :=
begin
by_cases ha : a = ⊤,
{ rw h ha,
exact le_top, },
by_cases hb : b = ⊤,
{ rw hb,
exact le_top, },
rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe],
exact h_nnreal ha hb,
end
end order
section complete_lattice
lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup
lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf
@[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s :=
assume x hx, le_top
lemma coe_mem_upper_bounds {s : set ℝ≥0} :
↑r ∈ upper_bounds ((coe : ℝ≥0 → ennreal) '' s) ↔ r ∈ upper_bounds s :=
by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt}
end complete_lattice
section mul
@[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d :=
canonically_ordered_semiring.mul_le_mul
@[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d :=
begin
rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩,
lift a to ℝ≥0 using ne_top_of_lt aa',
rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩,
lift b to ℝ≥0 using ne_top_of_lt bb',
norm_cast at *,
calc ↑(a * b) < ↑(a' * b') :
coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa'))
... = ↑a' * ↑b' : coe_mul
... ≤ c * d : mul_le_mul a'c.le b'd.le
end
lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a)
lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a)
lemma max_mul : max a b * c = max (a * c) (b * c) :=
mul_right_mono.map_max
lemma mul_max : a * max b c = max (a * b) (a * c) :=
mul_left_mono.map_max
lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm,
nnreal.mul_eq_mul_left] {contextual := tt},
end
lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left
lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt},
assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h)
end
lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left
lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) :=
λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le]
lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left
end mul
section sub
instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩
@[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r :=
le_antisymm
(le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $
by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb)
(Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r,
by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add])
@[simp] lemma top_sub_coe : ∞ - ↑r = ∞ :=
top_unique $ le_Inf $ by simp [add_eq_top]
@[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 :=
le_antisymm (Inf_le $ le_add_left h) (zero_le _)
@[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _
@[simp] lemma zero_sub : 0 - a = 0 :=
le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _)
@[simp] lemma sub_infty : a - ∞ = 0 :=
le_antisymm (Inf_le $ by simp) (zero_le _)
lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d :=
Inf_le_Inf $ assume e (h : b ≤ e + d),
calc a ≤ b : h₁
... ≤ e + d : h
... ≤ e + c : add_le_add (le_refl _) h₂
@[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a
| a none := by simp [none_eq_top]
| none (some b) := by simp [none_eq_top, some_eq_coe]
| (some a) (some b) :=
by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel]
@[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b :=
by rw [add_comm, add_sub_self h]
lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c :=
⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩
lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c :=
by rw [add_comm, add_comm c, add_right_inj h]
@[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a :=
begin
simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt},
rintros r p x rfl h,
rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h]
end
@[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a :=
by rwa [add_comm, sub_add_cancel_of_le]
lemma sub_add_self_eq_max : (a - b) + b = max a b :=
match le_total a b with
| or.inl h := by simp [h, max_eq_right]
| or.inr h := by simp [h, max_eq_left]
end
lemma le_sub_add_self : a ≤ (a - b) + b :=
by { rw sub_add_self_eq_max, exact le_max_left a b }
@[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b :=
iff.intro
(assume h : a - b ≤ c,
calc a ≤ (a - b) + b : le_sub_add_self
... ≤ c + b : add_le_add_right h _)
(assume h : a ≤ c + b, Inf_le h)
protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
add_comm c b ▸ ennreal.sub_le_iff_le_add
lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a :=
λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb)
protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b :=
ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h }
protected lemma sub_lt_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a :=
match a, b with
| none, _ := by { have := none_eq_top, assume h, contradiction }
| (some a), none := by {intros, simp only [none_eq_top, sub_infty, pos_iff_ne_zero], assumption}
| (some a), (some b) :=
begin
simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def],
assume h₁ h₂, apply nnreal.sub_lt_self, exact pos_iff_ne_zero.2 h₂
end
end
@[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b :=
by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0
@[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a :=
by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le]
using not_iff_not.2 (@sub_eq_zero_iff_le a b)
lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b :=
begin
cases a, { simp },
cases c, { simp },
cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] },
simp only [some_eq_coe],
rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt],
end
lemma sub_le_self (a b : ennreal) : a - b ≤ a :=
ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a)
@[simp] lemma sub_zero : a - 0 = a :=
eq.trans (add_zero (a - 0)).symm $ by simp
/-- A version of triangle inequality for difference as a "distance". -/
lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) :=
ennreal.sub_le_iff_le_add.2 $
calc a ≤ a - b + b : le_sub_add_self
... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _
... = a - b + (b - c) + c : (add_assoc _ _ _).symm
lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b :=
by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h),
sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2]
lemma sub_right_inj {a b c : ennreal} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) :
a - b = a - c ↔ b = c :=
iff.intro
begin
assume h, have : a - (a - b) = a - (a - c), rw h,
rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this
end
(λ h, by rw h)
lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c :=
begin
cases le_or_lt a b with hab hab,
{ simp [hab, mul_right_mono hab] },
symmetry,
cases eq_or_lt_of_le (zero_le b) with hb hb,
{ subst b, simp },
apply sub_eq_of_add_eq,
{ exact mul_ne_top (ne_top_of_lt hab) (h hb hab) },
rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)]
end
lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) :
a * (b - c) = a * b - a * c :=
by { simp only [mul_comm a], exact sub_mul h }
lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c :=
begin
-- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a`
by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞,
{ rw [sub_mul h],
exact le_refl _ },
{ push_neg at h,
rcases h with ⟨hb, hba, hc⟩,
subst c,
simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self,
zero_le] }
end
end sub
section sum
open finset
/-- A product of finite numbers is still finite -/
lemma prod_lt_top {s : finset α} {f : α → ennreal} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ :=
with_top.prod_lt_top h
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top {s : finset α} {f : α → ennreal} :
(∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ :=
with_top.sum_lt_top
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} :
∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) :=
with_top.sum_lt_top_iff
/-- A sum of numbers is infinite iff one of them is infinite -/
lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} :
(∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) :=
with_top.sum_eq_top_iff
/-- seeing `ennreal` as `ℝ≥0` does not change their sum, unless one of the `ennreal` is
infinity -/
lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) :
ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) :=
begin
rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr],
{ refl },
{ intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm },
{ exact (sum_lt_top hf).ne }
end
/-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/
lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) :
ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) :=
by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl }
end sum
section interval
variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal}
protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) :=
ext $ assume a, iff.intro
(assume ⟨_, hx⟩, hx)
(assume hx, ⟨zero_le _, hx⟩)
lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) :=
assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0
lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y :=
assume x0, by simp [x0]
lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) :=
assume xt x0 ε0 ε0',
⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩
end interval
section bit
@[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b :=
⟨λh, begin
rcases (lt_trichotomy a b) with h₁| h₂| h₃,
{ exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) },
{ exact h₂ },
{ exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) }
end,
λh, congr_arg _ h⟩
@[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 :=
by simpa only [bit0_zero] using @bit0_inj a 0
@[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ :=
by rw [bit0, add_eq_top, or_self]
@[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b :=
⟨λh, begin
unfold bit1 at h,
rwa [add_left_inj, bit0_inj] at h,
simp [lt_top_iff_ne_top]
end,
λh, congr_arg _ h⟩
@[simp] lemma bit1_ne_zero : bit1 a ≠ 0 :=
by unfold bit1; simp
@[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 :=
by simpa only [bit1_zero] using @bit1_inj a 0
@[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ :=
by unfold bit1; rw add_eq_top; simp
end bit
section inv
instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩
instance : div_inv_monoid ennreal :=
{ inv := has_inv.inv,
.. (infer_instance : monoid ennreal) }
@[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ :=
show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl
@[simp] lemma inv_top : ∞⁻¹ = 0 :=
bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul]
@[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ :=
le_antisymm
(le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $
by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb)
(Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1)
lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ :=
if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top]
else by simp only [coe_inv hr, le_refl]
@[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ennreal) = 2⁻¹ :=
by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two]
@[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r :=
by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr]
@[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 :=
by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one
@[simp] lemma div_one {a : ennreal} : a / 1 = a :=
by rw [div_eq_mul_inv, inv_one, mul_one]
protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n :=
begin
by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe,
zero_pow, top_pow, nat.zero_lt_succ] at *,
rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow', coe_pow]
end
@[simp] lemma inv_inv : (a⁻¹)⁻¹ = a :=
by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe,
-coe_inv, (coe_inv _).symm] at *
lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) :=
λ a, ennreal.inv_inv
lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) :=
ennreal.inv_involutive.bijective
@[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff
@[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 :=
inv_zero ▸ inv_eq_inv
lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp
@[simp] lemma inv_lt_top {x : ennreal} : x⁻¹ < ∞ ↔ 0 < x :=
by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] }
lemma div_lt_top {x y : ennreal} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ :=
mul_lt_top h1 (inv_lt_top.mpr h2)
@[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ :=
inv_top ▸ inv_eq_inv
lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp
@[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ :=
pos_iff_ne_zero.trans inv_ne_zero
@[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a :=
begin
cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top],
{ simp only [lt_irrefl] },
{ exact inv_pos.trans lt_top_iff_ne_top.symm },
{ simp only [not_lt_zero, not_top_lt] },
{ cases eq_or_lt_of_le (zero_le a) with ha ha;
cases eq_or_lt_of_le (zero_le b) with hb hb,
{ subst a, subst b, simp },
{ subst a, simp },
{ subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] },
{ rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe],
simp only [nnreal.coe_lt_coe.symm] at *,
exact inv_lt_inv ha hb } }
end
lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a :=
by simpa only [inv_inv] using @inv_lt_inv a b⁻¹
lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ :=
by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b
@[simp, priority 1100] -- higher than le_inv_iff_mul_le
lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm]
lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by simpa only [inv_inv] using @inv_le_inv a b⁻¹
lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by simpa only [inv_inv] using @inv_le_inv a⁻¹ b
@[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a :=
inv_lt_iff_inv_lt.trans $ by rw [inv_one]
@[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero]
@[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul]
lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ :=
by { lift a to ℝ≥0 using h, exact top_div_coe }
lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ :=
top_div_of_ne_top h.ne
lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ :=
by by_cases a = ∞; simp [top_div_of_ne_top, *]
@[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹
lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) :=
by simp [div_eq_mul_inv, ennreal.mul_eq_top]
lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) :
a ≤ c / b ↔ a * b ≤ c :=
begin
cases b,
{ simp at ht,
split,
{ assume ha, simp at ha, simp [ha] },
{ contrapose,
assume ha,
simp at ha,
have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha],
simp [this, ht] } },
by_cases hb : b ≠ 0,
{ have : (b : ennreal) ≠ 0, by simp [hb],
rw [← ennreal.mul_le_mul_left this coe_ne_top],
suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c,
{ simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] },
rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] },
{ simp at hb,
simp [hb] at h0,
have : c / 0 = ∞, by simp [div_eq_top, h0],
simp [hb, this] }
end
lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b :=
begin
suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv],
refine (le_div_iff_mul_le _ _).symm; simpa
end
lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b :=
begin
by_cases h0 : c = 0,
{ have : a = 0, by simpa [h0] using h, simp [*] },
by_cases hinf : c = ∞, by simp [hinf],
exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h
end
protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) :
c / b < a ↔ c < a * b :=
lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht
lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b :=
by { contrapose! h, exact ennreal.div_le_of_le_mul h }
lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) :=
begin
cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt},
by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le]
end
@[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
begin
cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] },
by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le],
suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] },
exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top)
end
lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 :=
begin
lift a to ℝ≥0 using ht,
norm_cast at *,
exact mul_inv_cancel h0
end
lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 :=
mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht
lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) :=
by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul]
lemma le_of_forall_nnreal_lt {x y : ennreal} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y :=
begin
refine le_of_forall_ge_of_dense (λ r hr, _),
lift r to ℝ≥0 using ne_top_of_lt hr,
exact h r hr
end
lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 :=
mul_inv_cancel h0 hI
lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b :=
by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one]
lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b :=
by rw [mul_comm, mul_div_cancel h0 hI]
lemma mul_div_le : a * (b / a) ≤ b :=
begin
by_cases h0 : a = 0, { simp [h0] },
by_cases hI : a = ∞, { simp [hI] },
rw mul_div_cancel' h0 hI, exact le_refl b
end
lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 :=
by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top]
lemma add_halves (a : ennreal) : a / 2 + a / 2 = a :=
by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one]
@[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ :=
by simp [div_eq_mul_inv]
@[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ :=
by simp [pos_iff_ne_zero, not_or_distrib]
lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 :=
by simp [ne_of_gt h]
lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two
lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a :=
begin
lift a to ℝ≥0 using ht,
have h : (2 : ennreal) = ((2 : ℝ≥0) : ennreal), from rfl,
have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero',
rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div`
norm_cast at hz,
exact nnreal.half_lt_self hz
end
lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 :=
begin
lift a to ℝ≥0 using h,
exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a)
end
lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ :=
by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top
lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) :
∃n:ℕ, (n:ennreal)⁻¹ < a :=
@inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)]
lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) :
∃ n > 0, b < (n : ℕ) * a :=
begin
have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha),
refine (ennreal.exists_nat_gt this).imp (λ n hn, _),
have : 0 < (n : ennreal), from (zero_le _).trans_lt hn,
refine ⟨coe_nat_lt_coe_nat.1 this, _⟩,
rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)]
end
lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) :
∃ n : ℕ, b < n * a :=
(exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd
lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) :
∃ n > 0, ((n : ℕ) : ennreal)⁻¹ * a < b :=
begin
rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩,
have : (n : ennreal) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne',
use [n, npos],
rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top,
mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)]
end
lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) :
∃ n > 0, ↑(n : ℝ≥0) * a < b :=
begin
rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩,
use (n : ℝ≥0)⁻¹,
simp [*, npos.ne', zero_lt_one]
end
end inv
section real
lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
refl
end
lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real :=
if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg]
else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg]
else le_of_eq (to_real_add ha hb)
lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) :
ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q :=
by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add,
coe_eq_coe, nnreal.of_real_add hp hq]
lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q :=
coe_le_coe.2 nnreal.of_real_add_le
@[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
norm_cast
end
@[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
norm_cast
end
lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) :
ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) :=
(le_total a b).elim
(λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right])
(λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left])
lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) :=
begin
cases a,
{ simp [none_eq_top] },
{ simp [some_eq_coe] }
end
lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):=
(nnreal.coe_pos).trans to_nnreal_pos_iff
lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q :=
by simp [ennreal.of_real, nnreal.of_real_le_of_real h]
lemma of_real_le_of_le_to_real {a : ℝ} {b : ennreal} (h : a ≤ ennreal.to_real b) :
ennreal.of_real a ≤ b :=
(of_real_le_of_real h).trans of_real_to_real_le
@[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) :
ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q :=
by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h]
@[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) :
ennreal.of_real p < ennreal.of_real q ↔ p < q :=
by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h]
lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) :
ennreal.of_real p < ennreal.of_real q ↔ p < q :=
by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp]
@[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p :=
by simp [ennreal.of_real]
@[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 :=
by simp [ennreal.of_real]
lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ∞) :
ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b :=
begin
lift b to ℝ≥0 using hb,
simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe
end
lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ∞) :
ennreal.of_real a < b ↔ a < ennreal.to_real b :=
begin
lift b to ℝ≥0 using hb,
simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha
end
lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) :
a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b :=
begin
lift a to ℝ≥0 using ha,
simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb
end
lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) :
ennreal.to_real a ≤ b :=
have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h,
(le_of_real_iff_to_real_le ha hb).1 h
lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ∞) :
a < ennreal.of_real b ↔ ennreal.to_real a < b :=
begin
lift a to ℝ≥0 using ha,
simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt
end
lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) :
ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) :=
by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp }
lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) :
(ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ :=
by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe,
nnreal.of_real_inv.symm]
lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) :
ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y :=
by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy,
mul_comm]
lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) :
ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a :=
begin
cases a,
{ simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top],
by_cases h' : c ≤ 0,
{ rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } },
{ rw [if_neg], refl, rw [of_real_eq_zero], assumption } },
{ simp only [ennreal.to_real, ennreal.to_nnreal],
simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul],
congr, apply nnreal.coe_of_real, exact h }
end
@[simp] lemma to_nnreal_mul_top (a : ennreal) : ennreal.to_nnreal (a * ∞) = 0 :=
begin
by_cases h : a = 0,
{ rw [h, zero_mul, zero_to_nnreal] },
{ rw [mul_top, if_neg h, top_to_nnreal] }
end
@[simp] lemma to_nnreal_top_mul (a : ennreal) : ennreal.to_nnreal (∞ * a) = 0 :=
by rw [mul_comm, to_nnreal_mul_top]
@[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ∞) = 0 :=
by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero]
@[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (∞ * a) = 0 :=
by { rw mul_comm, exact to_real_mul_top _ }
lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) :
ennreal.to_real a = ennreal.to_real b ↔ a = b :=
begin
lift a to ℝ≥0 using ha.ne,
lift b to ℝ≥0 using hb.ne,
simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real],
end
/-- `ennreal.to_nnreal` as a `monoid_hom`. -/
def to_nnreal_hom : ennreal →* ℝ≥0 :=
{ to_fun := ennreal.to_nnreal,
map_one' := to_nnreal_coe,
map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe,
to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] }
lemma to_nnreal_mul {a b : ennreal}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal :=
to_nnreal_hom.map_mul a b
lemma to_nnreal_pow (a : ennreal) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n :=
to_nnreal_hom.map_pow a n
lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} :
(∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal :=
to_nnreal_hom.map_prod _ _
/-- `ennreal.to_real` as a `monoid_hom`. -/
def to_real_hom : ennreal →* ℝ :=
(nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom
lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real :=
to_real_hom.map_mul a b
lemma to_real_pow (a : ennreal) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n :=
to_real_hom.map_pow a n
lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} :
(∏ i in s, f i).to_real = ∏ i in s, (f i).to_real :=
to_real_hom.map_prod _ _
end real
section infi
variables {ι : Sort*} {f g : ι → ennreal}
lemma infi_add : infi f + a = ⨅i, f i + a :=
le_antisymm
(le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _)
(ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _)
lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) :=
le_antisymm
(ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i)
(supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a))
lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) :=
begin
refine (eq_of_forall_ge_iff $ λ c, _),
rw [ennreal.sub_le_iff_le_add, add_comm, infi_add],
simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm],
end
lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a :=
by simp [Inf_eq_infi, infi_add]
lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b :=
by rw [add_comm, infi_add]; simp [add_comm]
lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) :=
suffices (⨅a, f a + g a) ≤ infi f + infi g,
from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this,
calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') :
le_infi $ assume a, le_infi $ assume a',
let ⟨k, h⟩ := h a a' in infi_le_of_le k h
... ≤ infi f + infi g :
by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _
lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι]
(h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) :
(⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a :=
finset.induction_on s (by simp) $ assume a s ha ih,
have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b,
from assume i j,
let ⟨k, hk⟩ := h (insert a s) i j in
⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $
assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩,
by simp [ha, ih.symm, infi_add_infi this]
lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) :
infi f * x = ⨅i, f i * x :=
begin
by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const],
refine le_antisymm
(le_infi $ λ i, mul_right_mono $ infi_le _ _)
((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $
λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _)
end
lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) :
x * infi f = ⨅i, x * f i :=
by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption }
/-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/
end infi
section supr
lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ∞ :=
(supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb)
end supr
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds in `ennreal` with the additional assumption that `a < ∞`. -/
lemma le_of_add_le_add_left {a b c : ennreal} : a < ∞ →
a + b ≤ a + c → b ≤ c :=
by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe]
end ennreal
|
b5fcde4b2c51b849a5911e398f4752007eb586ff | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/monoidal/natural_transformation.lean | d4a4776b6313b33b5a829574143413a0cd4edb08 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,430 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.monoidal.functor
import category_theory.full_subcategory
/-!
# Monoidal natural transformations
Natural transformations between (lax) monoidal functors must satisfy
an additional compatibility relation with the tensorators:
`F.μ X Y ≫ app (X ⊗ Y) = (app X ⊗ app Y) ≫ G.μ X Y`.
(Lax) monoidal functors between a fixed pair of monoidal categories
themselves form a category.
-/
open category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃
open category_theory.category
open category_theory.functor
namespace category_theory
open monoidal_category
variables {C : Type u₁} [category.{v₁} C] [monoidal_category.{v₁} C]
{D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D]
/--
A monoidal natural transformation is a natural transformation between (lax) monoidal functors
additionally satisfying:
`F.μ X Y ≫ app (X ⊗ Y) = (app X ⊗ app Y) ≫ G.μ X Y`
-/
@[ext]
structure monoidal_nat_trans (F G : lax_monoidal_functor C D)
extends nat_trans F.to_functor G.to_functor :=
(unit' : F.ε ≫ app (𝟙_ C) = G.ε . obviously)
(tensor' : ∀ X Y, F.μ _ _ ≫ app (X ⊗ Y) = (app X ⊗ app Y) ≫ G.μ _ _ . obviously)
restate_axiom monoidal_nat_trans.tensor'
attribute [simp, reassoc] monoidal_nat_trans.tensor
restate_axiom monoidal_nat_trans.unit'
attribute [simp, reassoc] monoidal_nat_trans.unit
namespace monoidal_nat_trans
/--
The identity monoidal natural transformation.
-/
@[simps]
def id (F : lax_monoidal_functor C D) : monoidal_nat_trans F F :=
{ ..(𝟙 F.to_functor) }
instance (F : lax_monoidal_functor C D) : inhabited (monoidal_nat_trans F F) := ⟨id F⟩
/--
Vertical composition of monoidal natural transformations.
-/
@[simps]
def vcomp {F G H : lax_monoidal_functor C D}
(α : monoidal_nat_trans F G) (β : monoidal_nat_trans G H) : monoidal_nat_trans F H :=
{ ..(nat_trans.vcomp α.to_nat_trans β.to_nat_trans) }
instance category_lax_monoidal_functor : category (lax_monoidal_functor C D) :=
{ hom := monoidal_nat_trans,
id := id,
comp := λ F G H α β, vcomp α β, }
@[simp] lemma comp_to_nat_trans_lax {F G H : lax_monoidal_functor C D} {α : F ⟶ G} {β : G ⟶ H} :
(α ≫ β).to_nat_trans =
@category_struct.comp (C ⥤ D) _ _ _ _ (α.to_nat_trans) (β.to_nat_trans) := rfl
instance category_monoidal_functor : category (monoidal_functor C D) :=
induced_category.category monoidal_functor.to_lax_monoidal_functor
@[simp] lemma comp_to_nat_trans {F G H : monoidal_functor C D} {α : F ⟶ G} {β : G ⟶ H} :
(α ≫ β).to_nat_trans =
@category_struct.comp (C ⥤ D) _ _ _ _ (α.to_nat_trans) (β.to_nat_trans) := rfl
variables {E : Type u₃} [category.{v₃} E] [monoidal_category.{v₃} E]
/--
Horizontal composition of monoidal natural transformations.
-/
@[simps]
def hcomp {F G : lax_monoidal_functor C D} {H K : lax_monoidal_functor D E}
(α : monoidal_nat_trans F G) (β : monoidal_nat_trans H K) :
monoidal_nat_trans (F ⊗⋙ H) (G ⊗⋙ K) :=
{ unit' :=
begin
dsimp, simp,
conv_lhs { rw [←K.to_functor.map_comp, α.unit], },
end,
tensor' := λ X Y,
begin
dsimp, simp,
conv_lhs { rw [←K.to_functor.map_comp, α.tensor, K.to_functor.map_comp], },
end,
..(nat_trans.hcomp α.to_nat_trans β.to_nat_trans) }
section
local attribute [simp] nat_trans.naturality monoidal_nat_trans.unit monoidal_nat_trans.tensor
/-- The cartesian product of two monoidal natural transformations is monoidal. -/
@[simps]
def prod {F G : lax_monoidal_functor C D} {H K : lax_monoidal_functor C E}
(α : monoidal_nat_trans F G) (β : monoidal_nat_trans H K) :
monoidal_nat_trans (F.prod' H) (G.prod' K) :=
{ app := λ X, (α.app X, β.app X) }
end
end monoidal_nat_trans
namespace monoidal_nat_iso
variables {F G : lax_monoidal_functor C D}
/--
Construct a monoidal natural isomorphism from object level isomorphisms,
and the monoidal naturality in the forward direction.
-/
def of_components
(app : ∀ X : C, F.obj X ≅ G.obj X)
(naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f)
(unit : F.ε ≫ (app (𝟙_ C)).hom = G.ε)
(tensor : ∀ X Y, F.μ X Y ≫ (app (X ⊗ Y)).hom = ((app X).hom ⊗ (app Y).hom) ≫ G.μ X Y) :
F ≅ G :=
{ hom := { app := λ X, (app X).hom, },
inv :=
{ app := λ X, (app X).inv,
unit' := by { dsimp, rw [←unit, assoc, iso.hom_inv_id, comp_id], },
tensor' := λ X Y,
begin
dsimp,
rw [iso.comp_inv_eq, assoc, tensor, ←tensor_comp_assoc,
iso.inv_hom_id, iso.inv_hom_id, tensor_id, id_comp],
end,
..(nat_iso.of_components app @naturality).inv, }, }
@[simp] lemma of_components.hom_app
(app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (unit) (tensor) (X) :
(of_components app naturality unit tensor).hom.app X = (app X).hom := rfl
@[simp] lemma of_components.inv_app
(app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (unit) (tensor) (X) :
(of_components app naturality unit tensor).inv.app X = (app X).inv :=
by simp [of_components]
instance is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α :=
⟨(is_iso.of_iso (of_components (λ X, as_iso (α.app X))
(λ X Y f, α.to_nat_trans.naturality f) α.unit α.tensor)).1⟩
end monoidal_nat_iso
noncomputable theory
/-- The unit of a monoidal equivalence can be upgraded to a monoidal natural transformation. -/
@[simps]
def monoidal_unit (F : monoidal_functor C D) [is_equivalence F.to_functor] :
lax_monoidal_functor.id C ⟶
F.to_lax_monoidal_functor ⊗⋙ (monoidal_inverse F).to_lax_monoidal_functor :=
let e := F.to_functor.as_equivalence in
{ to_nat_trans := e.unit,
tensor' := λ X Y, begin
-- This proof is not pretty; golfing welcome!
dsimp,
simp only [adjunction.hom_equiv_unit, adjunction.hom_equiv_naturality_right,
category.id_comp, category.assoc],
simp only [←functor.map_comp],
erw [e.counit_app_functor, e.counit_app_functor, F.to_lax_monoidal_functor.μ_natural,
is_iso.inv_hom_id_assoc],
simp only [category_theory.is_equivalence.inv_fun_map],
slice_rhs 2 3 { erw iso.hom_inv_id_app, },
dsimp,
simp only [category_theory.category.id_comp],
slice_rhs 1 2 { rw [←tensor_comp, iso.hom_inv_id_app, iso.hom_inv_id_app],
dsimp, rw [tensor_id], },
simp,
end }.
instance (F : monoidal_functor C D) [is_equivalence F.to_functor] : is_iso (monoidal_unit F) :=
begin
haveI : ∀ (X : C), is_iso ((monoidal_unit F).to_nat_trans.app X),
{ intros, dsimp, apply_instance, },
exact monoidal_nat_iso.is_iso_of_is_iso_app _
end
/-- The counit of a monoidal equivalence can be upgraded to a monoidal natural transformation. -/
@[simps]
def monoidal_counit (F : monoidal_functor C D) [is_equivalence F.to_functor] :
(monoidal_inverse F).to_lax_monoidal_functor ⊗⋙ F.to_lax_monoidal_functor ⟶
lax_monoidal_functor.id D :=
let e := F.to_functor.as_equivalence in
{ to_nat_trans := e.counit,
unit' := begin
dsimp,
simp only [category.comp_id, category.assoc, functor.map_inv, functor.map_comp,
nat_iso.inv_inv_app, is_iso.inv_comp, is_equivalence.fun_inv_map, adjunction.hom_equiv_unit],
erw [e.counit_app_functor, ←e.functor.map_comp_assoc, iso.hom_inv_id_app],
dsimp, simp,
end,
tensor' := λ X Y, begin
dsimp,
simp only [adjunction.hom_equiv_unit, adjunction.hom_equiv_naturality_right, category.assoc,
category.comp_id, functor.map_comp],
simp only [is_equivalence.fun_inv_map],
erw [e.counit_app_functor],
simp only [category.assoc],
erw [←e.functor.map_comp_assoc],
simp only [category_theory.iso.inv_hom_id_app,
category_theory.iso.inv_hom_id_app_assoc],
erw [iso.hom_inv_id_app],
erw [category_theory.functor.map_id],
simp only [category.id_comp],
simp only [category_theory.iso.inv_hom_id_app,
category_theory.is_iso.hom_inv_id_assoc],
erw [iso.inv_hom_id_app],
dsimp, simp, refl,
end }
instance (F : monoidal_functor C D) [is_equivalence F.to_functor] : is_iso (monoidal_counit F) :=
begin
haveI : ∀ (X : D), is_iso ((monoidal_counit F).to_nat_trans.app X),
{ intros, dsimp, apply_instance, },
exact monoidal_nat_iso.is_iso_of_is_iso_app _
end
end category_theory
|
59039ccdad1733cbd048527126ad5e609fbb25c2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/quiver/cast.lean | 62b6fad9209ca7069537bdc4826ceb5c88793ad6 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,296 | lean | /-
Copyright (c) 2022 Antoine Labelle, Rémi Bottinelli. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Antoine Labelle, Rémi Bottinelli
-/
import combinatorics.quiver.basic
import combinatorics.quiver.path
/-!
# Rewriting arrows and paths along vertex equalities
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This files defines `hom.cast` and `path.cast` (and associated lemmas) in order to allow
rewriting arrows and paths along equalities of their endpoints.
-/
universes v v₁ v₂ u u₁ u₂
variables {U : Type*} [quiver.{u+1} U]
namespace quiver
/-!
### Rewriting arrows along equalities of vertices
-/
/-- Change the endpoints of an arrow using equalities. -/
def hom.cast {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) : u' ⟶ v' :=
eq.rec (eq.rec e hv) hu
lemma hom.cast_eq_cast {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) :
e.cast hu hv = cast (by rw [hu, hv]) e :=
by { subst_vars, refl }
@[simp] lemma hom.cast_rfl_rfl {u v : U} (e : u ⟶ v) :
e.cast rfl rfl = e := rfl
@[simp] lemma hom.cast_cast {u v u' v' u'' v'' : U} (e : u ⟶ v)
(hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') :
(e.cast hu hv).cast hu' hv' = e.cast (hu.trans hu') (hv.trans hv') :=
by { subst_vars, refl }
lemma hom.cast_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (e : u ⟶ v) :
e.cast hu hv == e :=
by { subst_vars, refl }
lemma hom.cast_eq_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v')
(e : u ⟶ v) (e' : u' ⟶ v') : e.cast hu hv = e' ↔ e == e' :=
by { rw hom.cast_eq_cast, exact cast_eq_iff_heq }
lemma hom.eq_cast_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v')
(e : u ⟶ v) (e' : u' ⟶ v') : e' = e.cast hu hv ↔ e' == e :=
by { rw [eq_comm, hom.cast_eq_iff_heq], exact ⟨heq.symm, heq.symm⟩ }
/-!
### Rewriting paths along equalities of vertices
-/
open path
/-- Change the endpoints of a path using equalities. -/
def path.cast {u v u' v' : U} (hu : u = u') (hv : v = v') (p : path u v) : path u' v' :=
eq.rec (eq.rec p hv) hu
lemma path.cast_eq_cast {u v u' v' : U} (hu : u = u') (hv : v = v') (p : path u v) :
p.cast hu hv = cast (by rw [hu, hv]) p:=
eq.drec (eq.drec (eq.refl (path.cast (eq.refl u) (eq.refl v) p)) hu) hv
@[simp] lemma path.cast_rfl_rfl {u v : U} (p : path u v) :
p.cast rfl rfl = p := rfl
@[simp] lemma path.cast_cast {u v u' v' u'' v'' : U} (p : path u v)
(hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') :
(p.cast hu hv).cast hu' hv' = p.cast (hu.trans hu') (hv.trans hv') :=
by { subst_vars, refl }
@[simp] lemma path.cast_nil {u u' : U} (hu : u = u') :
(path.nil : path u u).cast hu hu = path.nil :=
by { subst_vars, refl }
lemma path.cast_heq {u v u' v' : U} (hu : u = u') (hv : v = v') (p : path u v) :
p.cast hu hv == p :=
by { rw path.cast_eq_cast, exact cast_heq _ _ }
lemma path.cast_eq_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v')
(p : path u v) (p' : path u' v') : p.cast hu hv = p' ↔ p == p' :=
by { rw path.cast_eq_cast, exact cast_eq_iff_heq }
lemma path.eq_cast_iff_heq {u v u' v' : U} (hu : u = u') (hv : v = v')
(p : path u v) (p' : path u' v') : p' = p.cast hu hv ↔ p' == p :=
⟨λ h, ((p.cast_eq_iff_heq hu hv p').1 h.symm).symm,
λ h, ((p.cast_eq_iff_heq hu hv p').2 h.symm).symm⟩
lemma path.cast_cons {u v w u' w' : U} (p : path u v) (e : v ⟶ w) (hu : u = u') (hw : w = w') :
(p.cons e).cast hu hw = (p.cast hu rfl).cons (e.cast rfl hw) :=
by { subst_vars, refl }
lemma cast_eq_of_cons_eq_cons {u v v' w : U} {p : path u v} {p' : path u v'}
{e : v ⟶ w} {e' : v' ⟶ w} (h : p.cons e = p'.cons e') :
p.cast rfl (obj_eq_of_cons_eq_cons h) = p' :=
by { rw path.cast_eq_iff_heq, exact heq_of_cons_eq_cons h }
lemma hom_cast_eq_of_cons_eq_cons {u v v' w : U} {p : path u v} {p' : path u v'}
{e : v ⟶ w} {e' : v' ⟶ w} (h : p.cons e = p'.cons e') :
e.cast (obj_eq_of_cons_eq_cons h) rfl = e' :=
by { rw hom.cast_eq_iff_heq, exact hom_heq_of_cons_eq_cons h }
lemma eq_nil_of_length_zero {u v : U} (p : path u v) (hzero : p.length = 0) :
p.cast (eq_of_length_zero p hzero) rfl = path.nil :=
by { cases p; simpa only [nat.succ_ne_zero, length_cons] using hzero, }
end quiver
|
45c46788c1b59374d089574e9647d02ae5de6ad5 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/group_theory/perm/support.lean | 92082252d0b6cb36ed6fac40d2cc8d23e40e1b83 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,566 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky
-/
import data.finset.sort
import data.fintype.basic
import group_theory.perm.basic
/-!
# Support of a permutation
## Main definitions
In the following, `f g : equiv.perm α`.
* `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed
either by `f`, or by `g`.
Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint.
* `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`.
* `equiv.perm.support`: the elements `x : α` that are not fixed by `f`.
-/
open equiv finset
namespace equiv.perm
variables {α : Type*}
section disjoint
/-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e.,
every element is fixed either by `f`, or by `g`. -/
def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x
variables {f g h : perm α}
@[symm] lemma disjoint.symm : disjoint f g → disjoint g f :=
by simp only [disjoint, or.comm, imp_self]
lemma disjoint_comm : disjoint f g ↔ disjoint g f :=
⟨disjoint.symm, disjoint.symm⟩
lemma disjoint.mul_comm (h : disjoint f g) : f * g = g * f :=
equiv.ext $ λ x, (h x).elim
(λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg])
(λ hg, by simp [mul_apply, hf, g.injective hg]))
(λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg])
(λ hf, by simp [mul_apply, hf, hg]))
@[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl
@[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl
lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl
@[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 :=
begin
refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩,
ext x,
cases h x with hx hx;
simp [hx]
end
lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g :=
begin
intro x,
rw [inv_eq_iff_eq, eq_comm],
exact h x
end
lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ :=
h.symm.inv_left.symm
@[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g :=
begin
refine ⟨λ h, _, disjoint.inv_left⟩,
convert h.inv_left,
exact (inv_inv _).symm
end
@[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g :=
by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm]
lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) :
disjoint (f * g) h :=
λ x, by cases H1 x; cases H2 x; simp *
lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) :
disjoint f (g * h) :=
by { rw disjoint_comm, exact H1.symm.mul_left H2.symm }
lemma disjoint_prod_right (l : list (perm α))
(h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod :=
begin
induction l with g l ih,
{ exact disjoint_one_right _ },
{ rw list.prod_cons,
exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) }
end
lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint)
(hp : l₁ ~ l₂) : l₁.prod = l₂.prod :=
hp.prod_eq' $ hl.imp $ λ f g, disjoint.mul_comm
lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l)
(h2 : l.pairwise disjoint) : l.nodup :=
begin
refine list.pairwise.imp_of_mem _ h2,
rintros σ - h_mem - h_disjoint rfl,
suffices : σ = 1,
{ rw this at h_mem,
exact h1 h_mem },
exact ext (λ a, (or_self _).mp (h_disjoint a)),
end
lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℕ, (f ^ n) x = x
| 0 := rfl
| (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self]
lemma gpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℤ, (f ^ n) x = x
| (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n
| -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx]
lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x
| 0 := or.inl rfl
| (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim
(λ h, or.inr (by rw [pow_succ, mul_apply, h]))
(λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx]))
lemma gpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x
| (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n
| -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply,
← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm],
exact pow_apply_eq_of_apply_apply_eq_self hffx _ }
lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} :
(σ * τ) a = a ↔ σ a = a ∧ τ a = a :=
begin
refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩,
cases hστ a with hσ hτ,
{ exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ },
{ exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ },
end
lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) :
σ * τ = 1 ↔ σ = 1 ∧ τ = 1 :=
by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib]
lemma disjoint.gpow_disjoint_gpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) :
disjoint (σ ^ m) (τ ^ n) :=
λ x, or.imp (λ h, gpow_apply_eq_self_of_apply_eq_self h m)
(λ h, gpow_apply_eq_self_of_apply_eq_self h n) (hστ x)
lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) :
disjoint (σ ^ m) (τ ^ n) :=
hστ.gpow_disjoint_gpow m n
end disjoint
section is_swap
variable [decidable_eq α]
/-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/
def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y
lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p]
{f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap :=
let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in
⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 },
equiv.ext $ λ z, begin
rw [hxy.2, of_subtype],
simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk],
split_ifs;
rw subtype.coe_mk <|> cc,
end⟩
lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α}
(hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x :=
begin
simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
end is_swap
section support
variables [decidable_eq α] [fintype α] {f g : perm α}
/-- The `finset` of nonfixed points of a permutation. -/
def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x)
@[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x :=
by rw [support, mem_filter, and_iff_right (mem_univ x)]
lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp
@[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 :=
by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not,
equiv.perm.ext_iff, one_apply]
@[simp] lemma support_one : (1 : perm α).support = ∅ :=
by rw support_eq_empty_iff
@[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one
lemma support_congr (h : f.support = g.support)
(h' : ∀ x ∈ f.support, f x = g x) : f = g :=
begin
ext x,
by_cases hx : x ∈ f.support,
{ exact h' x hx },
{ have : x ∉ g.support := h ▸ hx,
rw [not_mem_support.mp hx, not_mem_support.mp this] }
end
lemma support_mul_le (f g : perm α) :
(f * g).support ≤ f.support ⊔ g.support :=
λ x, begin
rw [sup_eq_union, mem_union, mem_support, mem_support,
mem_support, mul_apply, ←not_and_distrib, not_imp_not],
rintro ⟨hf, hg⟩,
rw [hg, hf]
end
lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α}
(hx : x ∈ l.prod.support) :
∃ f : perm α, f ∈ l ∧ x ∈ f.support :=
begin
contrapose! hx,
simp_rw [mem_support, not_not] at hx ⊢,
induction l with f l ih generalizing hx,
{ refl },
{ rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] },
end
lemma support_pow_le (σ : perm α) (n : ℤ) :
(σ ^ n).support ≤ σ.support :=
λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (gpow_apply_eq_self_of_apply_eq_self h2 n))
@[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support :=
by simp_rw [finset.ext_iff, mem_support, not_iff_not,
(inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff]
@[simp]
lemma apply_mem_support {x : α} :
f x ∈ f.support ↔ x ∈ f.support :=
by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq]
@[simp]
lemma pow_apply_mem_support {n : ℕ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
induction n with n ih,
{ refl },
rw [pow_succ, perm.mul_apply, apply_mem_support, ih]
end
@[simp]
lemma gpow_apply_mem_support {n : ℤ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
cases n,
{ rw [int.of_nat_eq_coe, gpow_coe_nat, pow_apply_mem_support] },
{ rw [gpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] }
end
lemma disjoint_iff_disjoint_support :
disjoint f g ↔ _root_.disjoint f.support g.support :=
by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib]
lemma disjoint.disjoint_support (h : disjoint f g) :
_root_.disjoint f.support g.support :=
disjoint_iff_disjoint_support.1 h
lemma disjoint.support_mul (h : disjoint f g) :
(f * g).support = f.support ∪ g.support :=
begin
refine le_antisymm (support_mul_le _ _) (λ a, _),
rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not],
exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩)
(λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩),
end
lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) :
l.prod.support = (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.pairwise_cons] at h,
have : disjoint hd tl.prod := disjoint_prod_right _ h.left,
simp [this.support_mul, hl h.right] }
end
lemma support_prod_le (l : list (perm α)) :
l.prod.support ≤ (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.prod_cons, list.map_cons, list.foldr_cons],
refine (support_mul_le hd tl.prod).trans _,
exact sup_le_sup (le_refl _) hl }
end
lemma support_gpow_le (σ : perm α) (n : ℤ) :
(σ ^ n).support ≤ σ.support :=
by { cases n; exact support_pow_le σ _ }
@[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} :=
begin
ext z,
by_cases hx : z = x;
by_cases hy : z = y,
any_goals { simpa [hx, hy] using h.symm },
{ simp [swap_apply_of_ne_of_ne, hx, hy] }
end
lemma support_swap_iff (x y : α) :
support (swap x y) = {x, y} ↔ x ≠ y :=
begin
refine ⟨λ h H, _, support_swap⟩,
subst H,
simp only [swap_self, support_refl, insert_singleton_self_eq] at h,
have : x ∈ ∅,
{ rw h,
exact mem_singleton.mpr rfl },
simpa
end
lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) :
support (swap x y * swap y z) = {x, y, z} :=
begin
simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons,
list.mem_singleton, and_self, list.nodup_nil] at h,
push_neg at h,
apply le_antisymm,
{ convert support_mul_le _ _,
rw [support_swap h.left.left, support_swap h.right],
ext,
simp [or.comm, or.left_comm] },
{ intro,
simp only [mem_insert, mem_singleton],
rintro (rfl | rfl | rfl | _);
simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm,
h.right.symm] }
end
lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) :
f.support \ {x, y} ≤ (swap x y * f).support :=
begin
intro,
simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff,
mem_singleton],
push_neg,
rintro ha ⟨hx, hy⟩ H,
rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H,
exact ha H
end
lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) :
(swap x (f x) * f).support = f.support \ {x} :=
begin
by_cases hx : f x = x,
{ simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] },
ext z,
by_cases hzx : z = x,
{ simp [hzx] },
by_cases hzf : z = f x,
{ simp [hzf, hx, h, swap_apply_of_ne_of_ne], },
by_cases hzfx : f z = x,
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] },
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] }
end
lemma mem_support_swap_mul_imp_mem_support_ne {x y : α}
(hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x :=
begin
simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
section extend_domain
variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p]
@[simp]
lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} :
support (g.extend_domain f) = g.support.map f.as_embedding :=
begin
ext b,
simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def,
function.embedding.trans_apply, mem_support],
by_cases pb : p b,
{ rw [extend_domain_apply_subtype _ _ pb],
split,
{ rintro h,
refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩,
contrapose! h,
simp [h] },
{ rintro ⟨a, ha, hb⟩,
contrapose! ha,
obtain rfl : a = f.symm ⟨b, pb⟩,
{ rw eq_symm_apply,
exact subtype.coe_injective hb },
rw eq_symm_apply,
exact subtype.coe_injective ha } },
{ rw [extend_domain_apply_not_subtype _ _ pb],
simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true],
rintros a ha rfl,
exact pb (subtype.prop _) }
end
lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} :
(g.extend_domain f).support.card = g.support.card :=
by simp
end extend_domain
section card
@[simp]
lemma card_support_eq_zero {f : perm α} :
f.support.card = 0 ↔ f = 1 :=
by rw [finset.card_eq_zero, support_eq_empty_iff]
lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
1 < f.support.card :=
begin
simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib],
contrapose! h,
ext a,
specialize h (f a) a,
rwa [apply_eq_iff_eq, or_self, or_self] at h,
end
lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 :=
begin
by_cases h : f = 1,
{ exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one },
{ exact ne_of_gt (one_lt_card_support_of_ne_one h) },
end
@[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 :=
by rw [le_iff_lt_or_eq, nat.lt_succ_iff, nat.le_zero_iff, card_support_eq_zero,
or_iff_not_imp_right, imp_iff_right f.card_support_ne_one]
lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
2 ≤ f.support.card :=
one_lt_card_support_of_ne_one h
lemma card_support_swap_mul {f : perm α} {x : α}
(hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card :=
finset.card_lt_card
⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left,
λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩
lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 :=
show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩,
from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff]
@[simp]
lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f :=
begin
split; intro h,
{ obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h,
obtain ⟨y, rfl⟩ := card_eq_one.1 ht,
rw mem_singleton at hmem,
refine ⟨x, y, hmem, _⟩,
ext a,
have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton],
by_cases ha : f a = a,
{ have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)),
rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] },
{ have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha),
obtain rfl | rfl := ((key a).mp ha),
{ rw [or.resolve_left ha' ha, swap_apply_left] },
{ rw [or.resolve_right ha' ha, swap_apply_right] } } },
{ obtain ⟨x, y, hxy, rfl⟩ := h,
exact card_support_swap hxy }
end
lemma disjoint.card_support_mul (h : disjoint f g) :
(f * g).support.card = f.support.card + g.support.card :=
begin
rw ←finset.card_disjoint_union,
{ congr,
ext,
simp [h.support_mul] },
{ simpa using h.disjoint_support }
end
lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)}
(h : l.pairwise disjoint) :
l.prod.support.card = (l.map (finset.card ∘ support)).sum :=
begin
induction l with a t ih,
{ exact card_support_eq_zero.mpr rfl, },
{ obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h,
rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht],
exact (disjoint_prod_right _ ha).card_support_mul }
end
end card
end support
end equiv.perm
|
1f36b23840ce712bd275c9b37f61feb4fdefe33a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Data/List.lean | 6bb2c731695325ba86f36903d7860cfd6bb17524 | [
"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 | 261 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.List.Basic
import Init.Data.List.BasicAux
import Init.Data.List.Control
|
6e469de93ddf38b9806f9789fb8fcd52d43e596d | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Meta/Tactic/Simp/Types.lean | 0345ffb9ce19dcd81c92ef026e64fa5f37cea52e | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 2,487 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.AppBuilder
import Lean.Meta.Tactic.Simp.SimpLemmas
import Lean.Meta.Tactic.Simp.CongrLemmas
namespace Lean.Meta
namespace Simp
structure Result where
expr : Expr
proof? : Option Expr := none -- If none, proof is assumed to be `refl`
deriving Inhabited
abbrev Cache := ExprMap Result
structure Context where
config : Config := {}
simpLemmas : SimpLemmas := {}
congrLemmas : CongrLemmas := {}
parent? : Option Expr := none
dischargeDepth : Nat := 0
deriving Inhabited
def Context.mkDefault : MetaM Context :=
return { config := {}, simpLemmas := (← getSimpLemmas), congrLemmas := (← getCongrLemmas) }
structure State where
cache : Cache := {}
numSteps : Nat := 0
abbrev SimpM := ReaderT Context $ StateRefT State MetaM
instance : MonadBacktrack SavedState SimpM where
saveState := Meta.saveState
restoreState s := s.restore
inductive Step where
| visit : Result → Step
| done : Result → Step
deriving Inhabited
def Step.result : Step → Result
| Step.visit r => r
| Step.done r => r
structure Methods where
pre : Expr → SimpM Step := fun e => return Step.visit { expr := e }
post : Expr → SimpM Step := fun e => return Step.done { expr := e }
discharge? : Expr → SimpM (Option Expr) := fun e => return none
deriving Inhabited
/- Internal monad -/
abbrev M := ReaderT Methods SimpM
def pre (e : Expr) : M Step := do
(← read).pre e
def post (e : Expr) : M Step := do
(← read).post e
def discharge? (e : Expr) : M (Option Expr) := do
(← read).discharge? e
def getConfig : M Config :=
return (← readThe Context).config
@[inline] def withParent (parent : Expr) (f : M α) : M α :=
withTheReader Context (fun ctx => { ctx with parent? := parent }) f
def getSimpLemmas : M SimpLemmas :=
return (← readThe Context).simpLemmas
def getCongrLemmas : M CongrLemmas :=
return (← readThe Context).congrLemmas
@[inline] def withSimpLemmas (s : SimpLemmas) (x : M α) : M α := do
let cacheSaved := (← get).cache
modify fun s => { s with cache := {} }
try
withTheReader Context (fun ctx => { ctx with simpLemmas := s }) x
finally
modify fun s => { s with cache := cacheSaved }
end Simp
export Simp (SimpM)
end Lean.Meta
|
a03efaab7a1876f94b48cd2646efa59a430ad660 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/box_integral/box/basic.lean | edbc1d4c03659df8853d7c4b4785572ab706e125 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 17,896 | 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 data.set.intervals.monotone
import topology.algebra.order.monotone_convergence
import topology.metric_space.basic
/-!
# Rectangular boxes in `ℝⁿ`
In this file we define rectangular boxes in `ℝⁿ`. As usual, we represent `ℝⁿ` as the type of
functions `ι → ℝ` (usually `ι = fin n` for some `n`). When we need to interpret a box `[l, u]` as a
set, we use the product `{x | ∀ i, l i < x i ∧ x i ≤ u i}` of half-open intervals `(l i, u i]`. We
exclude `l i` because this way boxes of a partition are disjoint as sets in `ℝⁿ`.
Currently, the only use cases for these constructions are the definitions of Riemann-style integrals
(Riemann, Henstock-Kurzweil, McShane).
## Main definitions
We use the same structure `box_integral.box` both for ambient boxes and for elements of a partition.
Each box is stored as two points `lower upper : ι → ℝ` and a proof of `∀ i, lower i < upper i`. We
define instances `has_mem (ι → ℝ) (box ι)` and `has_coe_t (box ι) (set $ ι → ℝ)` so that each box is
interpreted as the set `{x | ∀ i, x i ∈ set.Ioc (I.lower i) (I.upper i)}`. This way boxes of a
partition are pairwise disjoint and their union is exactly the original box.
We require boxes to be nonempty, because this way coercion to sets is injective. The empty box can
be represented as `⊥ : with_bot (box_integral.box ι)`.
We define the following operations on boxes:
* coercion to `set (ι → ℝ)` and `has_mem (ι → ℝ) (box_integral.box ι)` as described above;
* `partial_order` and `semilattice_sup` instances such that `I ≤ J` is equivalent to
`(I : set (ι → ℝ)) ⊆ J`;
* `lattice` instances on `with_bot (box_integral.box ι)`;
* `box_integral.box.Icc`: the closed box `set.Icc I.lower I.upper`; defined as a bundled monotone
map from `box ι` to `set (ι → ℝ)`;
* `box_integral.box.face I i : box (fin n)`: a hyperface of `I : box_integral.box (fin (n + 1))`;
* `box_integral.box.distortion`: the maximal ratio of two lengths of edges of a box; defined as the
supremum of `nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`.
We also provide a convenience constructor `box_integral.box.mk' (l u : ι → ℝ) : with_bot (box ι)`
that returns the box `⟨l, u, _⟩` if it is nonempty and `⊥` otherwise.
## Tags
rectangular box
-/
open set function metric filter
noncomputable theory
open_locale nnreal classical topological_space
namespace box_integral
variables {ι : Type*}
/-!
### Rectangular box: definition and partial order
-/
/-- A nontrivial rectangular box in `ι → ℝ` with corners `lower` and `upper`. Repesents the product
of half-open intervals `(lower i, upper i]`. -/
structure box (ι : Type*) :=
(lower upper : ι → ℝ)
(lower_lt_upper : ∀ i, lower i < upper i)
attribute [simp] box.lower_lt_upper
namespace box
variables (I J : box ι) {x y : ι → ℝ}
instance : inhabited (box ι) := ⟨⟨0, 1, λ i, zero_lt_one⟩⟩
lemma lower_le_upper : I.lower ≤ I.upper := λ i, (I.lower_lt_upper i).le
lemma lower_ne_upper (i) : I.lower i ≠ I.upper i := (I.lower_lt_upper i).ne
instance : has_mem (ι → ℝ) (box ι) := ⟨λ x I, ∀ i, x i ∈ Ioc (I.lower i) (I.upper i)⟩
instance : has_coe_t (box ι) (set $ ι → ℝ) := ⟨λ I, {x | x ∈ I}⟩
@[simp] lemma mem_mk {l u x : ι → ℝ} {H} : x ∈ mk l u H ↔ ∀ i, x i ∈ Ioc (l i) (u i) := iff.rfl
@[simp, norm_cast] lemma mem_coe : x ∈ (I : set (ι → ℝ)) ↔ x ∈ I := iff.rfl
lemma mem_def : x ∈ I ↔ ∀ i, x i ∈ Ioc (I.lower i) (I.upper i) := iff.rfl
lemma mem_univ_Ioc {I : box ι} : x ∈ pi univ (λ i, Ioc (I.lower i) (I.upper i)) ↔ x ∈ I :=
mem_univ_pi
lemma coe_eq_pi : (I : set (ι → ℝ)) = pi univ (λ i, Ioc (I.lower i) (I.upper i)) :=
set.ext $ λ x, mem_univ_Ioc.symm
@[simp] lemma upper_mem : I.upper ∈ I := λ i, right_mem_Ioc.2 $ I.lower_lt_upper i
lemma exists_mem : ∃ x, x ∈ I := ⟨_, I.upper_mem⟩
lemma nonempty_coe : set.nonempty (I : set (ι → ℝ)) := I.exists_mem
@[simp] lemma coe_ne_empty : (I : set (ι → ℝ)) ≠ ∅ := I.nonempty_coe.ne_empty
@[simp] lemma empty_ne_coe : ∅ ≠ (I : set (ι → ℝ)) := I.coe_ne_empty.symm
instance : has_le (box ι) := ⟨λ I J, ∀ ⦃x⦄, x ∈ I → x ∈ J⟩
lemma le_def : I ≤ J ↔ ∀ x ∈ I, x ∈ J := iff.rfl
lemma le_tfae :
tfae [I ≤ J,
(I : set (ι → ℝ)) ⊆ J,
Icc I.lower I.upper ⊆ Icc J.lower J.upper,
J.lower ≤ I.lower ∧ I.upper ≤ J.upper] :=
begin
tfae_have : 1 ↔ 2, from iff.rfl,
tfae_have : 2 → 3,
{ intro h,
simpa [coe_eq_pi, closure_pi_set, lower_ne_upper] using closure_mono h },
tfae_have : 3 ↔ 4, from Icc_subset_Icc_iff I.lower_le_upper,
tfae_have : 4 → 2, from λ h x hx i, Ioc_subset_Ioc (h.1 i) (h.2 i) (hx i),
tfae_finish
end
variables {I J}
@[simp, norm_cast] lemma coe_subset_coe : (I : set (ι → ℝ)) ⊆ J ↔ I ≤ J := iff.rfl
lemma le_iff_bounds : I ≤ J ↔ J.lower ≤ I.lower ∧ I.upper ≤ J.upper := (le_tfae I J).out 0 3
lemma injective_coe : injective (coe : box ι → set (ι → ℝ)) :=
begin
rintros ⟨l₁, u₁, h₁⟩ ⟨l₂, u₂, h₂⟩ h,
simp only [subset.antisymm_iff, coe_subset_coe, le_iff_bounds] at h,
congr,
exacts [le_antisymm h.2.1 h.1.1, le_antisymm h.1.2 h.2.2]
end
@[simp, norm_cast] lemma coe_inj : (I : set (ι → ℝ)) = J ↔ I = J :=
injective_coe.eq_iff
@[ext] lemma ext (H : ∀ x, x ∈ I ↔ x ∈ J) : I = J :=
injective_coe $ set.ext H
lemma ne_of_disjoint_coe (h : disjoint (I : set (ι → ℝ)) J) : I ≠ J :=
mt coe_inj.2 $ h.ne I.coe_ne_empty
instance : partial_order (box ι) :=
{ le := (≤),
.. partial_order.lift (coe : box ι → set (ι → ℝ)) injective_coe }
/-- Closed box corresponding to `I : box_integral.box ι`. -/
protected def Icc : box ι ↪o set (ι → ℝ) :=
order_embedding.of_map_le_iff (λ I : box ι, Icc I.lower I.upper) (λ I J, (le_tfae I J).out 2 0)
lemma Icc_def : I.Icc = Icc I.lower I.upper := rfl
@[simp] lemma upper_mem_Icc (I : box ι) : I.upper ∈ I.Icc := right_mem_Icc.2 I.lower_le_upper
@[simp] lemma lower_mem_Icc (I : box ι) : I.lower ∈ I.Icc := left_mem_Icc.2 I.lower_le_upper
protected lemma is_compact_Icc (I : box ι) : is_compact I.Icc := is_compact_Icc
lemma Icc_eq_pi : I.Icc = pi univ (λ i, Icc (I.lower i) (I.upper i)) := (pi_univ_Icc _ _).symm
lemma le_iff_Icc : I ≤ J ↔ I.Icc ⊆ J.Icc := (le_tfae I J).out 0 2
lemma antitone_lower : antitone (λ I : box ι, I.lower) :=
λ I J H, (le_iff_bounds.1 H).1
lemma monotone_upper : monotone (λ I : box ι, I.upper) :=
λ I J H, (le_iff_bounds.1 H).2
lemma coe_subset_Icc : ↑I ⊆ I.Icc := λ x hx, ⟨λ i, (hx i).1.le, λ i, (hx i).2⟩
/-!
### Supremum of two boxes
-/
/-- `I ⊔ J` is the least box that includes both `I` and `J`. Since `↑I ∪ ↑J` is usually not a box,
`↑(I ⊔ J)` is larger than `↑I ∪ ↑J`. -/
instance : has_sup (box ι) :=
⟨λ I J, ⟨I.lower ⊓ J.lower, I.upper ⊔ J.upper,
λ i, (min_le_left _ _).trans_lt $ (I.lower_lt_upper i).trans_le (le_max_left _ _)⟩⟩
instance : semilattice_sup (box ι) :=
{ le_sup_left := λ I J, le_iff_bounds.2 ⟨inf_le_left, le_sup_left⟩,
le_sup_right := λ I J, le_iff_bounds.2 ⟨inf_le_right, le_sup_right⟩,
sup_le := λ I₁ I₂ J h₁ h₂, le_iff_bounds.2 ⟨le_inf (antitone_lower h₁) (antitone_lower h₂),
sup_le (monotone_upper h₁) (monotone_upper h₂)⟩,
.. box.partial_order, .. box.has_sup }
/-!
### `with_bot (box ι)`
In this section we define coercion from `with_bot (box ι)` to `set (ι → ℝ)` by sending `⊥` to `∅`.
-/
instance with_bot_coe : has_coe_t (with_bot (box ι)) (set (ι → ℝ)) := ⟨λ o, o.elim ∅ coe⟩
@[simp, norm_cast] lemma coe_bot : ((⊥ : with_bot (box ι)) : set (ι → ℝ)) = ∅ := rfl
@[simp, norm_cast] lemma coe_coe : ((I : with_bot (box ι)) : set (ι → ℝ)) = I := rfl
lemma is_some_iff : ∀ {I : with_bot (box ι)}, I.is_some ↔ (I : set (ι → ℝ)).nonempty
| ⊥ := by { erw option.is_some, simp }
| (I : box ι) := by { erw option.is_some, simp [I.nonempty_coe] }
lemma bUnion_coe_eq_coe (I : with_bot (box ι)) :
(⋃ (J : box ι) (hJ : ↑J = I), (J : set (ι → ℝ))) = I :=
by induction I using with_bot.rec_bot_coe; simp [with_bot.coe_eq_coe]
@[simp, norm_cast] lemma with_bot_coe_subset_iff {I J : with_bot (box ι)} :
(I : set (ι → ℝ)) ⊆ J ↔ I ≤ J :=
begin
induction I using with_bot.rec_bot_coe, { simp },
induction J using with_bot.rec_bot_coe, { simp [subset_empty_iff] },
simp
end
@[simp, norm_cast] lemma with_bot_coe_inj {I J : with_bot (box ι)} :
(I : set (ι → ℝ)) = J ↔ I = J :=
by simp only [subset.antisymm_iff, ← le_antisymm_iff, with_bot_coe_subset_iff]
/-- Make a `with_bot (box ι)` from a pair of corners `l u : ι → ℝ`. If `l i < u i` for all `i`,
then the result is `⟨l, u, _⟩ : box ι`, otherwise it is `⊥`. In any case, the result interpreted
as a set in `ι → ℝ` is the set `{x : ι → ℝ | ∀ i, x i ∈ Ioc (l i) (u i)}`. -/
def mk' (l u : ι → ℝ) : with_bot (box ι) :=
if h : ∀ i, l i < u i then ↑(⟨l, u, h⟩ : box ι) else ⊥
@[simp] lemma mk'_eq_bot {l u : ι → ℝ} : mk' l u = ⊥ ↔ ∃ i, u i ≤ l i :=
by { rw mk', split_ifs; simpa using h }
@[simp] lemma mk'_eq_coe {l u : ι → ℝ} : mk' l u = I ↔ l = I.lower ∧ u = I.upper :=
begin
cases I with lI uI hI, rw mk', split_ifs,
{ simp [with_bot.coe_eq_coe] },
{ suffices : l = lI → u ≠ uI, by simpa,
rintro rfl rfl, exact h hI }
end
@[simp] lemma coe_mk' (l u : ι → ℝ) : (mk' l u : set (ι → ℝ)) = pi univ (λ i, Ioc (l i) (u i)) :=
begin
rw mk', split_ifs,
{ exact coe_eq_pi _ },
{ rcases not_forall.mp h with ⟨i, hi⟩,
rw [coe_bot, univ_pi_eq_empty], exact Ioc_eq_empty hi }
end
instance : has_inf (with_bot (box ι)) :=
⟨λ I, with_bot.rec_bot_coe (λ J, ⊥) (λ I J, with_bot.rec_bot_coe ⊥
(λ J, mk' (I.lower ⊔ J.lower) (I.upper ⊓ J.upper)) J) I⟩
@[simp] lemma coe_inf (I J : with_bot (box ι)) : (↑(I ⊓ J) : set (ι → ℝ)) = I ∩ J :=
begin
induction I using with_bot.rec_bot_coe, { change ∅ = _, simp },
induction J using with_bot.rec_bot_coe, { change ∅ = _, simp },
change ↑(mk' _ _) = _,
simp only [coe_eq_pi, ← pi_inter_distrib, Ioc_inter_Ioc, pi.sup_apply, pi.inf_apply, coe_mk',
coe_coe]
end
instance : lattice (with_bot (box ι)) :=
{ inf_le_left := λ I J,
begin
rw [← with_bot_coe_subset_iff, coe_inf],
exact inter_subset_left _ _
end,
inf_le_right := λ I J,
begin
rw [← with_bot_coe_subset_iff, coe_inf],
exact inter_subset_right _ _
end,
le_inf := λ I J₁ J₂ h₁ h₂,
begin
simp only [← with_bot_coe_subset_iff, coe_inf] at *,
exact subset_inter h₁ h₂
end,
.. with_bot.semilattice_sup, .. box.with_bot.has_inf }
@[simp, norm_cast] lemma disjoint_with_bot_coe {I J : with_bot (box ι)} :
disjoint (I : set (ι → ℝ)) J ↔ disjoint I J :=
by { simp only [disjoint, ← with_bot_coe_subset_iff, coe_inf], refl }
lemma disjoint_coe : disjoint (I : with_bot (box ι)) J ↔ disjoint (I : set (ι → ℝ)) J :=
disjoint_with_bot_coe.symm
lemma not_disjoint_coe_iff_nonempty_inter :
¬disjoint (I : with_bot (box ι)) J ↔ (I ∩ J : set (ι → ℝ)).nonempty :=
by rw [disjoint_coe, set.not_disjoint_iff_nonempty_inter]
/-!
### Hyperface of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`
-/
/-- Face of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`: the box in `ℝⁿ = fin n → ℝ` with corners at
`I.lower ∘ fin.succ_above i` and `I.upper ∘ fin.succ_above i`. -/
@[simps { simp_rhs := tt }] def face {n} (I : box (fin (n + 1))) (i : fin (n + 1)) : box (fin n) :=
⟨I.lower ∘ fin.succ_above i, I.upper ∘ fin.succ_above i, λ j, I.lower_lt_upper _⟩
@[simp] lemma face_mk {n} (l u : fin (n + 1) → ℝ) (h : ∀ i, l i < u i) (i : fin (n + 1)) :
face ⟨l, u, h⟩ i = ⟨l ∘ fin.succ_above i, u ∘ fin.succ_above i, λ j, h _⟩ :=
rfl
@[mono] lemma face_mono {n} {I J : box (fin (n + 1))} (h : I ≤ J) (i : fin (n + 1)) :
face I i ≤ face J i :=
λ x hx i, Ioc_subset_Ioc ((le_iff_bounds.1 h).1 _) ((le_iff_bounds.1 h).2 _) (hx _)
lemma monotone_face {n} (i : fin (n + 1)) : monotone (λ I, face I i) := λ I J h, face_mono h i
lemma maps_to_insert_nth_face_Icc {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Icc (I.lower i) (I.upper i)) :
maps_to (i.insert_nth x) (I.face i).Icc I.Icc :=
λ y hy, fin.insert_nth_mem_Icc.2 ⟨hx, hy⟩
lemma maps_to_insert_nth_face {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Ioc (I.lower i) (I.upper i)) :
maps_to (i.insert_nth x) (I.face i) I :=
λ y hy, by simpa only [mem_coe, mem_def, i.forall_iff_succ_above, hx, fin.insert_nth_apply_same,
fin.insert_nth_apply_succ_above, true_and]
lemma continuous_on_face_Icc {X} [topological_space X] {n} {f : (fin (n + 1) → ℝ) → X}
{I : box (fin (n + 1))} (h : continuous_on f I.Icc) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Icc (I.lower i) (I.upper i)) :
continuous_on (f ∘ i.insert_nth x) (I.face i).Icc :=
h.comp (continuous_on_const.fin_insert_nth i continuous_on_id) (I.maps_to_insert_nth_face_Icc hx)
/-!
### Covering of the interior of a box by a monotone sequence of smaller boxes
-/
/-- The interior of a box. -/
protected def Ioo : box ι →o set (ι → ℝ) :=
{ to_fun := λ I, pi univ (λ i, Ioo (I.lower i) (I.upper i)),
monotone' := λ I J h, pi_mono $ λ i hi, Ioo_subset_Ioo ((le_iff_bounds.1 h).1 i)
((le_iff_bounds.1 h).2 i) }
lemma Ioo_subset_coe (I : box ι) : I.Ioo ⊆ I := λ x hx i, Ioo_subset_Ioc_self (hx i trivial)
protected lemma Ioo_subset_Icc (I : box ι) : I.Ioo ⊆ I.Icc := I.Ioo_subset_coe.trans coe_subset_Icc
lemma Union_Ioo_of_tendsto [finite ι] {I : box ι} {J : ℕ → box ι} (hJ : monotone J)
(hl : tendsto (lower ∘ J) at_top (𝓝 I.lower)) (hu : tendsto (upper ∘ J) at_top (𝓝 I.upper)) :
(⋃ n, (J n).Ioo) = I.Ioo :=
have hl' : ∀ i, antitone (λ n, (J n).lower i),
from λ i, (monotone_eval i).comp_antitone (antitone_lower.comp_monotone hJ),
have hu' : ∀ i, monotone (λ n, (J n).upper i),
from λ i, (monotone_eval i).comp (monotone_upper.comp hJ),
calc (⋃ n, (J n).Ioo) = pi univ (λ i, ⋃ n, Ioo ((J n).lower i) ((J n).upper i)) :
Union_univ_pi_of_monotone (λ i, (hl' i).Ioo (hu' i))
... = I.Ioo :
pi_congr rfl (λ i hi, Union_Ioo_of_mono_of_is_glb_of_is_lub (hl' i) (hu' i)
(is_glb_of_tendsto_at_top (hl' i) (tendsto_pi_nhds.1 hl _))
(is_lub_of_tendsto_at_top (hu' i) (tendsto_pi_nhds.1 hu _)))
lemma exists_seq_mono_tendsto (I : box ι) : ∃ J : ℕ →o box ι, (∀ n, (J n).Icc ⊆ I.Ioo) ∧
tendsto (lower ∘ J) at_top (𝓝 I.lower) ∧ tendsto (upper ∘ J) at_top (𝓝 I.upper) :=
begin
choose a b ha_anti hb_mono ha_mem hb_mem hab ha_tendsto hb_tendsto
using λ i, exists_seq_strict_anti_strict_mono_tendsto (I.lower_lt_upper i),
exact ⟨⟨λ k, ⟨flip a k, flip b k, λ i, hab _ _ _⟩,
λ k l hkl, le_iff_bounds.2 ⟨λ i, (ha_anti i).antitone hkl, λ i, (hb_mono i).monotone hkl⟩⟩,
λ n x hx i hi, ⟨(ha_mem _ _).1.trans_le (hx.1 _), (hx.2 _).trans_lt (hb_mem _ _).2⟩,
tendsto_pi_nhds.2 ha_tendsto, tendsto_pi_nhds.2 hb_tendsto⟩
end
section distortion
variable [fintype ι]
/-- The distortion of a box `I` is the maximum of the ratios of the lengths of its edges.
It is defined as the maximum of the ratios
`nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`. -/
def distortion (I : box ι) : ℝ≥0 :=
finset.univ.sup $ λ i : ι, nndist I.lower I.upper / nndist (I.lower i) (I.upper i)
lemma distortion_eq_of_sub_eq_div {I J : box ι} {r : ℝ}
(h : ∀ i, I.upper i - I.lower i = (J.upper i - J.lower i) / r) :
distortion I = distortion J :=
begin
simp only [distortion, nndist_pi_def, real.nndist_eq', h, map_div₀],
congr' 1 with i,
have : 0 < r,
{ by_contra hr,
have := div_nonpos_of_nonneg_of_nonpos (sub_nonneg.2 $ J.lower_le_upper i) (not_lt.1 hr),
rw ← h at this,
exact this.not_lt (sub_pos.2 $ I.lower_lt_upper i) },
simp_rw [nnreal.finset_sup_div, div_div_div_cancel_right _ ((map_ne_zero real.nnabs).2 this.ne')],
end
lemma nndist_le_distortion_mul (I : box ι) (i : ι) :
nndist I.lower I.upper ≤ I.distortion * nndist (I.lower i) (I.upper i) :=
calc nndist I.lower I.upper =
(nndist I.lower I.upper / nndist (I.lower i) (I.upper i)) * nndist (I.lower i) (I.upper i) :
(div_mul_cancel _ $ mt nndist_eq_zero.1 (I.lower_lt_upper i).ne).symm
... ≤ I.distortion * nndist (I.lower i) (I.upper i) :
mul_le_mul_right' (finset.le_sup $ finset.mem_univ i) _
lemma dist_le_distortion_mul (I : box ι) (i : ι) :
dist I.lower I.upper ≤ I.distortion * (I.upper i - I.lower i) :=
have A : I.lower i - I.upper i < 0, from sub_neg.2 (I.lower_lt_upper i),
by simpa only [← nnreal.coe_le_coe, ← dist_nndist, nnreal.coe_mul, real.dist_eq,
abs_of_neg A, neg_sub] using I.nndist_le_distortion_mul i
lemma diam_Icc_le_of_distortion_le (I : box ι) (i : ι) {c : ℝ≥0} (h : I.distortion ≤ c) :
diam I.Icc ≤ c * (I.upper i - I.lower i) :=
have (0 : ℝ) ≤ c * (I.upper i - I.lower i),
from mul_nonneg c.coe_nonneg (sub_nonneg.2 $ I.lower_le_upper _),
diam_le_of_forall_dist_le this $ λ x hx y hy,
calc dist x y ≤ dist I.lower I.upper : real.dist_le_of_mem_pi_Icc hx hy
... ≤ I.distortion * (I.upper i - I.lower i) : I.dist_le_distortion_mul i
... ≤ c * (I.upper i - I.lower i) :
mul_le_mul_of_nonneg_right h (sub_nonneg.2 (I.lower_le_upper i))
end distortion
end box
end box_integral
|
247047ed454115b4ff18379231f22454f86e085d | 92b50235facfbc08dfe7f334827d47281471333b | /hott/algebra/e_closure.hlean | f798596bf261e6b872a416e5dd7eab1457ffe648 | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 4,453 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
The "equivalence closure" of a type-valued relation.
Given a binary type-valued relation (fibration), we add reflexivity, symmetry and transitivity terms
-/
import .relation types.eq2 arity
open eq
inductive e_closure {A : Type} (R : A → A → Type) : A → A → Type :=
| of_rel : Π{a a'} (r : R a a'), e_closure R a a'
| refl : Πa, e_closure R a a
| symm : Π{a a'} (r : e_closure R a a'), e_closure R a' a
| trans : Π{a a' a''} (r : e_closure R a a') (r' : e_closure R a' a''), e_closure R a a''
namespace e_closure
infix `⬝r`:75 := e_closure.trans
postfix `⁻¹ʳ`:(max+10) := e_closure.symm
notation `[`:max a `]`:0 := e_closure.of_rel a
abbreviation rfl {A : Type} {R : A → A → Type} {a : A} := refl R a
end e_closure
namespace relation
section
parameters {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R
variables ⦃a a' : A⦄ {s : R a a'} {r : T a a}
parameter {R}
protected definition e_closure.elim {B : Type} {f : A → B}
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : f a = f a' :=
begin
induction t,
exact e r,
reflexivity,
exact v_0⁻¹,
exact v_0 ⬝ v_1
end
definition ap_e_closure_elim_h {B C : Type} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap g (e_closure.elim e t) = e_closure.elim e' t :=
begin
induction t,
apply p,
reflexivity,
exact ap_inv g (e_closure.elim e r) ⬝ inverse2 v_0,
exact ap_con g (e_closure.elim e r) (e_closure.elim e r') ⬝ (v_0 ◾ v_1)
end
definition ap_e_closure_elim {B C : Type} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: ap g (e_closure.elim e t) = e_closure.elim (λa a' r, ap g (e r)) t :=
ap_e_closure_elim_h e (λa a' s, idp) t
definition ap_e_closure_elim_h_eq {B C : Type} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap_e_closure_elim_h e p t =
ap_e_closure_elim g e t ⬝ ap (λx, e_closure.elim x t) (eq_of_homotopy3 p) :=
begin
fapply homotopy3.rec_on p,
intro q, esimp at q, induction q,
esimp, rewrite eq_of_homotopy3_id
end
theorem ap_ap_e_closure_elim_h {B C D : Type} {f : A → B}
{g : B → C} (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: square (ap (ap h) (ap_e_closure_elim_h e p t))
(ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (e_closure.elim e t))⁻¹
(ap_e_closure_elim_h e' (λa a' s, (ap (ap h) (p s))⁻¹) t) :=
begin
induction t,
{ unfold [ap_e_closure_elim_h, e_closure.elim],
apply square_of_eq, exact !con.right_inv ⬝ !con.left_inv⁻¹},
{ apply ids},
{ unfold [e_closure.elim, ap_e_closure_elim_h],
rewrite [ap_con (ap h)],
refine (transpose !ap_compose_inv)⁻¹ᵛ ⬝h _,
rewrite [con_inv,inv_inv,-inv2_inv],
exact !ap_inv2 ⬝v square_inv2 v_0},
{ unfold [e_closure.elim, ap_e_closure_elim_h],
rewrite [ap_con (ap h)],
refine (transpose !ap_compose_con)⁻¹ᵛ ⬝h _,
rewrite [con_inv,inv_inv,con2_inv],
refine !ap_con2 ⬝v square_con2 v_0 v_1},
end
theorem ap_ap_e_closure_elim {B C D : Type} {f : A → B}
(g : B → C) (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: square (ap (ap h) (ap_e_closure_elim g e t))
(ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (e_closure.elim e t))⁻¹
(ap_e_closure_elim h (λa a' r, ap g (e r)) t) :=
!ap_ap_e_closure_elim_h
open e_closure
definition is_equivalence_e_closure : is_equivalence T :=
begin
constructor,
intro a, exact rfl,
intro a a' t, exact t⁻¹ʳ,
intro a a' a'' t t', exact t ⬝r t',
end
end
end relation
|
5df28fecb958a5d985cab8e910a36bd984db150f | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/number_theory/primorial.lean | 87e204ad0791d557eeb34273d567614ecfd03b6a | [
"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 | 7,387 | lean | /-
Copyright (c) 2020 Patrick Stevens. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Stevens
-/
import tactic.ring_exp
import data.nat.parity
import data.nat.choose.sum
/-!
# Primorial
This file defines the primorial function (the product of primes less than or equal to some bound),
and proves that `primorial n ≤ 4 ^ n`.
## Notations
We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less
than or equal to `n`.
-/
open finset
open nat
open_locale big_operators nat
/-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`.
-/
def primorial (n : ℕ) : ℕ := ∏ p in (filter prime (range (n + 1))), p
local notation x`#` := primorial x
lemma primorial_succ {n : ℕ} (n_big : 1 < n) (r : n % 2 = 1) : (n + 1)# = n# :=
begin
have not_prime : ¬prime (n + 1),
{ intros is_prime,
cases (prime.eq_two_or_odd is_prime) with _ n_even,
{ linarith, },
{ exfalso,
rw ←not_even_iff at n_even r,
have e : even (n + 1 - n) := (even_sub (lt_add_one n).le).2 (iff_of_false n_even r),
simp only [nat.add_sub_cancel_left, not_even_one] at e,
exact e, }, },
apply finset.prod_congr,
{ rw [@range_succ (n + 1), filter_insert, if_neg not_prime], },
{ exact λ _ _, rfl, },
end
lemma dvd_choose_of_middling_prime (p : ℕ) (is_prime : prime p) (m : ℕ)
(p_big : m + 1 < p) (p_small : p ≤ 2 * m + 1) : p ∣ choose (2 * m + 1) (m + 1) :=
begin
have m_size : m + 1 ≤ 2 * m + 1 := le_of_lt (lt_of_lt_of_le p_big p_small),
have expanded :
choose (2 * m + 1) (m + 1) * (m + 1)! * (2 * m + 1 - (m + 1))! = (2 * m + 1)! :=
@choose_mul_factorial_mul_factorial (2 * m + 1) (m + 1) m_size,
have p_div_big_fact : p ∣ (2 * m + 1)! := (prime.dvd_factorial is_prime).mpr p_small,
rw [←expanded, mul_assoc] at p_div_big_fact,
have s : ¬(p ∣ (m + 1)!),
{ intros p_div_fact,
have p_le_succ_m : p ≤ m + 1 := (prime.dvd_factorial is_prime).mp p_div_fact,
linarith, },
have t : ¬(p ∣ (2 * m + 1 - (m + 1))!),
{ intros p_div_fact,
have p_small : p ≤ 2 * m + 1 - (m + 1) := (prime.dvd_factorial is_prime).mp p_div_fact,
have t : 2 * m + 1 - (m + 1) = m, by { norm_num, rw two_mul m, exact nat.add_sub_cancel m m, },
rw t at p_small,
obtain p_lt_m | rfl | m_lt_p : _ := lt_trichotomy p m,
{ have r : m < m + 1 := lt_add_one m, linarith, },
{ linarith, },
{ linarith, }, },
obtain p_div_choose | p_div_facts : p ∣ choose (2 * m + 1) (m + 1) ∨ p ∣ _! * _! :=
(prime.dvd_mul is_prime).1 p_div_big_fact,
{ exact p_div_choose, },
cases (prime.dvd_mul is_prime).1 p_div_facts,
cc, cc,
end
lemma prod_primes_dvd {s : finset ℕ} : ∀ (n : ℕ) (h : ∀ a ∈ s, prime a) (div : ∀ a ∈ s, a ∣ n),
(∏ p in s, p) ∣ n :=
begin
apply finset.induction_on s,
{ simp, },
{ intros a s a_not_in_s induct n primes divs,
rw finset.prod_insert a_not_in_s,
obtain ⟨k, rfl⟩ : a ∣ n, by exact divs a (finset.mem_insert_self a s),
have step : ∏ p in s, p ∣ k,
{ apply induct k,
{ intros b b_in_s,
exact primes b (finset.mem_insert_of_mem b_in_s), },
{ intros b b_in_s,
have b_div_n, by exact divs b (finset.mem_insert_of_mem b_in_s),
have a_prime : prime a, { exact primes a (finset.mem_insert_self a s), },
have b_prime : prime b, { exact primes b (finset.mem_insert_of_mem b_in_s), },
obtain b_div_a | b_div_k : b ∣ a ∨ b ∣ k, exact (prime.dvd_mul b_prime).mp b_div_n,
{ exfalso,
have b_eq_a : b = a,
{ cases (nat.dvd_prime a_prime).1 b_div_a with b_eq_1 b_eq_a,
{ subst b_eq_1, exfalso, exact prime.ne_one b_prime rfl, },
{ exact b_eq_a } },
subst b_eq_a,
exact a_not_in_s b_in_s, },
{ exact b_div_k } } },
exact mul_dvd_mul_left a step, }
end
lemma primorial_le_4_pow : ∀ (n : ℕ), n# ≤ 4 ^ n
| 0 := le_refl _
| 1 := le_of_inf_eq rfl
| (n + 2) :=
match nat.mod_two_eq_zero_or_one (n + 1) with
| or.inl n_odd :=
match nat.even_iff.2 n_odd with
| ⟨m, twice_m⟩ :=
let recurse : m + 1 < n + 2 := by linarith in
begin
calc (n + 2)#
= ∏ i in filter prime (range (2 * m + 2)), i : by simpa [←twice_m]
... = ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2) ∪ range (m + 2)), i :
begin
rw [range_eq_Ico, range_eq_Ico, finset.union_comm, finset.Ico.union_consecutive],
exact bot_le,
simp only [add_le_add_iff_right],
linarith,
end
... = ∏ i in (filter prime (finset.Ico (m + 2) (2 * m + 2))
∪ (filter prime (range (m + 2)))), i :
by rw filter_union
... = (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i)
* (∏ i in filter prime (range (m + 2)), i) :
begin
apply finset.prod_union,
have disj : disjoint (finset.Ico (m + 2) (2 * m + 2)) (range (m + 2)),
{ simp only [finset.disjoint_left, and_imp, finset.Ico.mem, not_lt,
finset.mem_range],
intros _ pr _, exact pr, },
exact finset.disjoint_filter_filter disj,
end
... ≤ (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i) * 4 ^ (m + 1) :
by exact nat.mul_le_mul_left _ (primorial_le_4_pow (m + 1))
... ≤ (choose (2 * m + 1) (m + 1)) * 4 ^ (m + 1) :
begin
have s : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)),
i ∣ choose (2 * m + 1) (m + 1),
{ refine prod_primes_dvd (choose (2 * m + 1) (m + 1)) _ _,
{ intros a, rw finset.mem_filter, cc, },
{ intros a, rw finset.mem_filter,
intros pr,
rcases pr with ⟨ size, is_prime ⟩,
simp only [finset.Ico.mem] at size,
rcases size with ⟨ a_big , a_small ⟩,
exact dvd_choose_of_middling_prime a is_prime m a_big
(nat.lt_succ_iff.mp a_small), }, },
have r : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)),
i ≤ choose (2 * m + 1) (m + 1),
{ refine @nat.le_of_dvd _ _ _ s,
exact @choose_pos (2 * m + 1) (m + 1) (by linarith), },
exact nat.mul_le_mul_right _ r,
end
... = (choose (2 * m + 1) m) * 4 ^ (m + 1) : by rw choose_symm_half m
... ≤ 4 ^ m * 4 ^ (m + 1) : nat.mul_le_mul_right _ (choose_middle_le_pow m)
... = 4 ^ (2 * m + 1) : by ring_exp
... = 4 ^ (n + 2) : by rw ←twice_m,
end
end
| or.inr n_even :=
begin
obtain one_lt_n | n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := lt_or_le 1 (n + 1),
{ rw primorial_succ (by linarith) n_even,
calc (n + 1)#
≤ 4 ^ n.succ : primorial_le_4_pow (n + 1)
... ≤ 4 ^ (n + 2) : pow_le_pow (by norm_num) (nat.le_succ _), },
{ have n_zero : n = 0 := eq_bot_iff.2 (succ_le_succ_iff.1 n_le_one),
norm_num [n_zero, primorial, range_succ, prod_filter, not_prime_zero, prime_two] },
end
end
|
66db413b4e450f487aa9981dace305331860bf88 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/reassoc_axiom.lean | 169cf59f657f4b9d788a427aa2596a84882b1214 | [
"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 | 8,047 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import category_theory.category
/-!
# Tools to reformulate category-theoretic axioms in a more associativity-friendly way
## The `reassoc` attribute
The `reassoc` attribute can be applied to a lemma
```lean
@[reassoc]
lemma some_lemma : foo ≫ bar = baz := ...
```
and produce
```lean
lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ...
```
The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If
`simp` is added first, the generated lemma will also have the `simp` attribute.
## The `reassoc_axiom` command
When declaring a class of categories, the axioms can be reformulated to be more amenable
to manipulation in right associated expressions:
```lean
class some_class (C : Type) [category C] :=
(foo : Π X : C, X ⟶ X)
(bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y)
reassoc_axiom some_class.bar
```
Here too, the `reassoc` attribute can be used instead. It works well when combined with
`simp`:
```lean
attribute [simp, reassoc] some_class.bar
```
-/
namespace tactic
open interactive lean.parser category_theory
/-- From an expression `f ≫ g`, extract the expression representing the category instance. -/
meta def get_cat_inst : expr → tactic expr
| `(@category_struct.comp _ %%struct_inst _ _ _ _ _) := pure struct_inst
| _ := failed
/-- (internals for `@[reassoc]`)
Given a lemma of the form `f ≫ g = h`, proves a new lemma of the form
`h : ∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`, and returns the type and proof of this lemma.
-/
meta def prove_reassoc (h : expr) : tactic (expr × expr) :=
do
(vs,t) ← infer_type h >>= open_pis,
(vs',t) ← whnf t >>= open_pis,
let vs := vs ++ vs',
(lhs,rhs) ← match_eq t,
struct_inst ← get_cat_inst lhs <|> get_cat_inst rhs <|> fail "no composition found in statement",
`(@has_hom.hom _ %%hom_inst %%X %%Y) ← infer_type lhs,
C ← infer_type X,
X' ← mk_local' `X' binder_info.implicit C,
ft ← to_expr ``(@has_hom.hom _ %%hom_inst %%Y %%X'),
f' ← mk_local_def `f' ft,
t' ← to_expr ``(@category_struct.comp _ %%struct_inst _ _ _%%lhs %%f' =
@category_struct.comp _ %%struct_inst _ _ _ %%rhs %%f'),
let c' := h.mk_app vs,
(_,pr) ← solve_aux t' (rewrite_target c'; reflexivity),
pr ← instantiate_mvars pr,
let s := simp_lemmas.mk,
s ← s.add_simp ``category.assoc,
s ← s.add_simp ``category.id_comp,
s ← s.add_simp ``category.comp_id,
(t'', pr', _) ← simplify s [] t',
pr' ← mk_eq_mp pr' pr,
t'' ← pis (vs ++ [X',f']) t'',
pr' ← lambdas (vs ++ [X',f']) pr',
pure (t'',pr')
/-- (implementation for `@[reassoc]`)
Given a declaration named `n` of the form `f ≫ g = h`, proves a new lemma named `n'`
of the form `∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`.
-/
meta def reassoc_axiom (n : name) (n' : name := n.append_suffix "_assoc") : tactic unit :=
do d ← get_decl n,
let ls := d.univ_params.map level.param,
let c := @expr.const tt n ls,
(t'',pr') ← prove_reassoc c,
add_decl $ declaration.thm n' d.univ_params t'' (pure pr'),
copy_attribute `simp n n'
/--
The `reassoc` attribute can be applied to a lemma
```lean
@[reassoc]
lemma some_lemma : foo ≫ bar = baz := ...
```
to produce
```lean
lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ...
```
The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If
`simp` is added first, the generated lemma will also have the `simp` attribute.
-/
@[user_attribute]
meta def reassoc_attr : user_attribute unit (option name) :=
{ name := `reassoc,
descr := "create a companion lemma for associativity-aware rewriting",
parser := optional ident,
after_set := some (λ n _ _,
do some n' ← reassoc_attr.get_param n | reassoc_axiom n (n.append_suffix "_assoc"),
reassoc_axiom n $ n.get_prefix ++ n' ) }
add_tactic_doc
{ name := "reassoc",
category := doc_category.attr,
decl_names := [`tactic.reassoc_attr],
tags := ["category theory"] }
/--
When declaring a class of categories, the axioms can be reformulated to be more amenable
to manipulation in right associated expressions:
```lean
class some_class (C : Type) [category C] :=
(foo : Π X : C, X ⟶ X)
(bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y)
reassoc_axiom some_class.bar
```
The above will produce:
```lean
lemma some_class.bar_assoc {Z : C} (g : Y ⟶ Z) :
foo X ≫ f ≫ g = f ≫ foo Y ≫ g := ...
```
Here too, the `reassoc` attribute can be used instead. It works well when combined with
`simp`:
```lean
attribute [simp, reassoc] some_class.bar
```
-/
@[user_command]
meta def reassoc_cmd (_ : parse $ tk "reassoc_axiom") : lean.parser unit :=
do n ← ident,
of_tactic $
do n ← resolve_constant n,
reassoc_axiom n
add_tactic_doc
{ name := "reassoc_axiom",
category := doc_category.cmd,
decl_names := [`tactic.reassoc_cmd],
tags := ["category theory"] }
namespace interactive
setup_tactic_parser
/-- `reassoc h`, for assumption `h : x ≫ y = z`, creates a new assumption
`h : ∀ {W} (f : Z ⟶ W), x ≫ y ≫ f = z ≫ f`.
`reassoc! h`, does the same but deletes the initial `h` assumption.
(You can also add the attribute `@[reassoc]` to lemmas to generate new declarations generalized
in this way.)
-/
meta def reassoc (del : parse (tk "!")?) (ns : parse ident*) : tactic unit :=
do ns.mmap' (λ n,
do h ← get_local n,
(t,pr) ← prove_reassoc h,
assertv n t pr,
when del.is_some (tactic.clear h) )
end interactive
def calculated_Prop {α} (β : Prop) (hh : α) := β
meta def derive_reassoc_proof : tactic unit :=
do `(calculated_Prop %%v %%h) ← target,
(t,pr) ← prove_reassoc h,
unify v t,
exact pr
end tactic
/-- With `h : x ≫ y ≫ z = x` (with universal quantifiers tolerated),
`reassoc_of h : ∀ {X'} (f : W ⟶ X'), x ≫ y ≫ z ≫ f = x ≫ f`.
The type and proof of `reassoc_of h` is generated by `tactic.derive_reassoc_proof`
which make `reassoc_of` meta-programming adjacent. It is not called as a tactic but as
an expression. The goal is to avoid creating assumptions that are dismissed after one use:
```lean
example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z)
(h : x ≫ y = w)
(h' : y ≫ z = y ≫ z') :
x ≫ y ≫ z = w ≫ z' :=
begin
rw [h',reassoc_of h],
end
```
-/
theorem category_theory.reassoc_of {α} (hh : α) {β}
(x : tactic.calculated_Prop β hh . tactic.derive_reassoc_proof) : β := x
/--
`reassoc_of h` takes local assumption `h` and add a ` ≫ f` term on the right of
both sides of the equality. Instead of creating a new assumption from the result, `reassoc_of h`
stands for the proof of that reassociated statement. This keeps complicated assumptions that are
used only once or twice from polluting the local context.
In the following, assumption `h` is needed in a reassociated form. Instead of proving it as a new
goal and adding it as an assumption, we use `reassoc_of h` as a rewrite rule which works just as
well.
```lean
example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z)
(h : x ≫ y = w)
(h' : y ≫ z = y ≫ z') :
x ≫ y ≫ z = w ≫ z' :=
begin
-- reassoc_of h : ∀ {X' : C} (f : W ⟶ X'), x ≫ y ≫ f = w ≫ f
rw [h',reassoc_of h],
end
```
Although `reassoc_of` is not a tactic or a meta program, its type is generated
through meta-programming to make it usable inside normal expressions.
-/
add_tactic_doc
{ name := "category_theory.reassoc_of",
category := doc_category.tactic,
decl_names := [`category_theory.reassoc_of],
tags := ["category theory"] }
|
0792e191860a2db03184ebfb2d2be8e095a5da30 | 1fbca480c1574e809ae95a3eda58188ff42a5e41 | /src/util/data/functor.lean | f4c2eec0b8cb6f9f7afa7dfd990adec31ff2a8fa | [] | no_license | unitb/lean-lib | 560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e | 439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9 | refs/heads/master | 1,610,706,025,400 | 1,570,144,245,000 | 1,570,144,245,000 | 99,579,229 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,960 | lean |
universe variables u v w u' v' w'
class functor_pair (f : Type u → Type v) (g : Type u' → Type v') :=
(f_functor : functor f)
(g_functor : functor g)
(map : ∀ {α β}, (α → β) → f α → g β)
(map_fmap_comm : ∀ {α β β' γ}
(h : β → γ) (hp : α → β)
(hp' : β' → γ) (h' : α → β')
(x : f α),
h ∘ hp = hp' ∘ h' →
functor.map h (map hp x) = map hp' (functor.map h' x))
section thms
variables {F : Type u → Type v}
variables {α β γ : Type u}
variables [functor F] [is_lawful_functor F]
lemma functor.id_map' : functor.map id = (id : F α → F α) :=
by { apply funext, apply is_lawful_functor.id_map }
lemma functor.comp_map' (f : α → β) (g : β → γ)
: functor.map (g ∘ f) = (functor.map g ∘ functor.map f : F α → F γ) :=
by { apply funext, intro, apply is_lawful_functor.comp_map }
@[norm]
lemma functor.map_map (f : α → β) (g : β → γ) (x : F α) :
g <$> f <$> x = (g ∘ f) <$> x :=
by rw ← comp_map
end thms
/- identity functor -/
structure identity (α : Type u) : Type u :=
(run_identity : α)
namespace identity
open function
variables {α : Type u} {β : Type v} {γ : Type u'}
def map (f : α → β) : identity α → identity β
| ⟨ x ⟩ := ⟨ f x ⟩
local infixr <$> := map
lemma id_map : ∀ (x : identity α), map id x = x
| ⟨ x ⟩ := rfl
lemma comp_map (f : α → β) (g : β → γ)
: ∀ (x : identity α), map (g ∘ f) x = g <$> f <$> x
| ⟨ x ⟩ := rfl
end identity
instance identity_functor : functor identity :=
{ map := @identity.map }
instance identity_lawful_functor : is_lawful_functor identity :=
{ id_map := @identity.id_map
, comp_map := @identity.comp_map }
instance : functor_pair identity identity :=
{ f_functor := identity_functor
, g_functor := identity_functor
, map := @identity.map
, map_fmap_comm :=
begin
intros α β β' γ,
intros h hp hp' h' x,
intros H,
rw [← identity.comp_map,← identity.comp_map,H],
end }
lemma identity.fmap_mk {α β : Type v} (f : α → β) (x : α)
: f <$> identity.mk x = identity.mk (f x) := rfl
/- compose functor instance -/
structure compose (f : Type u → Type u') (g : Type v → Type u) (α : Type v) : Type u' :=
(run : f $ g α)
namespace compose
section functor
variables {f : Type u → Type u'} {g : Type v → Type u}
variables [functor f] [functor g]
variables {α β γ : Type v}
def map (h : α → β) : compose f g α → compose f g β
| ⟨ x ⟩ := ⟨ functor.map h <$> x ⟩
local infix ` <$> ` := map
variables [is_lawful_functor f] [is_lawful_functor g]
variables {α β γ}
lemma id_map : ∀ (x : compose f g α), map id x = x
| ⟨ x ⟩ :=
by simp! [functor.id_map']
lemma comp_map (g_1 : α → β) (h : β → γ) : ∀ (x : compose f g α),
map (h ∘ g_1) x = map h (map g_1 x)
| ⟨ x ⟩ :=
by simp [map,functor.comp_map' g_1 h,is_lawful_functor.comp_map (functor.map g_1)]
{ single_pass := tt }
end functor
section functor_pair
variables {f : Type v → Type w} {g : Type u → Type v}
variables {f' : Type v' → Type w'} {g' : Type u' → Type v'}
variables [functor_pair f f'] [functor_pair g g']
variables {α : Type u} {β : Type u'}
def map_pair (h : α → β) : compose f g α → compose f' g' β
| ⟨ x ⟩ := ⟨ functor_pair.map f' (functor_pair.map g' h) x ⟩
end functor_pair
end compose
instance functor_compose {f : Type u → Type u'} {g : Type v → Type u}
[functor f] [functor g]
: functor (compose f g) :=
{ map := @compose.map f g _ _ }
instance lawful_functor_compose {f : Type u → Type u'} {g : Type v → Type u}
[functor f] [functor g]
[is_lawful_functor f] [is_lawful_functor g]
: is_lawful_functor (compose f g) :=
{ id_map := λ _, @compose.id_map f g _ _ _ _ _
, comp_map := λ _ _ _, @compose.comp_map f g _ _ _ _ _ _ _ }
instance compose_functor_pair
{f : Type v → Type w} {g : Type u → Type v}
{f' : Type v' → Type w'} {g' : Type u' → Type v'}
[functor_pair f f'] [functor_pair g g']
: functor_pair (compose f g) (compose f' g') :=
{ f_functor := @functor_compose f g
(functor_pair.f_functor f f')
(functor_pair.f_functor g g')
, g_functor := @functor_compose f' g'
(functor_pair.g_functor f f')
(functor_pair.g_functor g g')
, map := @compose.map_pair f g _ _ _ _
, map_fmap_comm :=
begin
intros α β β' γ,
intros h hp hp' h' x H,
unfold functor.map,
cases x with x,
unfold compose.map_pair compose.map,
apply congr_arg,
rw [functor_pair.map_fmap_comm],
apply funext, intro i, unfold function.comp functor.map,
rw [functor_pair.map_fmap_comm],
apply H,
end }
@[norm]
lemma compose.fmap_mk {α β : Type u'}
{f : Type u → Type v} {g : Type u' → Type u}
[functor f] [functor g]
(h : α → β) (x : f (g α))
: h <$> compose.mk x = compose.mk (functor.map h <$> x) := rfl
|
3047ff583ad658765a50a04b95ce11ab5de97866 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/smt/rsimp.lean | c7d555b847ddd0e521971e2ae72f9d9aa50de447 | [
"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 | 6,490 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.smt.smt_tactic init.meta.fun_info init.meta.rb_map
open tactic
private meta def add_lemma (m : transparency) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas :=
(do h ← hinst_lemma.mk_from_decl_core m h tt, return $ hs.add h) <|> return hs
private meta def to_hinst_lemmas (m : transparency) (ex : name_set) : list name → hinst_lemmas → tactic hinst_lemmas
| [] hs := return hs
| (n::ns) hs :=
if ex.contains n then to_hinst_lemmas ns hs else
let add n := add_lemma m n hs >>= to_hinst_lemmas ns
in do eqns ← tactic.get_eqn_lemmas_for tt n,
match eqns with
| [] := add n
| _ := mcond (is_prop_decl n) (add n) (to_hinst_lemmas eqns hs >>= to_hinst_lemmas ns)
end
/-- Create a rsimp attribute named `attr_name`, the attribute declaration is named `attr_decl_name`.
The cached hinst_lemmas structure is built using the lemmas marked with simp attribute `simp_attr_name`,
but *not* marked with `ex_attr_name`.
We say `ex_attr_name` is the "exception set". It is useful for excluding lemmas in `simp_attr_name`
which are not good or redundant for ematching. -/
meta def mk_hinst_lemma_attr_from_simp_attr (attr_decl_name attr_name : name) (simp_attr_name : name) (ex_attr_name : name) : command :=
do let t := `(user_attribute hinst_lemmas),
let v := `({name := attr_name,
descr := sformat!"hinst_lemma attribute derived from '{simp_attr_name}'",
cache_cfg := {
mk_cache := λ ns,
let aux := simp_attr_name in
let ex_attr := ex_attr_name in
do {
hs ← to_hinst_lemmas reducible mk_name_set ns hinst_lemmas.mk,
ss ← attribute.get_instances aux,
ex ← get_name_set_for_attr ex_attr,
to_hinst_lemmas reducible ex ss hs
},
dependencies := [`reducibility, simp_attr_name]}} : user_attribute hinst_lemmas),
add_decl (declaration.defn attr_decl_name [] t v reducibility_hints.abbrev ff),
attribute.register attr_decl_name
run_cmd mk_name_set_attr `no_rsimp
run_cmd mk_hinst_lemma_attr_from_simp_attr `rsimp_attr `rsimp `simp `no_rsimp
/- The following lemmas are not needed by rsimp, and they actually hurt performance since they generate a lot of
instances. -/
attribute [no_rsimp]
id.def ne.def not_true not_false_iff ne_self_iff_false eq_self_iff_true heq_self_iff_true iff_not_self not_iff_self
true_iff_false false_iff_true and.comm and.assoc and.left_comm and_true true_and and_false false_and not_and_self and_not_self
and_self or.comm or.assoc or.left_comm or_true true_or or_false false_or or_self iff_true true_iff iff_false false_iff
iff_self implies_true_iff false_implies_iff if_t_t if_true if_false
namespace rsimp
meta def is_value_like : expr → bool
| e :=
if ¬ e.is_app then ff
else let fn := e.get_app_fn in
if ¬ fn.is_constant then ff
else let nargs := e.get_app_num_args,
fname := fn.const_name in
if fname = ``has_zero.zero ∧ nargs = 2 then tt
else if fname = ``has_one.one ∧ nargs = 2 then tt
else if fname = ``bit0 ∧ nargs = 3 then is_value_like e.app_arg
else if fname = ``bit1 ∧ nargs = 4 then is_value_like e.app_arg
else if fname = ``char.of_nat ∧ nargs = 1 then is_value_like e.app_arg
else ff
/-- Return the size of term by considering only explicit arguments. -/
meta def explicit_size : expr → tactic nat
| e :=
if ¬ e.is_app then return 1
else if is_value_like e then return 1
else fold_explicit_args e 1
(λ n arg, do r ← explicit_size arg, return $ r + n)
/-- Choose smallest element (with respect to explicit_size) in `e`s equivalence class. -/
meta def choose (ccs : cc_state) (e : expr) : tactic expr :=
do sz ← explicit_size e,
p ← ccs.mfold_eqc e (e, sz) $ λ p e',
if p.2 = 1 then return p
else do {
sz' ← explicit_size e',
if sz' < p.2 then return (e', sz')
else return p
},
return p.1
meta def repr_map := expr_map expr
meta def mk_repr_map := expr_map.mk expr
meta def to_repr_map (ccs : cc_state) : tactic repr_map :=
ccs.roots.mfoldl (λ S e, do r ← choose ccs e, return $ S.insert e r) mk_repr_map
meta def rsimplify (ccs : cc_state) (e : expr) (m : option repr_map := none) : tactic (expr × expr) :=
do m ← match m with
| none := to_repr_map ccs
| some m := return m
end,
r ← simplify_top_down () (λ _ t,
do root ← return $ ccs.root t,
new_t ← m.find root,
guard (¬ new_t =ₐ t),
prf ← ccs.eqv_proof t new_t,
return ((), new_t, prf))
e,
return r.2
structure config :=
(attr_name := `rsimp_attr)
(max_rounds := 8)
open smt_tactic
meta def collect_implied_eqs (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic cc_state :=
do focus1 $ using_smt_with {em_attr := cfg.attr_name} $
do
add_lemmas_from_facts,
add_lemmas extra,
iterate_at_most cfg.max_rounds (ematch >> try smt_tactic.close),
(done >> return cc_state.mk)
<|>
to_cc_state
meta def rsimplify_goal (ccs : cc_state) (m : option repr_map := none) : tactic unit :=
do t ← target,
(new_t, pr) ← rsimplify ccs t m,
try (replace_target new_t pr)
meta def rsimplify_at (ccs : cc_state) (h : expr) (m : option repr_map := none) : tactic unit :=
do when (expr.is_local_constant h = ff) (tactic.fail "tactic rsimplify_at failed, the given expression is not a hypothesis"),
htype ← infer_type h,
(new_htype, heq) ← rsimplify ccs htype m,
try $ do assert (expr.local_pp_name h) new_htype,
mk_eq_mp heq h >>= exact,
try $ clear h
end rsimp
open rsimp
namespace tactic
meta def rsimp (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic unit :=
do ccs ← collect_implied_eqs cfg extra,
try $ rsimplify_goal ccs
meta def rsimp_at (h : expr) (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic unit :=
do ccs ← collect_implied_eqs cfg extra,
try $ rsimplify_at ccs h
namespace interactive
/- TODO(Leo): allow user to provide extra lemmas manually -/
meta def rsimp : tactic unit :=
tactic.rsimp
end interactive
end tactic
|
3500368224568e8ece02ec6c8fa605cf09b81d5c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/field_theory/separable.lean | 5410fe3fd43fd8c2f5b3c43ed3d6621c05196f49 | [] | 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 | 16,781 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.polynomial.big_operators
import Mathlib.field_theory.minpoly
import Mathlib.field_theory.splitting_field
import Mathlib.field_theory.tower
import Mathlib.algebra.squarefree
import Mathlib.PostPort
universes u u_1 v u_2 u_3
namespace Mathlib
/-!
# Separable polynomials
We define a polynomial to be separable if it is coprime with its derivative. We prove basic
properties about separable polynomials here.
## Main definitions
* `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative.
* `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a
commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`.
* `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`.
-/
namespace polynomial
/-- A polynomial is separable iff it is coprime with its derivative. -/
def separable {R : Type u} [comm_semiring R] (f : polynomial R) :=
is_coprime f (coe_fn derivative f)
theorem separable_def {R : Type u} [comm_semiring R] (f : polynomial R) : separable f ↔ is_coprime f (coe_fn derivative f) :=
iff.rfl
theorem separable_def' {R : Type u} [comm_semiring R] (f : polynomial R) : separable f ↔ ∃ (a : polynomial R), ∃ (b : polynomial R), a * f + b * coe_fn derivative f = 1 :=
iff.rfl
theorem separable_one {R : Type u} [comm_semiring R] : separable 1 :=
is_coprime_one_left
theorem separable_X_add_C {R : Type u} [comm_semiring R] (a : R) : separable (X + coe_fn C a) := sorry
theorem separable_X {R : Type u} [comm_semiring R] : separable X :=
eq.mpr (id (Eq._oldrec (Eq.refl (separable X)) (propext (separable_def X))))
(eq.mpr (id (Eq._oldrec (Eq.refl (is_coprime X (coe_fn derivative X))) derivative_X)) is_coprime_one_right)
theorem separable_C {R : Type u} [comm_semiring R] (r : R) : separable (coe_fn C r) ↔ is_unit r := sorry
theorem separable.of_mul_left {R : Type u} [comm_semiring R] {f : polynomial R} {g : polynomial R} (h : separable (f * g)) : separable f := sorry
theorem separable.of_mul_right {R : Type u} [comm_semiring R] {f : polynomial R} {g : polynomial R} (h : separable (f * g)) : separable g :=
separable.of_mul_left (eq.mp (Eq._oldrec (Eq.refl (separable (f * g))) (mul_comm f g)) h)
theorem separable.of_dvd {R : Type u} [comm_semiring R] {f : polynomial R} {g : polynomial R} (hf : separable f) (hfg : g ∣ f) : separable g :=
Exists.dcases_on hfg
fun (f' : polynomial R) (hfg_h : f = g * f') =>
Eq._oldrec (fun (hf : separable (g * f')) => separable.of_mul_left hf) (Eq.symm hfg_h) hf
theorem separable_gcd_left {F : Type u_1} [field F] {f : polynomial F} (hf : separable f) (g : polynomial F) : separable (euclidean_domain.gcd f g) :=
separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g)
theorem separable_gcd_right {F : Type u_1} [field F] {g : polynomial F} (f : polynomial F) (hg : separable g) : separable (euclidean_domain.gcd f g) :=
separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g)
theorem separable.is_coprime {R : Type u} [comm_semiring R] {f : polynomial R} {g : polynomial R} (h : separable (f * g)) : is_coprime f g := sorry
theorem separable.of_pow' {R : Type u} [comm_semiring R] {f : polynomial R} {n : ℕ} (h : separable (f ^ n)) : is_unit f ∨ separable f ∧ n = 1 ∨ n = 0 := sorry
theorem separable.of_pow {R : Type u} [comm_semiring R] {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : separable (f ^ n)) : separable f ∧ n = 1 :=
or.resolve_right (or.resolve_left (separable.of_pow' hfs) hf) hn
theorem separable.map {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] {p : polynomial R} (h : separable p) {f : R →+* S} : separable (map f p) := sorry
/-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/
def expand (R : Type u) [comm_semiring R] (p : ℕ) : alg_hom R (polynomial R) (polynomial R) :=
alg_hom.mk (ring_hom.to_fun (eval₂_ring_hom C (X ^ p))) sorry sorry sorry sorry sorry
theorem coe_expand (R : Type u) [comm_semiring R] (p : ℕ) : ⇑(expand R p) = eval₂ C (X ^ p) :=
rfl
theorem expand_eq_sum {R : Type u} [comm_semiring R] (p : ℕ) {f : polynomial R} : coe_fn (expand R p) f = finsupp.sum f fun (e : ℕ) (a : R) => coe_fn C a * (X ^ p) ^ e :=
id (Eq.refl (finsupp.sum f fun (e : ℕ) (a : R) => coe_fn C a * (X ^ p) ^ e))
@[simp] theorem expand_C {R : Type u} [comm_semiring R] (p : ℕ) (r : R) : coe_fn (expand R p) (coe_fn C r) = coe_fn C r :=
eval₂_C C (X ^ p)
@[simp] theorem expand_X {R : Type u} [comm_semiring R] (p : ℕ) : coe_fn (expand R p) X = X ^ p :=
eval₂_X C (X ^ p)
@[simp] theorem expand_monomial {R : Type u} [comm_semiring R] (p : ℕ) (q : ℕ) (r : R) : coe_fn (expand R p) (coe_fn (monomial q) r) = coe_fn (monomial (q * p)) r := sorry
theorem expand_expand {R : Type u} [comm_semiring R] (p : ℕ) (q : ℕ) (f : polynomial R) : coe_fn (expand R p) (coe_fn (expand R q) f) = coe_fn (expand R (p * q)) f := sorry
theorem expand_mul {R : Type u} [comm_semiring R] (p : ℕ) (q : ℕ) (f : polynomial R) : coe_fn (expand R (p * q)) f = coe_fn (expand R p) (coe_fn (expand R q) f) :=
Eq.symm (expand_expand p q f)
@[simp] theorem expand_one {R : Type u} [comm_semiring R] (f : polynomial R) : coe_fn (expand R 1) f = f := sorry
theorem expand_pow {R : Type u} [comm_semiring R] (p : ℕ) (q : ℕ) (f : polynomial R) : coe_fn (expand R (p ^ q)) f = nat.iterate (⇑(expand R p)) q f := sorry
theorem derivative_expand {R : Type u} [comm_semiring R] (p : ℕ) (f : polynomial R) : coe_fn derivative (coe_fn (expand R p) f) = coe_fn (expand R p) (coe_fn derivative f) * (↑p * X ^ (p - 1)) := sorry
theorem coeff_expand {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : coeff (coe_fn (expand R p) f) n = ite (p ∣ n) (coeff f (n / p)) 0 := sorry
@[simp] theorem coeff_expand_mul {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : coeff (coe_fn (expand R p) f) (n * p) = coeff f n := sorry
@[simp] theorem coeff_expand_mul' {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : coeff (coe_fn (expand R p) f) (p * n) = coeff f n :=
eq.mpr (id (Eq._oldrec (Eq.refl (coeff (coe_fn (expand R p) f) (p * n) = coeff f n)) (mul_comm p n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (coeff (coe_fn (expand R p) f) (n * p) = coeff f n)) (coeff_expand_mul hp f n)))
(Eq.refl (coeff f n)))
theorem expand_eq_map_domain {R : Type u} [comm_semiring R] (p : ℕ) (f : polynomial R) : coe_fn (expand R p) f = finsupp.map_domain (fun (_x : ℕ) => _x * p) f := sorry
theorem expand_inj {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) {f : polynomial R} {g : polynomial R} : coe_fn (expand R p) f = coe_fn (expand R p) g ↔ f = g := sorry
theorem expand_eq_zero {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) {f : polynomial R} : coe_fn (expand R p) f = 0 ↔ f = 0 := sorry
theorem expand_eq_C {R : Type u} [comm_semiring R] {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : coe_fn (expand R p) f = coe_fn C r ↔ f = coe_fn C r := sorry
theorem nat_degree_expand {R : Type u} [comm_semiring R] (p : ℕ) (f : polynomial R) : nat_degree (coe_fn (expand R p) f) = nat_degree f * p := sorry
theorem map_expand {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (coe_fn (expand R p) q) = coe_fn (expand S p) (map f q) := sorry
theorem separable_X_sub_C {R : Type u} [comm_ring R] {x : R} : separable (X - coe_fn C x) := sorry
theorem separable.mul {R : Type u} [comm_ring R] {f : polynomial R} {g : polynomial R} (hf : separable f) (hg : separable g) (h : is_coprime f g) : separable (f * g) := sorry
theorem separable_prod' {R : Type u} [comm_ring R] {ι : Type u_1} {f : ι → polynomial R} {s : finset ι} : (∀ (x : ι), x ∈ s → ∀ (y : ι), y ∈ s → x ≠ y → is_coprime (f x) (f y)) →
(∀ (x : ι), x ∈ s → separable (f x)) → separable (finset.prod s fun (x : ι) => f x) := sorry
theorem separable_prod {R : Type u} [comm_ring R] {ι : Type u_1} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ (x : ι), separable (f x)) : separable (finset.prod finset.univ fun (x : ι) => f x) :=
separable_prod' (fun (x : ι) (hx : x ∈ finset.univ) (y : ι) (hy : y ∈ finset.univ) (hxy : x ≠ y) => h1 x y hxy)
fun (x : ι) (hx : x ∈ finset.univ) => h2 x
theorem separable.inj_of_prod_X_sub_C {R : Type u} [comm_ring R] [nontrivial R] {ι : Type u_1} {f : ι → R} {s : finset ι} (hfs : separable (finset.prod s fun (i : ι) => X - coe_fn C (f i))) {x : ι} {y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := sorry
theorem separable.injective_of_prod_X_sub_C {R : Type u} [comm_ring R] [nontrivial R] {ι : Type u_1} [fintype ι] {f : ι → R} (hfs : separable (finset.prod finset.univ fun (i : ι) => X - coe_fn C (f i))) : function.injective f :=
fun (x y : ι) (hfxy : f x = f y) => separable.inj_of_prod_X_sub_C hfs (finset.mem_univ x) (finset.mem_univ y) hfxy
theorem is_unit_of_self_mul_dvd_separable {R : Type u} [comm_ring R] {p : polynomial R} {q : polynomial R} (hp : separable p) (hq : q * q ∣ p) : is_unit q := sorry
theorem is_local_ring_hom_expand (R : Type u) [integral_domain R] {p : ℕ} (hp : 0 < p) : is_local_ring_hom ↑(expand R p) := sorry
theorem separable_iff_derivative_ne_zero {F : Type u} [field F] {f : polynomial F} (hf : irreducible f) : separable f ↔ coe_fn derivative f ≠ 0 := sorry
theorem separable_map {F : Type u} [field F] {K : Type v} [field K] (f : F →+* K) {p : polynomial F} : separable (map f p) ↔ separable p := sorry
/-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/
def contract {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] (f : polynomial F) : polynomial F :=
finsupp.mk (finset.preimage (finsupp.support f) (fun (_x : ℕ) => _x * p) sorry) (fun (n : ℕ) => coeff f (n * p)) sorry
theorem coeff_contract {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] (f : polynomial F) (n : ℕ) : coeff (contract p f) n = coeff f (n * p) :=
rfl
theorem of_irreducible_expand {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] {f : polynomial F} (hf : irreducible (coe_fn (expand F p) f)) : irreducible f :=
of_irreducible_map (↑(expand F p)) hf
theorem of_irreducible_expand_pow {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] {f : polynomial F} {n : ℕ} : irreducible (coe_fn (expand F (p ^ n)) f) → irreducible f := sorry
theorem expand_char {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] (f : polynomial F) : map (frobenius F p) (coe_fn (expand F p) f) = f ^ p := sorry
theorem map_expand_pow_char {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] (f : polynomial F) (n : ℕ) : map (frobenius F p ^ n) (coe_fn (expand F (p ^ n)) f) = f ^ p ^ n := sorry
theorem expand_contract {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] {f : polynomial F} (hf : coe_fn derivative f = 0) : coe_fn (expand F p) (contract p f) = f := sorry
theorem separable_or {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] {f : polynomial F} (hf : irreducible f) : separable f ∨ ¬separable f ∧ ∃ (g : polynomial F), irreducible g ∧ coe_fn (expand F p) g = f := sorry
theorem exists_separable_of_irreducible {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ), ∃ (g : polynomial F), separable g ∧ coe_fn (expand F (p ^ n)) g = f := sorry
theorem is_unit_or_eq_zero_of_separable_expand {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] {f : polynomial F} (n : ℕ) (hf : separable (coe_fn (expand F (p ^ n)) f)) : is_unit f ∨ n = 0 := sorry
theorem unique_separable_of_irreducible {F : Type u} [field F] (p : ℕ) [hp : fact (nat.prime p)] [HF : char_p F p] {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : separable g₁) (hgf₁ : coe_fn (expand F (p ^ n₁)) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : separable g₂) (hgf₂ : coe_fn (expand F (p ^ n₂)) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := sorry
theorem separable_prod_X_sub_C_iff' {F : Type u} [field F] {ι : Type u_1} {f : ι → F} {s : finset ι} : separable (finset.prod s fun (i : ι) => X - coe_fn C (f i)) ↔ ∀ (x : ι), x ∈ s → ∀ (y : ι), y ∈ s → f x = f y → x = y := sorry
theorem separable_prod_X_sub_C_iff {F : Type u} [field F] {ι : Type u_1} [fintype ι] {f : ι → F} : separable (finset.prod finset.univ fun (i : ι) => X - coe_fn C (f i)) ↔ function.injective f := sorry
theorem not_unit_X_sub_C {F : Type u} [field F] (a : F) : ¬is_unit (X - coe_fn C a) := sorry
theorem nodup_of_separable_prod {F : Type u} [field F] {s : multiset F} (hs : separable (multiset.prod (multiset.map (fun (a : F) => X - coe_fn C a) s))) : multiset.nodup s := sorry
theorem multiplicity_le_one_of_separable {F : Type u} [field F] {p : polynomial F} {q : polynomial F} (hq : ¬is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := sorry
theorem separable.squarefree {F : Type u} [field F] {p : polynomial F} (hsep : separable p) : squarefree p := sorry
/--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/
theorem separable_X_pow_sub_C {F : Type u} [field F] {n : ℕ} (a : F) (hn : ↑n ≠ 0) (ha : a ≠ 0) : separable (X ^ n - coe_fn C a) := sorry
/--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/
theorem squarefree_X_pow_sub_C {F : Type u} [field F] {n : ℕ} (a : F) (hn : ↑n ≠ 0) (ha : a ≠ 0) : squarefree (X ^ n - coe_fn C a) :=
separable.squarefree (separable_X_pow_sub_C a hn ha)
theorem root_multiplicity_le_one_of_separable {F : Type u} [field F] {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := sorry
theorem count_roots_le_one {F : Type u} [field F] {p : polynomial F} (hsep : separable p) (x : F) : multiset.count x (roots p) ≤ 1 := sorry
theorem nodup_roots {F : Type u} [field F] {p : polynomial F} (hsep : separable p) : multiset.nodup (roots p) :=
iff.mpr multiset.nodup_iff_count_le_one (count_roots_le_one hsep)
theorem eq_X_sub_C_of_separable_of_root_eq {F : Type u} [field F] {K : Type v} [field K] {i : F →+* K} {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : separable h) (h_root : eval x h = 0) (h_splits : splits i h) (h_roots : ∀ (y : K), y ∈ roots (map i h) → y = coe_fn i x) : h = coe_fn C (leading_coeff h) * (X - coe_fn C x) := sorry
end polynomial
theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) : polynomial.separable f := sorry
-- TODO: refactor to allow transcendental extensions?
-- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions
/-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff
the minimal polynomial of every `x : K` is separable. -/
def is_separable (F : Type u_1) (K : Type u_2) [field F] [field K] [algebra F K] :=
∀ (x : K), is_integral F x ∧ polynomial.separable (minpoly F x)
protected instance is_separable_self (F : Type u_1) [field F] : is_separable F F :=
fun (x : F) =>
{ left := is_integral_algebra_map,
right :=
eq.mpr (id (Eq._oldrec (Eq.refl (polynomial.separable (minpoly F x))) (minpoly.eq_X_sub_C' x)))
polynomial.separable_X_sub_C }
theorem is_separable_tower_top_of_is_separable (F : Type u_1) (K : Type u_2) (E : Type u_3) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] [h : is_separable F E] : is_separable K E := sorry
theorem is_separable_tower_bot_of_is_separable (F : Type u_1) (K : Type u_2) (E : Type u_3) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] [h : is_separable F E] : is_separable F K := sorry
theorem is_separable.of_alg_hom (F : Type u_1) {E : Type u_3} [field F] [field E] [algebra F E] (E' : Type u_2) [field E'] [algebra F E'] (f : alg_hom F E E') [is_separable F E'] : is_separable F E :=
let _inst : algebra E E' := ring_hom.to_algebra (alg_hom.to_ring_hom f);
is_separable_tower_bot_of_is_separable F E E'
|
3899bf1047fb89b94816123b74a49393eb9f21cf | 7453f4f6074a6d5ce92b7bee2b29c409c061fbef | /src/Interpolation/try-rolle-vec.lean | faeb4e32661da890c228a5c8bbdba46d6abdd9fa | [
"Apache-2.0"
] | permissive | stanescuUW/numerical-analysis-with-Lean | b7b26755b8e925279f3afc1caa16b0666fc77ef8 | 98e6974f8b68cc5232ceff40535d776a33444c73 | refs/heads/master | 1,670,371,433,242 | 1,598,204,960,000 | 1,598,204,960,000 | 282,081,575 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,569 | lean | import analysis.calculus.local_extr
import analysis.calculus.times_cont_diff
import analysis.calculus.iterated_deriv
import tactic data.fin
open set
namespace rolle_general
lemma fin_le_last_val (n : ℕ) : ∀ i : fin (n + 2), i ≤ (n+1) :=
begin
intro i,
have j0 : n + 1 < n + 1 + 1, linarith,
have j0 := @fin.coe_val_of_lt (n+1) (n+1) j0,
have h3 : i.val ≤ n + 1, linarith [i.is_lt],
apply fin.le_iff_val_le_val.mpr,
rw ← j0 at h3,
exact h3,
end
-- Again thanks to Shing Tak Lam
lemma fin_lt_succ (n : ℕ) (i : fin (n + 1)) : (i : fin (n+2)) < (i+1) :=
begin
cases i with i hi,
change (_ : fin (n+2)).val < (_ : fin (n+2)).val,
simp only [fin.coe_mk, coe_coe],
norm_cast,
rw [fin.coe_val_of_lt, fin.coe_val_of_lt]; omega,
end
-- Result below thanks to Sebastien Gouezel
lemma sgouezel
(a b : ℝ) (f : ℝ → ℝ) (n : ℕ) (hf : times_cont_diff_on ℝ (n+1) f (Ioo a b) ) :
times_cont_diff_on ℝ n (deriv f) (Ioo a b) :=
begin
have : deriv f = (λ u : ℝ →L[ℝ] ℝ, u 1) ∘ (fderiv ℝ f), by { ext x, refl },
simp only [this],
have : times_cont_diff_on ℝ n (fderiv ℝ f) (Ioo a b),
{ apply ((times_cont_diff_on_succ_iff_fderiv_within (unique_diff_on_Ioo a b)).1 hf).2.congr,
assume x hx,
calc fderiv ℝ f x = fderiv_within ℝ f univ x : by simp
... = fderiv_within ℝ f (univ ∩ Ioo a b) x :
(fderiv_within_inter (Ioo_mem_nhds hx.1 hx.2) unique_diff_within_at_univ).symm
... = fderiv_within ℝ f (Ioo a b) x : by simp },
apply times_cont_diff.comp_times_cont_diff_on _ this,
exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff
end
#check vector ℝ 2
def myXl : list ℕ := [1,3,5,7,9]
def myX : vector ℕ 1 := vector.insert_nth 2 1 vector.nil -- inserts value 2 at position 0?
#eval myX.nth 0
def myX2 := vector.insert_nth 7 0 myX -- inserts value, how ???
def myX3 := vector.insert_nth 3 2 myX -- inserts value ???
#eval myX2.nth 0
#eval myX2.nth 1
#eval myX3.nth 0
#eval myX3.nth 1
#eval myX3.nth 2
#check myX2.nth
#check myX.nth
#check list
#check vector.mem_iff_nth
#check vector.nth_mem
def myL : list ℕ := [3, 5]
#check myL.length
def mX : vector ℕ 2 := ⟨ myL, rfl ⟩
#check mX.nth 0
#eval mX.nth 0
#eval mX.nth 1
def strict_mono_vec {n : ℕ} (x : vector ℝ n) := ∀ (i j : fin n), i < j → x.nth i < x.nth j
lemma one_step (n : ℕ) (x : vector ℝ (n+2)) (hx : strict_mono_vec x) :
∀ (f : ℝ → ℝ), continuous_on f ( Icc (x.nth 0) (x.nth (n+1)) ) →
(∀ i, f (x.nth i) = 0) →
∃ (xp : vector ℝ (n+1)), strict_mono_vec xp ∧
∀ (i : fin (n+1)), xp.nth i ∈ ( Ioo (x.nth 0) (x.nth (n+1)) ) ∧ deriv f (xp.nth i) = 0 :=
begin
intros f hf hxi,
have h1 : ∀ (i : fin (n+1)), ∃ y ∈ (Ioo (x i) (x (i+1))), deriv f y = 0,
intro i,
apply exists_deriv_eq_zero,
-- show x i < x (i+1)
exact hx (fin_lt_succ n i),
-- show f continuous on Icc (x i) (x (i+1))
have h02 : Icc (x i) (x (i+1)) ⊆ Icc (x 0) (x (n+1)),
intros z hz,
cases hz with hz1 hz2,
split,
have g3 := (strict_mono.le_iff_le hx).mpr (fin.zero_le i),
linarith, -- use strict_mono x
have h020 := fin_le_last_val n (i+1),
have g3 := (strict_mono.le_iff_le hx).mpr h020,
linarith,
exact continuous_on.mono hf h02,
-- show f (x i) = f (x (i+1))
rw [hxi i, hxi (i+1)],
-- this is just normal Rolle, exists_deriv_eq_zero
choose xp hxp using h1,
use xp, split,
intros i j hij,
cases (hxp i).1 with hi1 hi2, cases (hxp j).1 with hj1 hj2,
rcases lt_trichotomy ((i+1) : fin (n+2) ) (j : fin (n+2)) with h1|h2|h3,
-- case (i+1) < j
have hii1 := hx h1, linarith,
-- case (i+1) = j
rw h2 at hi2, linarith,
-- case j < (i+1) is not possible because i < j
exfalso,
have h3n : (j : ℕ) < ((i + 1) : ℕ), {
norm_num at h3,
change (j.val : fin (n+2)).val < (i.val.succ : fin (n+2)).val at h3,
rwa [fin.coe_val_of_lt (show j.1 < n + 2, by linarith [j.2]),
fin.coe_val_of_lt (show i.1 + 1 < n + 2, by linarith [i.2])] at h3,
},
have gf1 := nat.lt_succ_iff.mp h3n,
--strange as it looks, linarith still needs this
have hijn : (i : ℕ) < (j : ℕ), exact hij,
linarith,
intro i, split,
swap, exact (hxp i).2,
have g0 := (hxp i).1,
split,
cases g0 with g01 g02,
have g2 := (strict_mono.le_iff_le hx).mpr (@fin.zero_le (n+1) i),
linarith,
cases g0 with g01 g02,
have g03 := (strict_mono.le_iff_le hx).mpr (fin_le_last_val n (i+1)),
linarith, done
end
theorem general_rolle (n : ℕ) (x : fin (n+2) → ℝ) (hx : strict_mono x) :
∀ (f : ℝ → ℝ), times_cont_diff_on ℝ n f ( Icc (x 0) (x (n+1)) ) →
(∀ i, f (x i) = 0) →
∃ c ∈ Ioo (x 0) (x (n+1)), iterated_deriv (n+1) f c = 0 :=
begin
induction n with d hd,
{ -- base case, just plain Rolle `exists_deriv_eq_zero`
intros f hf hi,
norm_cast at hf,
rw times_cont_diff_on_zero at hf,
have h1 : 0 < 1, linarith,
-- The above was needed because linarith fails on next one:
have h2 : (0 : fin 2) < (1 : fin 2), exact h1, -- linarith fails !!!???
have hx01 := hx h2, clear h1, clear h2,
have heq : f (x 0) = f (x 1), rw [hi 0, hi 1],
have h5 := exists_deriv_eq_zero f hx01 hf heq,
rw iterated_deriv_one,
have g : (((0 : ℕ) + 1) : fin 2) = 1, norm_cast,
rw g,
exact h5,
},
{ -- induction step
-- the derivative is in Cᵈ
intros f hf hi,
have hfc := times_cont_diff_on.continuous_on hf,
have H := one_step d.succ x hx f hfc hi,
cases H with xp hxp, cases hxp with hxpx hxpi,
set g := deriv f with hg,
have hf1 : times_cont_diff_on ℝ d.succ f (Ioo (x 0) (x (d.succ+1))),
have hf11 : Ioo (x 0) (x (d.succ + 1)) ⊆ Icc (x 0) (x (d.succ + 1)),
exact Ioo_subset_Icc_self,
exact times_cont_diff_on.mono hf hf11,
have hder0 := sgouezel (x 0) (x (d.succ +1)) f d hf1,
have hder : times_cont_diff_on ℝ d g (Icc (xp 0) (xp (d+1))),
have hdr0 : Icc (xp 0) (xp (d+1)) ⊆ Ioo (x 0) (x (d.succ + 1)),
intros z hz,
cases hz with hz1 hz2,
split,
cases (hxpi 0).1 with h0z0 h0z1, linarith,
cases (hxpi d.succ).1 with hdz0 hdz1,
norm_cast at hz2, linarith,
exact times_cont_diff_on.mono hder0 hdr0,
have hdg := hd xp hxpx g hder, clear hd,
have H1 : ∀ i, g (xp i) = 0,
intro i,
exact (hxpi i).2,
have G := hdg H1,
have K : iterated_deriv (d.succ + 1) f = iterated_deriv d.succ g,
apply iterated_deriv_succ',
rw ← K at G,
cases G with c hc,
use c,
cases hc with hc1 hc2,
split, swap, exact hc2,
have hxp0 := (hxpi 0).1, cases hxp0 with hxp01 hxp02,
cases hc1 with hc10 hc11,
split, linarith,
have hxp1 := (hxpi d.succ).1, cases hxp1 with hxp11 hxp12,
have hxpeq0 : d+1 = d.succ, rw nat.succ_eq_add_one,
have hxpeq1 : ((d+1) : fin (d.succ + 1) ) = d.succ,
norm_cast,
rw hxpeq1 at hc11,
linarith,
},
done
end
end rolle_general
|
bca656cc9d4d503507e4128f63d15e4c0a5d929a | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/algebra/order.lean | 506a14dc4be6cef2bcac03122c587e541c35331b | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,569 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: algebra.order
Author: Jeremy Avigad
Various types of orders. We develop weak orders "≤" and strict orders "<" separately. We also
consider structures with both, where the two are related by
x < y ↔ (x ≤ y ∧ x ≠ y) (order_pair)
x ≤ y ↔ (x < y ∨ x = y) (strong_order_pair)
These might not hold constructively in some applications, but we can define additional structures
with both < and ≤ as needed.
-/
import logic.eq logic.connectives
open eq eq.ops
namespace algebra
variable {A : Type}
/- overloaded symbols -/
structure has_le [class] (A : Type) :=
(le : A → A → Prop)
structure has_lt [class] (A : Type) :=
(lt : A → A → Prop)
infixl `<=` := has_le.le
infixl `≤` := has_le.le
infixl `<` := has_lt.lt
definition has_le.ge [reducible] {A : Type} [s : has_le A] (a b : A) := b ≤ a
notation a ≥ b := has_le.ge a b
notation a >= b := has_le.ge a b
definition has_lt.gt [reducible] {A : Type} [s : has_lt A] (a b : A) := b < a
notation a > b := has_lt.gt a b
/- weak orders -/
structure weak_order [class] (A : Type) extends has_le A :=
(le_refl : ∀a, le a a)
(le_trans : ∀a b c, le a b → le b c → le a c)
(le_antisymm : ∀a b, le a b → le b a → a = b)
section
variable [s : weak_order A]
include s
theorem le.refl (a : A) : a ≤ a := !weak_order.le_refl
theorem le.trans {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans
calc_trans le.trans
theorem ge.trans {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1
calc_trans ge.trans
theorem le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm
end
structure linear_weak_order [class] (A : Type) extends weak_order A :=
(le_total : ∀a b, le a b ∨ le b a)
theorem le.total [s : linear_weak_order A] (a b : A) : a ≤ b ∨ b ≤ a :=
!linear_weak_order.le_total
/- strict orders -/
structure strict_order [class] (A : Type) extends has_lt A :=
(lt_irrefl : ∀a, ¬ lt a a)
(lt_trans : ∀a b c, lt a b → lt b c → lt a c)
section
variable [s : strict_order A]
include s
theorem lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl
theorem lt.trans {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans
calc_trans lt.trans
theorem gt.trans {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1
calc_trans gt.trans
theorem ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b :=
assume eq_ab : a = b,
show false, from lt.irrefl b (eq_ab ▸ lt_ab)
theorem ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b :=
ne.symm (ne_of_lt gt_ab)
theorem lt.asymm {a b : A} (H : a < b) : ¬ b < a :=
assume H1 : b < a, lt.irrefl _ (lt.trans H H1)
end
/- well-founded orders -/
-- TODO: do these duplicate what Leo has done? if so, eliminate
structure wf_strict_order [class] (A : Type) extends strict_order A :=
(wf_rec : ∀P : A → Type, (∀x, (∀y, lt y x → P y) → P x) → ∀x, P x)
definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type}
(x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x :=
wf_strict_order.wf_rec P H x
theorem wf.ind_on.{u v} {A : Type.{u}} [s : wf_strict_order.{u 0} A] {P : A → Prop}
(x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x :=
wf.rec_on x H
/- structures with a weak and a strict order -/
structure order_pair [class] (A : Type) extends weak_order A, has_lt A :=
(lt_iff_le_and_ne : ∀a b, lt a b ↔ (le a b ∧ a ≠ b))
section
variable [s : order_pair A]
variables {a b c : A}
include s
theorem lt_iff_le_and_ne : a < b ↔ (a ≤ b ∧ a ≠ b) :=
!order_pair.lt_iff_le_and_ne
theorem le_of_lt (H : a < b) : a ≤ b :=
and.elim_left (iff.mp lt_iff_le_and_ne H)
theorem lt_of_le_of_ne (H1 : a ≤ b) (H2 : a ≠ b) : a < b :=
iff.mp (iff.symm lt_iff_le_and_ne) (and.intro H1 H2)
private theorem lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a :=
assume H : a < a,
have H1 : a ≠ a, from and.elim_right (iff.mp !lt_iff_le_and_ne H),
H1 rfl
private theorem lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c :=
have le_ab : a ≤ b, from le_of_lt lt_ab,
have le_bc : b ≤ c, from le_of_lt lt_bc,
have le_ac : a ≤ c, from le.trans le_ab le_bc,
have ne_ac : a ≠ c, from
assume eq_ac : a = c,
have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc,
have eq_ab : a = b, from le.antisymm le_ab le_ba,
have ne_ab : a ≠ b, from and.elim_right (iff.mp lt_iff_le_and_ne lt_ab),
ne_ab eq_ab,
show a < c, from lt_of_le_of_ne le_ac ne_ac
definition order_pair.to_strict_order [instance] [coercion] [reducible] : strict_order A :=
⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄
theorem lt_of_lt_of_le : a < b → b ≤ c → a < c :=
assume lt_ab : a < b,
assume le_bc : b ≤ c,
have le_ac : a ≤ c, from le.trans (le_of_lt lt_ab) le_bc,
have ne_ac : a ≠ c, from
assume eq_ac : a = c,
have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc,
have eq_ab : a = b, from le.antisymm (le_of_lt lt_ab) le_ba,
show false, from ne_of_lt lt_ab eq_ab,
show a < c, from lt_of_le_of_ne le_ac ne_ac
theorem lt_of_le_of_lt : a ≤ b → b < c → a < c :=
assume le_ab : a ≤ b,
assume lt_bc : b < c,
have le_ac : a ≤ c, from le.trans le_ab (le_of_lt lt_bc),
have ne_ac : a ≠ c, from
assume eq_ac : a = c,
have le_cb : c ≤ b, from eq_ac ▸ le_ab,
have eq_bc : b = c, from le.antisymm (le_of_lt lt_bc) le_cb,
show false, from ne_of_lt lt_bc eq_bc,
show a < c, from lt_of_le_of_ne le_ac ne_ac
theorem gt_of_gt_of_ge (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1
theorem gt_of_ge_of_gt (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1
calc_trans lt_of_lt_of_le
calc_trans lt_of_le_of_lt
calc_trans gt_of_gt_of_ge
calc_trans gt_of_ge_of_gt
theorem not_le_of_lt (H : a < b) : ¬ b ≤ a :=
assume H1 : b ≤ a,
lt.irrefl _ (lt_of_lt_of_le H H1)
theorem not_lt_of_le (H : a ≤ b) : ¬ b < a :=
assume H1 : b < a,
lt.irrefl _ (lt_of_le_of_lt H H1)
end
structure strong_order_pair [class] (A : Type) extends order_pair A :=
(le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b)
theorem le_iff_lt_or_eq [s : strong_order_pair A] {a b : A} : a ≤ b ↔ a < b ∨ a = b :=
!strong_order_pair.le_iff_lt_or_eq
theorem lt_or_eq_of_le [s : strong_order_pair A] {a b : A} (le_ab : a ≤ b) : a < b ∨ a = b :=
iff.mp le_iff_lt_or_eq le_ab
-- We can also construct a strong order pair by defining a strict order, and then defining
-- x ≤ y ↔ x < y ∨ x = y
structure strict_order_with_le [class] (A : Type) extends strict_order A, has_le A :=
(le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b)
private theorem le_refl (s : strict_order_with_le A) (a : A) : a ≤ a :=
iff.mp (iff.symm !strict_order_with_le.le_iff_lt_or_eq) (or.intro_right _ rfl)
private theorem le_trans (s : strict_order_with_le A) (a b c : A) (le_ab : a ≤ b) (le_bc : b ≤ c) : a ≤ c :=
or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab)
(assume lt_ab : a < b,
or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_bc)
(assume lt_bc : b < c,
iff.elim_right
!strict_order_with_le.le_iff_lt_or_eq (or.intro_left _ (lt.trans lt_ab lt_bc)))
(assume eq_bc : b = c, eq_bc ▸ le_ab))
(assume eq_ab : a = b,
eq_ab⁻¹ ▸ le_bc)
private theorem le_antisymm (s : strict_order_with_le A) (a b : A) (le_ab : a ≤ b) (le_ba : b ≤ a) : a = b :=
or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab)
(assume lt_ab : a < b,
or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ba)
(assume lt_ba : b < a, absurd (lt.trans lt_ab lt_ba) (lt.irrefl a))
(assume eq_ba : b = a, eq_ba⁻¹))
(assume eq_ab : a = b, eq_ab)
private theorem lt_iff_le_ne (s : strict_order_with_le A) (a b : A) : a < b ↔ a ≤ b ∧ a ≠ b :=
iff.intro
(assume lt_ab : a < b,
have le_ab : a ≤ b, from
iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (or.intro_left _ lt_ab),
show a ≤ b ∧ a ≠ b, from and.intro le_ab (ne_of_lt lt_ab))
(assume H : a ≤ b ∧ a ≠ b,
have H1 : a < b ∨ a = b, from
iff.mp !strict_order_with_le.le_iff_lt_or_eq (and.elim_left H),
show a < b, from or_resolve_left H1 (and.elim_right H))
definition strict_order_with_le.to_order_pair [instance] [coercion] [reducible] [s : strict_order_with_le A] :
strong_order_pair A :=
⦃ strong_order_pair, s,
le_refl := le_refl s,
le_trans := le_trans s,
le_antisymm := le_antisymm s,
lt_iff_le_and_ne := lt_iff_le_ne s ⦄
/- linear orders -/
structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A
structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A,
linear_weak_order A
section
variable [s : linear_strong_order_pair A]
variables (a b c : A)
include s
theorem lt.trichotomy : a < b ∨ a = b ∨ b < a :=
or.elim (le.total a b)
(assume H : a ≤ b,
or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inl H1) (assume H1, or.inr (or.inl H1)))
(assume H : b ≤ a,
or.elim (iff.mp !le_iff_lt_or_eq H)
(assume H1, or.inr (or.inr H1))
(assume H1, or.inr (or.inl (H1⁻¹))))
theorem lt.by_cases {a b : A} {P : Prop}
(H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P :=
or.elim !lt.trichotomy
(assume H, H1 H)
(assume H, or.elim H (assume H', H2 H') (assume H', H3 H'))
definition linear_strong_order_pair.to_linear_order_pair [instance] [coercion] [reducible]
: linear_order_pair A :=
⦃ linear_order_pair, s ⦄
theorem le_of_not_lt {a b : A} (H : ¬ a < b) : b ≤ a :=
lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H')
theorem lt_of_not_le {a b : A} (H : ¬ a ≤ b) : b < a :=
lt.by_cases
(assume H', absurd (le_of_lt H') H)
(assume H', absurd (H' ▸ !le.refl) H)
(assume H', H')
theorem lt_or_ge : a < b ∨ a ≥ b :=
lt.by_cases
(assume H1 : a < b, or.inl H1)
(assume H1 : a = b, or.inr (H1 ▸ le.refl a))
(assume H1 : a > b, or.inr (le_of_lt H1))
theorem le_or_gt : a ≤ b ∨ a > b :=
!or.swap (lt_or_ge b a)
theorem lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ∨ a > b :=
lt.by_cases (assume H1, or.inl H1) (assume H1, absurd H1 H) (assume H1, or.inr H1)
end
structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A :=
(decidable_lt : decidable_rel lt)
section
variable [s : decidable_linear_order A]
variables {a b c d : A}
include s
open decidable
definition decidable_lt [instance] : decidable (a < b) :=
@decidable_linear_order.decidable_lt _ _ _ _
definition decidable_le [instance] : decidable (a ≤ b) :=
by_cases
(assume H : a < b, inl (le_of_lt H))
(assume H : ¬ a < b,
have H1 : b ≤ a, from le_of_not_lt H,
by_cases
(assume H2 : b < a, inr (not_le_of_lt H2))
(assume H2 : ¬ b < a, inl (le_of_not_lt H2)))
definition decidable_eq [instance] : decidable (a = b) :=
by_cases
(assume H : a ≤ b,
by_cases
(assume H1 : b ≤ a, inl (le.antisymm H H1))
(assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a))))
(assume H : ¬ a ≤ b,
(inr (assume H1 : a = b, H (H1 ▸ !le.refl))))
-- testing equality first may result in more definitional equalities
definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B :=
if a = b then t_eq else (if a < b then t_lt else t_gt)
theorem lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) :
lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H
theorem lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) :
lt.cases a b t_lt t_eq t_gt = t_lt :=
if_neg (ne_of_lt H) ⬝ if_pos H
theorem lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) :
lt.cases a b t_lt t_eq t_gt = t_gt :=
if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H)
end
end algebra
/-
For reference, these are all the transitivity rules defined in this file:
calc_trans le.trans
calc_trans lt.trans
calc_trans lt_of_lt_of_le
calc_trans lt_of_le_of_lt
calc_trans ge.trans
calc_trans gt.trans
calc_trans gt_of_gt_of_ge
calc_trans gt_of_ge_of_gt
-/
|
50271ebe271943350da6704d933244c0cc52cde4 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/analysis/quaternion.lean | 6182fa0b41165a1086c121b52d0401b8eccd2aee | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,358 | 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 data.quaternion
import analysis.normed_space.inner_product
/-!
# Quaternions as a normed algebra
In this file we define the following structures on the space `ℍ := ℍ[ℝ]` of quaternions:
* inner product space;
* normed ring;
* normed space over `ℝ`.
## Notation
The following notation is available with `open_locale quaternion`:
* `ℍ` : quaternions
## Tags
quaternion, normed ring, normed space, normed algebra
-/
localized "notation `ℍ` := quaternion ℝ" in quaternion
open_locale real_inner_product_space
noncomputable theory
namespace quaternion
instance : has_inner ℝ ℍ := ⟨λ a b, (a * b.conj).re⟩
lemma inner_self (a : ℍ) : ⟪a, a⟫ = norm_sq a := rfl
lemma inner_def (a b : ℍ) : ⟪a, b⟫ = (a * b.conj).re := rfl
instance : inner_product_space ℝ ℍ :=
inner_product_space.of_core
{ inner := has_inner.inner,
conj_sym := λ x y, by simp [inner_def, mul_comm],
nonneg_re := λ x, norm_sq_nonneg,
definite := λ x, norm_sq_eq_zero.1,
add_left := λ x y z, by simp only [inner_def, add_mul, add_re],
smul_left := λ x y r, by simp [inner_def] }
lemma norm_sq_eq_norm_sq (a : ℍ) : norm_sq a = ∥a∥ * ∥a∥ :=
by rw [← inner_self, real_inner_self_eq_norm_sq]
instance : norm_one_class ℍ :=
⟨by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_one, real.sqrt_one]⟩
@[simp] lemma norm_mul (a b : ℍ) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
begin
simp only [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_mul],
exact real.sqrt_mul norm_sq_nonneg _
end
@[simp, norm_cast] lemma norm_coe (a : ℝ) : ∥(a : ℍ)∥ = ∥a∥ :=
by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq_coe, real.sqrt_sq_eq_abs, real.norm_eq_abs]
noncomputable instance : normed_ring ℍ :=
{ dist_eq := λ _ _, rfl,
norm_mul := λ a b, (norm_mul a b).le }
noncomputable instance : normed_algebra ℝ ℍ :=
{ norm_algebra_map_eq := norm_coe,
to_algebra := quaternion.algebra }
instance : has_coe ℂ ℍ := ⟨λ z, ⟨z.re, z.im, 0, 0⟩⟩
@[simp, norm_cast] lemma coe_complex_re (z : ℂ) : (z : ℍ).re = z.re := rfl
@[simp, norm_cast] lemma coe_complex_im_i (z : ℂ) : (z : ℍ).im_i = z.im := rfl
@[simp, norm_cast] lemma coe_complex_im_j (z : ℂ) : (z : ℍ).im_j = 0 := rfl
@[simp, norm_cast] lemma coe_complex_im_k (z : ℂ) : (z : ℍ).im_k = 0 := rfl
@[simp, norm_cast] lemma coe_complex_add (z w : ℂ) : ↑(z + w) = (z + w : ℍ) := by ext; simp
@[simp, norm_cast] lemma coe_complex_mul (z w : ℂ) : ↑(z * w) = (z * w : ℍ) := by ext; simp
@[simp, norm_cast] lemma coe_complex_zero : ((0 : ℂ) : ℍ) = 0 := rfl
@[simp, norm_cast] lemma coe_complex_one : ((1 : ℂ) : ℍ) = 1 := rfl
@[simp, norm_cast] lemma coe_real_complex_mul (r : ℝ) (z : ℂ) : (r • z : ℍ) = ↑r * ↑z :=
by ext; simp
@[simp, norm_cast] lemma coe_complex_coe (r : ℝ) : ((r : ℂ) : ℍ) = r := rfl
/-- Coercion `ℂ →ₐ[ℝ] ℍ` as an algebra homomorphism. -/
def of_complex : ℂ →ₐ[ℝ] ℍ :=
{ to_fun := coe,
map_one' := rfl,
map_zero' := rfl,
map_add' := coe_complex_add,
map_mul' := coe_complex_mul,
commutes' := λ x, rfl }
@[simp] lemma coe_of_complex : ⇑of_complex = coe := rfl
end quaternion
|
257dfc842c9c0cfbaeac3a96295e9bd2ca68b5dd | 271e26e338b0c14544a889c31c30b39c989f2e0f | /tests/compiler/rbmap_library.lean | 5cd88a21b03758fc1cd6a47727eee55c4e4d7f16 | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,267 | lean | def check (b : Bool) : IO Unit :=
unless b $ IO.println "ERROR"
def sz {α β : Type} {lt : α → α → Bool} (m : RBMap α β lt) : Nat :=
m.fold (fun sz _ _ => sz+1) 0
def depth {α β : Type} {lt : α → α → Bool} (m : RBMap α β lt) : Nat :=
m.depth Nat.max
def tst1 : IO Unit :=
do let Map := RBMap String Nat (fun a b => a < b);
let m : Map := {};
let m := m.insert "hello" 0;
let m := m.insert "world" 1;
check (m.find "hello" == some 0);
check (m.find "world" == some 1);
let m := m.erase "hello";
check (m.find "hello" == none);
check (m.find "world" == some 1);
pure ()
def tst2 : IO Unit :=
do let Map := RBMap Nat Nat (fun a b => a < b);
let m : Map := {};
let n : Nat := 10000;
let m := n.fold (fun i (m : Map) => m.insert i (i*10)) m;
check (m.all (fun k v => v == k*10));
check (sz m == n);
IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m));
let m := (n/2).fold (fun i (m : Map) => m.erase (2*i)) m;
check (m.all (fun k v => v == k*10));
check (sz m == n / 2);
IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m));
pure ()
abbrev Map := RBMap Nat Nat (fun a b => a < b)
def mkRandMap (max : Nat) : Nat → Map → Array (Nat × Nat) → IO (Map × Array (Nat × Nat))
| 0, m, a => pure (m, a)
| n+1, m, a => do
k ← IO.rand 0 max;
v ← IO.rand 0 max;
if m.find k == none then do
let m := m.insert k v;
let a := a.push (k, v);
mkRandMap n m a
else
mkRandMap n m a
def tst3 (seed : Nat) (n : Nat) (max : Nat) : IO Unit :=
do IO.setRandSeed seed;
(m, a) ← mkRandMap max n {} Array.empty;
check (sz m == a.size);
check (a.all (fun ⟨k, v⟩ => m.find k == some v));
IO.println ("tst3 size: " ++ toString a.size);
let m := a.iterate m (fun i ⟨k, v⟩ m => if i.val % 2 == 0 then m.erase k else m);
check (sz m == a.size / 2);
a.iterateM () (fun i ⟨k, v⟩ _ => when (i.val % 2 == 1) (check (m.find k == some v)));
IO.println ("tst3 after, depth: " ++ toString (depth m) ++ ", size: " ++ toString (sz m));
pure ()
def main (xs : List String) : IO Unit :=
tst1 *> tst2 *>
tst3 1 1000 20000 *>
tst3 2 1000 40000 *>
tst3 3 100 4000 *>
tst3 4 5000 100000 *>
tst3 5 1000 40000 *>
pure ()
|
644ad439fd5bdb260bbd982f166f423173a3d62e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/inner_product_space/euclidean_dist.lean | 55b118bbe129307454d4c6d0d05c4d2c849cc40b | [
"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 | 4,663 | 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.inner_product_space.calculus
import analysis.inner_product_space.pi_L2
/-!
# Euclidean distance on a finite dimensional space
When we define a smooth bump function on a normed space, it is useful to have a smooth distance on
the space. Since the default distance is not guaranteed to be smooth, we define `to_euclidean` to be
an equivalence between a finite dimensional normed space and the standard Euclidean space of the
same dimension. Then we define `euclidean.dist x y = dist (to_euclidean x) (to_euclidean y)` and
provide some definitions (`euclidean.ball`, `euclidean.closed_ball`) and simple lemmas about this
distance. This way we hide the usage of `to_euclidean` behind an API.
-/
open_locale topological_space
open set
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
noncomputable theory
/-- If `E` is a finite dimensional space over `ℝ`, then `to_euclidean` is a continuous `ℝ`-linear
equivalence between `E` and the Euclidean space of the same dimension. -/
def to_euclidean : E ≃L[ℝ] euclidean_space ℝ (fin $ finite_dimensional.finrank ℝ E) :=
continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm
namespace euclidean
/-- If `x` and `y` are two points in a finite dimensional space over `ℝ`, then `euclidean.dist x y`
is the distance between these points in the metric defined by some inner product space structure on
`E`. -/
def dist (x y : E) : ℝ := dist (to_euclidean x) (to_euclidean y)
/-- Closed ball w.r.t. the euclidean distance. -/
def closed_ball (x : E) (r : ℝ) : set E := {y | dist y x ≤ r}
/-- Open ball w.r.t. the euclidean distance. -/
def ball (x : E) (r : ℝ) : set E := {y | dist y x < r}
lemma ball_eq_preimage (x : E) (r : ℝ) :
ball x r = to_euclidean ⁻¹' (metric.ball (to_euclidean x) r) :=
rfl
lemma closed_ball_eq_preimage (x : E) (r : ℝ) :
closed_ball x r = to_euclidean ⁻¹' (metric.closed_ball (to_euclidean x) r) :=
rfl
lemma ball_subset_closed_ball {x : E} {r : ℝ} : ball x r ⊆ closed_ball x r :=
λ y (hy : _ < _), le_of_lt hy
lemma is_open_ball {x : E} {r : ℝ} : is_open (ball x r) :=
metric.is_open_ball.preimage to_euclidean.continuous
lemma mem_ball_self {x : E} {r : ℝ} (hr : 0 < r) : x ∈ ball x r := metric.mem_ball_self hr
lemma closed_ball_eq_image (x : E) (r : ℝ) :
closed_ball x r = to_euclidean.symm '' metric.closed_ball (to_euclidean x) r :=
by rw [to_euclidean.image_symm_eq_preimage, closed_ball_eq_preimage]
lemma is_compact_closed_ball {x : E} {r : ℝ} : is_compact (closed_ball x r) :=
begin
rw closed_ball_eq_image,
exact (is_compact_closed_ball _ _).image to_euclidean.symm.continuous
end
lemma is_closed_closed_ball {x : E} {r : ℝ} : is_closed (closed_ball x r) :=
is_compact_closed_ball.is_closed
lemma closure_ball (x : E) {r : ℝ} (h : r ≠ 0) : closure (ball x r) = closed_ball x r :=
by rw [ball_eq_preimage, ← to_euclidean.preimage_closure, closure_ball (to_euclidean x) h,
closed_ball_eq_preimage]
lemma exists_pos_lt_subset_ball {R : ℝ} {s : set E} {x : E}
(hR : 0 < R) (hs : is_closed s) (h : s ⊆ ball x R) :
∃ r ∈ Ioo 0 R, s ⊆ ball x r :=
begin
rw [ball_eq_preimage, ← image_subset_iff] at h,
rcases exists_pos_lt_subset_ball hR (to_euclidean.is_closed_image.2 hs) h with ⟨r, hr, hsr⟩,
exact ⟨r, hr, image_subset_iff.1 hsr⟩
end
lemma nhds_basis_closed_ball {x : E} :
(𝓝 x).has_basis (λ r : ℝ, 0 < r) (closed_ball x) :=
begin
rw [to_euclidean.to_homeomorph.nhds_eq_comap],
exact metric.nhds_basis_closed_ball.comap _
end
lemma closed_ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : closed_ball x r ∈ 𝓝 x :=
nhds_basis_closed_ball.mem_of_mem hr
lemma nhds_basis_ball {x : E} :
(𝓝 x).has_basis (λ r : ℝ, 0 < r) (ball x) :=
begin
rw [to_euclidean.to_homeomorph.nhds_eq_comap],
exact metric.nhds_basis_ball.comap _
end
lemma ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : ball x r ∈ 𝓝 x :=
nhds_basis_ball.mem_of_mem hr
end euclidean
variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] {f g : F → E} {n : ℕ∞}
lemma cont_diff.euclidean_dist (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g)
(h : ∀ x, f x ≠ g x) :
cont_diff ℝ n (λ x, euclidean.dist (f x) (g x)) :=
begin
simp only [euclidean.dist],
apply @cont_diff.dist ℝ,
exacts [(@to_euclidean E _ _ _).cont_diff.comp hf,
(@to_euclidean E _ _ _).cont_diff.comp hg, λ x, to_euclidean.injective.ne (h x)]
end
|
db60b93405a51a04fd036b0bf8d384494a81415f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebraic_geometry/sheafed_space_auto.lean | e4f3d1818f2e0b2835c639a150bc1f626b0de38b | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,530 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebraic_geometry.presheafed_space
import Mathlib.topology.sheaves.sheaf
import Mathlib.PostPort
universes v u l u_1
namespace Mathlib
/-!
# Sheafed spaces
Introduces the category of topological spaces equipped with a sheaf (taking values in an
arbitrary target category `C`.)
We further describe how to apply functors and natural transformations to the values of the
presheaves.
-/
namespace algebraic_geometry
/-- A `SheafedSpace C` is a topological space equipped with a sheaf of `C`s. -/
structure SheafedSpace (C : Type u) [category_theory.category C]
[category_theory.limits.has_products C]
extends PresheafedSpace C where
sheaf_condition : Top.presheaf.sheaf_condition (PresheafedSpace.presheaf _to_PresheafedSpace)
namespace SheafedSpace
protected instance coe_carrier {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] : has_coe (SheafedSpace C) Top :=
has_coe.mk fun (X : SheafedSpace C) => PresheafedSpace.carrier (to_PresheafedSpace X)
/-- Extract the `sheaf C (X : Top)` from a `SheafedSpace C`. -/
def sheaf {C : Type u} [category_theory.category C] [category_theory.limits.has_products C]
(X : SheafedSpace C) : Top.sheaf C ↑X :=
Top.sheaf.mk (PresheafedSpace.presheaf (to_PresheafedSpace X)) (sheaf_condition X)
@[simp] theorem as_coe {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (X : SheafedSpace C) :
PresheafedSpace.carrier (to_PresheafedSpace X) = ↑X :=
rfl
@[simp] theorem mk_coe {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (carrier : Top) (presheaf : Top.presheaf C carrier)
(h :
Top.presheaf.sheaf_condition
(PresheafedSpace.presheaf (PresheafedSpace.mk carrier presheaf))) :
↑(mk (PresheafedSpace.mk carrier presheaf) h) = carrier :=
rfl
protected instance topological_space {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (X : SheafedSpace C) : topological_space ↥X :=
category_theory.bundled.str (PresheafedSpace.carrier (to_PresheafedSpace X))
/-- The trivial `punit` valued sheaf on any topological space. -/
def punit (X : Top) : SheafedSpace (category_theory.discrete PUnit) :=
mk
(PresheafedSpace.mk (PresheafedSpace.carrier (PresheafedSpace.const X PUnit.unit))
(PresheafedSpace.presheaf (PresheafedSpace.const X PUnit.unit)))
(Top.presheaf.sheaf_condition_punit
(PresheafedSpace.presheaf
(PresheafedSpace.mk (PresheafedSpace.carrier (PresheafedSpace.const X PUnit.unit))
(PresheafedSpace.presheaf (PresheafedSpace.const X PUnit.unit)))))
protected instance inhabited : Inhabited (SheafedSpace (category_theory.discrete PUnit)) :=
{ default := punit (Top.of pempty) }
protected instance category_theory.category {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] : category_theory.category (SheafedSpace C) :=
(fun
(this :
category_theory.category
(category_theory.induced_category (PresheafedSpace C) to_PresheafedSpace)) =>
this)
(category_theory.induced_category.category to_PresheafedSpace)
/-- Forgetting the sheaf condition is a functor from `SheafedSpace C` to `PresheafedSpace C`. -/
def forget_to_PresheafedSpace {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] : SheafedSpace C ⥤ PresheafedSpace C :=
category_theory.induced_functor to_PresheafedSpace
@[simp] theorem id_base {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (X : SheafedSpace C) : PresheafedSpace.hom.base 𝟙 = 𝟙 :=
rfl
theorem id_c {C : Type u} [category_theory.category C] [category_theory.limits.has_products C]
(X : SheafedSpace C) :
PresheafedSpace.hom.c 𝟙 =
category_theory.iso.inv
(category_theory.functor.left_unitor
(PresheafedSpace.presheaf (to_PresheafedSpace X))) ≫
category_theory.whisker_right
(category_theory.nat_trans.op
(category_theory.iso.hom
(topological_space.opens.map_id (PresheafedSpace.carrier (to_PresheafedSpace X)))))
(PresheafedSpace.presheaf (to_PresheafedSpace X)) :=
rfl
@[simp] theorem id_c_app {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (X : SheafedSpace C)
(U : topological_space.opens ↥(PresheafedSpace.carrier (to_PresheafedSpace X))ᵒᵖ) :
category_theory.nat_trans.app (PresheafedSpace.hom.c 𝟙) U =
category_theory.eq_to_hom
(opposite.op_induction
(fun (U : topological_space.opens ↥(PresheafedSpace.carrier (to_PresheafedSpace X))) =>
subtype.cases_on U
fun (U_val : set ↥(PresheafedSpace.carrier (to_PresheafedSpace X)))
(U_property : is_open U_val) =>
Eq.refl
(category_theory.functor.obj (PresheafedSpace.presheaf (to_PresheafedSpace X))
(opposite.op { val := U_val, property := U_property })))
U) :=
sorry
@[simp] theorem comp_base {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] {X : SheafedSpace C} {Y : SheafedSpace C}
{Z : SheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) :
PresheafedSpace.hom.base (f ≫ g) = PresheafedSpace.hom.base f ≫ PresheafedSpace.hom.base g :=
rfl
@[simp] theorem comp_c_app {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] {X : SheafedSpace C} {Y : SheafedSpace C}
{Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z)
(U : topological_space.opens ↥(PresheafedSpace.carrier (to_PresheafedSpace Z))ᵒᵖ) :
category_theory.nat_trans.app (PresheafedSpace.hom.c (α ≫ β)) U =
category_theory.nat_trans.app (PresheafedSpace.hom.c β) U ≫
category_theory.nat_trans.app (PresheafedSpace.hom.c α)
(opposite.op
(category_theory.functor.obj
(topological_space.opens.map (PresheafedSpace.hom.base β)) (opposite.unop U))) ≫
category_theory.nat_trans.app
(category_theory.iso.inv
(Top.presheaf.pushforward.comp (PresheafedSpace.presheaf (to_PresheafedSpace X))
(PresheafedSpace.hom.base α) (PresheafedSpace.hom.base β)))
U :=
rfl
/-- The forgetful functor from `SheafedSpace` to `Top`. -/
def forget (C : Type u) [category_theory.category C] [category_theory.limits.has_products C] :
SheafedSpace C ⥤ Top :=
category_theory.functor.mk (fun (X : SheafedSpace C) => ↑X)
fun (X Y : SheafedSpace C) (f : X ⟶ Y) => PresheafedSpace.hom.base f
/--
The restriction of a sheafed space along an open embedding into the space.
-/
def restrict {C : Type u} [category_theory.category C] [category_theory.limits.has_products C]
{U : Top} (X : SheafedSpace C) (f : U ⟶ ↑X) (h : open_embedding ⇑f) : SheafedSpace C :=
sorry
/--
The global sections, notated Gamma.
-/
def Γ {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] :
SheafedSpace Cᵒᵖ ⥤ C :=
category_theory.functor.op forget_to_PresheafedSpace ⋙ PresheafedSpace.Γ
theorem Γ_def {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] :
Γ = category_theory.functor.op forget_to_PresheafedSpace ⋙ PresheafedSpace.Γ :=
rfl
@[simp] theorem Γ_obj {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] (X : SheafedSpace Cᵒᵖ) :
category_theory.functor.obj Γ X =
category_theory.functor.obj
(PresheafedSpace.presheaf (to_PresheafedSpace (opposite.unop X))) (opposite.op ⊤) :=
rfl
theorem Γ_obj_op {C : Type u} [category_theory.category C] [category_theory.limits.has_products C]
(X : SheafedSpace C) :
category_theory.functor.obj Γ (opposite.op X) =
category_theory.functor.obj (PresheafedSpace.presheaf (to_PresheafedSpace X))
(opposite.op ⊤) :=
rfl
@[simp] theorem Γ_map {C : Type u} [category_theory.category C]
[category_theory.limits.has_products C] {X : SheafedSpace Cᵒᵖ} {Y : SheafedSpace Cᵒᵖ}
(f : X ⟶ Y) :
category_theory.functor.map Γ f =
category_theory.nat_trans.app (PresheafedSpace.hom.c (category_theory.has_hom.hom.unop f))
(opposite.op ⊤) ≫
category_theory.functor.map
(PresheafedSpace.presheaf (to_PresheafedSpace (opposite.unop Y)))
(category_theory.has_hom.hom.op
(topological_space.opens.le_map_top
(PresheafedSpace.hom.base (category_theory.has_hom.hom.unop f)) ⊤)) :=
rfl
theorem Γ_map_op {C : Type u} [category_theory.category C] [category_theory.limits.has_products C]
{X : SheafedSpace C} {Y : SheafedSpace C} (f : X ⟶ Y) :
category_theory.functor.map Γ (category_theory.has_hom.hom.op f) =
category_theory.nat_trans.app (PresheafedSpace.hom.c f) (opposite.op ⊤) ≫
category_theory.functor.map (PresheafedSpace.presheaf (to_PresheafedSpace X))
(category_theory.has_hom.hom.op
(topological_space.opens.le_map_top (PresheafedSpace.hom.base f) ⊤)) :=
rfl
end Mathlib |
fda9bacbc7a254a584e07c4a51bed205c5628aa4 | da3a76c514d38801bae19e8a9e496dc31f8e5866 | /library/tools/debugger/util.lean | 31880327810d76d2cdbb64476160db8b07bbba88 | [
"Apache-2.0"
] | permissive | cipher1024/lean | 270c1ac5781e6aee12f5c8d720d267563a164beb | f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a | refs/heads/master | 1,611,223,459,029 | 1,487,566,573,000 | 1,487,566,573,000 | 83,356,543 | 0 | 0 | null | 1,488,229,336,000 | 1,488,229,336,000 | null | UTF-8 | Lean | false | false | 4,030 | 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
-/
namespace debugger
def is_space (c : char) : bool :=
if c = #" " ∨ c = char.of_nat 11 ∨ c = #"\n" then tt else ff
def split_core : string → string → list string
| (c::cs) [] :=
if is_space c then split_core cs [] else split_core cs [c]
| (c::cs) r :=
if is_space c then r^.reverse :: split_core cs [] else split_core cs (c::r)
| [] [] := []
| [] r := [r^.reverse]
def split (s : string) : list string :=
(split_core s [])^.reverse
def to_qualified_name_core : string → string → name
| [] r := if r = "" then name.anonymous else mk_simple_name r^.reverse
| (c::cs) r :=
if is_space c then to_qualified_name_core cs r
else if c = #"." then
if r = "" then to_qualified_name_core cs []
else name.mk_string r^.reverse (to_qualified_name_core cs [])
else to_qualified_name_core cs (c::r)
def to_qualified_name (s : string) : name :=
to_qualified_name_core s []
def olean_to_lean (s : string) :=
list.dropn 5 s ++ "lean"
meta def get_file (fn : name) : vm string :=
do {
d ← vm.get_decl fn,
some n ← return (vm_decl.olean d) | failure,
return (olean_to_lean n)
}
<|>
return "[current file]"
meta def pos_info (fn : name) : vm string :=
do {
d ← vm.get_decl fn,
some (line, col) ← return (vm_decl.pos d) | failure,
file ← get_file fn,
return (file ++ ":" ++ line^.to_string ++ ":" ++ col^.to_string)
}
<|>
return "<position not available>"
meta def show_fn (header : string) (fn : name) (frame : nat) : vm unit :=
do pos ← pos_info fn,
vm.put_str ("[" ++ frame^.to_string ++ "] " ++ header),
if header = "" then return () else vm.put_str " ",
vm.put_str (fn^.to_string ++ " at " ++ pos ++ "\n")
meta def show_curr_fn (header : string) : vm unit :=
do fn ← vm.curr_fn,
sz ← vm.call_stack_size,
show_fn header fn (sz-1)
meta def is_valid_fn_prefix (p : name) : vm bool :=
do env ← vm.get_env,
return $ env^.fold ff (λ d r,
r ||
let n := d^.to_name in
p^.is_prefix_of n)
meta def show_frame (frame_idx : nat) : vm unit :=
do sz ← vm.call_stack_size,
fn ← if frame_idx >= sz then vm.curr_fn else vm.call_stack_fn frame_idx,
show_fn "" fn frame_idx
meta def type_to_string : option expr → nat → vm string
| none i := do
o ← vm.stack_obj i,
match o^.kind with
| vm_obj_kind.simple := return "[tagged value]"
| vm_obj_kind.constructor := return "[constructor]"
| vm_obj_kind.closure := return "[closure]"
| vm_obj_kind.native_closure := return "[native closure]"
| vm_obj_kind.mpz := return "[big num]"
| vm_obj_kind.name := return "name"
| vm_obj_kind.level := return "level"
| vm_obj_kind.expr := return "expr"
| vm_obj_kind.declaration := return "declaration"
| vm_obj_kind.environment := return "environment"
| vm_obj_kind.tactic_state := return "tactic_state"
| vm_obj_kind.format := return "format"
| vm_obj_kind.options := return "options"
| vm_obj_kind.other := return "[other]"
end
| (some type) i := do
fmt ← vm.pp_expr type,
opts ← vm.get_options,
return (fmt^.to_string opts)
meta def show_vars_core : nat → nat → nat → vm unit
| c i e :=
if i = e then return ()
else do
(n, type) ← vm.stack_obj_info i,
type_str ← type_to_string type i,
vm.put_str $ "#" ++ c^.to_string ++ " " ++ n^.to_string ++ " : " ++ type_str ++ "\n",
show_vars_core (c+1) (i+1) e
meta def show_vars (frame : nat) : vm unit :=
do (s, e) ← vm.call_stack_var_range frame,
show_vars_core 0 s e
meta def show_stack_core : nat → vm unit
| 0 := return ()
| (i+1) := do
fn ← vm.call_stack_fn i,
show_fn "" fn i,
show_stack_core i
meta def show_stack : vm unit :=
do sz ← vm.call_stack_size,
show_stack_core sz
end debugger
|
2d33e6cadfd600e2ec55d12f61ba510e9acb3553 | 827a8a5c2041b1d7f55e128581f583dfbd65ecf6 | /topology.lean | 655aa1a804d88d5c9533543c86e30ce2ccfa8016 | [
"Apache-2.0"
] | permissive | fpvandoorn/leansnippets | 6af0499f6f3fd2c07e4b580734d77b67574e7c27 | 601bafbe07e9534af76f60994d6bdf741996ef93 | refs/heads/master | 1,590,063,910,882 | 1,545,093,878,000 | 1,545,093,878,000 | 36,044,957 | 2 | 2 | null | 1,442,619,708,000 | 1,432,256,875,000 | Lean | UTF-8 | Lean | false | false | 1,928 | lean | import classical
open set
section
structure foo.{l} : Type.{l+1} :=
(elim : Type.{l} → Type.{l})
end
structure topology [class] (X : Type) : Type :=
(is_open : set X → Prop)
(empty : is_open (λx, false))
(full : is_open (λx, true))
(union : Π(P : set X → Prop), (Πf, is_open f) → is_open (λx, ∃f, f x ∧ P f))
(intersection : Πf g, is_open f → is_open g → is_open (λx, f x ∧ g x))
namespace topology
variables (X Y : Type) [τ : topology X] [σ : topology Y]
include τ
set_option pp.universes true
theorem foo : is_open (λ(x : X), false) := !empty
-- definition union2 (P : (X → Prop) → Prop) (H : ΠO, P O → is_open O) :=
-- union (λO : subtype P, subtype.elt_of O)
definition interior (A : X → Prop) :=
union (λB : X → Prop, is_open B ∧ B ⊆ A)
include σ
definition continuous (f : X → Y) :=
∀(B : set Y), is_open B → is_open (λx : X, f x ∈ B)
end topology
-- structure topology2 [class] (X : Type) (Y : Type) :=
-- (element : X → Y → Prop)
-- (extensionality : Πy1 y2, (Πx, element x y1 ↔ element x y2) → y1 = y2)
-- (empty : Y)
-- (is_empty : Πx, ¬element x empty)
-- (full : Y)
-- (is_full : Πx, element x full)
-- (union : Π{A : Type}, (A → Y) → Y)
-- (is_union : Πx A (F : A → Y), element x (union F) ↔ ∃a, element x (F a))
-- (intersection : Y → Y → Y)
-- (is_intersection : Πx O1 O2, element x (intersection O1 O2) ↔ element x O1 ∧ element x O2)
-- namespace topology2
-- variables (X Y : Type₊) (τ : topology2 X Y)
-- include τ
-- infix ∈ := element
-- notation 0 := empty
-- notation 1 := full
-- check @union
-- definition union2 (P : Y → Prop) := @union X _ τ _ (λO : subtype P, subtype.elt_of O)
-- set_option pp.universes true
-- check @subtype
-- definition interior (f : X → Prop) :=
-- union (λP : Σ(g : A), ,
-- end topology2
|
21affd8724224bc1daaa175d82b3664976908b63 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/geometry/manifold/charted_space.lean | baa4940a1a64d6e56289f9f03f8e337517d93020 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 48,205 | 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
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 topological_space
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 ` ≫ₕ `:100 := local_homeomorph.trans" in manifold
localized "infixr ` ≫ `:100 := local_equiv.trans" in manifold
/- `simp` looks for subsingleton instances at every call. This turns out to be very
inefficient, especially in `simp`-heavy parts of the library such as the manifold code.
Disable two such instances to speed up things.
NB: this is just a hack. TODO: fix `simp` properly. -/
localized "attribute [-instance] unique.subsingleton pi.subsingleton" 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 = ∅} := disjoint_iff.1 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_eq] 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)`.
-/
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 _ _)
/-- 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
(is_open.mem_nhds (chart_at H x).open_target (mem_chart_target 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
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 : countable s) :
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
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, countable s ∧ (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ :=
countable_cover_nhds_of_sigma_compact
(λ x : M, is_open.mem_nhds (chart_at H x).open_source (mem_chart_source H x)),
exact charted_space.second_countable_of_countable_cover H hsU hsc
end
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
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_inhabited_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 M 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.mem_maximal_atlas_of_mem_atlas [has_groupoid M G]
{e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ G.maximal_atlas M :=
λ 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.mem_maximal_atlas_of_mem_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.mem_maximal_atlas_of_mem_atlas (by simp)
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_inhabited_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
|
9ad7db37158215f24483748d93aace2590d4df40 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/module/big_operators.lean | 2945a10c102fad2b61648930597273ddece3293d | [
"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 | 1,601 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yury Kudryashov, Yaël Dillies
-/
import algebra.module.basic
import group_theory.group_action.big_operators
/-!
# Finite sums over modules over a ring
-/
open_locale big_operators
variables {α β R M ι : Type*}
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M)
lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_list_sum l
lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_multiset_sum l
lemma multiset.sum_smul_sum {s : multiset R} {t : multiset M} :
s.sum • t.sum = ((s ×ˢ t).map $ λ p : R × M, p.fst • p.snd).sum :=
begin
induction s using multiset.induction with a s ih,
{ simp },
{ simp [add_smul, ih, ←multiset.smul_sum] }
end
lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} :
(∑ i in s, f i) • x = (∑ i in s, (f i) • x) :=
((smul_add_hom R M).flip x).map_sum f s
lemma finset.sum_smul_sum {f : α → R} {g : β → M} {s : finset α} {t : finset β} :
(∑ i in s, f i) • (∑ i in t, g i) = ∑ p in s ×ˢ t, f p.fst • g p.snd :=
by { rw [finset.sum_product, finset.sum_smul, finset.sum_congr rfl], intros, rw finset.smul_sum }
end add_comm_monoid
lemma finset.cast_card [comm_semiring R] (s : finset α) : (s.card : R) = ∑ a in s, 1 :=
by rw [finset.sum_const, nat.smul_one_eq_coe]
|
949c97702be85dc220ce2883f79d4db227287e48 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/mv_polynomial/comm_ring.lean | 8fe35f1db0fe8e3ab2054e6b2ad4a17c1f33be61 | [
"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 | 5,008 | 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.variables
/-!
# Multivariate polynomials over a ring
Many results about polynomials hold when the coefficient ring is a commutative semiring.
Some stronger results can be derived when we assume this semiring is a ring.
This file does not define any new operations, but proves some of these stronger results.
## Notation
As in other polynomial files we typically use the notation:
+ `σ : Type*` (indexing the variables)
+ `α : Type*` `[comm_ring α]` (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_ring
variable [comm_ring α]
variables {p q : mv_polynomial σ α}
instance : comm_ring (mv_polynomial σ α) := add_monoid_algebra.comm_ring
instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) :=
by apply is_ring_hom.of_semiring
variables (σ a a')
@[simp] lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _
@[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _
@[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ α) :
coeff m (-p) = -coeff m p := finsupp.neg_apply
@[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply
instance coeff.is_add_group_hom (m : σ →₀ ℕ) :
is_add_group_hom (coeff m : mv_polynomial σ α → α) :=
{ map_add := coeff_add m }
variables {σ} (p)
section degrees
lemma degrees_neg (p : mv_polynomial σ α) : (- p).degrees = p.degrees :=
by rw [degrees, finsupp.support_neg]; refl
lemma degrees_sub (p q : mv_polynomial σ α) :
(p - q).degrees ≤ p.degrees ⊔ q.degrees :=
le_trans (degrees_add p (-q)) $ by rw [degrees_neg]
end degrees
section vars
variables (p q)
@[simp] lemma vars_neg : (-p).vars = p.vars :=
by simp [vars, degrees_neg]
lemma vars_sub_subset : (p - q).vars ⊆ p.vars ∪ q.vars :=
by convert vars_add_subset p (-q) using 2; simp
variables {p q}
@[simp]
lemma vars_sub_of_disjoint (hpq : disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars :=
begin
rw ←vars_neg q at hpq,
convert vars_add_of_disjoint hpq using 2,
simp
end
end vars
section eval₂
variables [comm_ring β]
variables (f : α →+* β) (g : σ → β)
@[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂_hom f g).map_sub _ _
@[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := (eval₂_hom f g).map_neg _
lemma hom_C (f : mv_polynomial σ ℤ → β) [is_ring_hom f] (n : ℤ) : f (C n) = (n : β) :=
((ring_hom.of f).comp (ring_hom.of C)).eq_int_cast n
/-- A ring homomorphism f : Z[X_1, X_2, ...] → R
is determined by the evaluations f(X_1), f(X_2), ... -/
@[simp] lemma eval₂_hom_X {α : Type u} (c : ℤ →+* β)
(f : mv_polynomial α ℤ →+* β) (x : mv_polynomial α ℤ) :
eval₂ c (f ∘ X) x = f x :=
mv_polynomial.induction_on x
(λ n, by { rw [hom_C f, eval₂_C], exact (ring_hom.of c).eq_int_cast n })
(λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm })
(λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm })
/-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as
functions out of the type `σ`, -/
def hom_equiv : (mv_polynomial σ ℤ →+* β) ≃ (σ → β) :=
{ to_fun := λ f, ⇑f ∘ X,
inv_fun := λ f, eval₂_hom (int.cast_ring_hom β) f,
left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _,
right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] }
end eval₂
section total_degree
@[simp] lemma total_degree_neg (a : mv_polynomial σ α) :
(-a).total_degree = a.total_degree :=
by simp only [total_degree, finsupp.support_neg]
lemma total_degree_sub (a b : mv_polynomial σ α) :
(a - b).total_degree ≤ max a.total_degree b.total_degree :=
calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg
... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b)
... = max a.total_degree b.total_degree : by rw total_degree_neg
end total_degree
end comm_ring
end mv_polynomial
|
761b96094e4eb80e3cdebeafd100f7df31461791 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/measure_theory/group/basic.lean | a634469dbf901594417d6054a58c25fd50081dee | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,285 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.integral.lebesgue
import measure_theory.measure.regular
/-!
# Measures on Groups
We develop some properties of measures on (topological) groups
* We define properties on measures: left and right invariant measures.
* We define the measure `μ.inv : A ↦ μ(A⁻¹)` and show that it is right invariant iff
`μ` is left invariant.
-/
noncomputable theory
open_locale ennreal pointwise
open has_inv set function measure_theory.measure
namespace measure_theory
variables {G : Type*}
section
variables [measurable_space G] [has_mul G]
/-- A measure `μ` on a topological group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself.
To left translate sets we use preimage under left multiplication,
since preimages are nicer to work with than images. -/
@[to_additive "A measure on a topological group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself.
To left translate sets we use preimage under left addition,
since preimages are nicer to work with than images."]
def is_mul_left_invariant (μ : set G → ℝ≥0∞) : Prop :=
∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, g * h) ⁻¹' A) = μ A
/-- A measure `μ` on a topological group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself.
To right translate sets we use preimage under right multiplication,
since preimages are nicer to work with than images. -/
@[to_additive "A measure on a topological group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself.
To right translate sets we use preimage under right addition,
since preimages are nicer to work with than images."]
def is_mul_right_invariant (μ : set G → ℝ≥0∞) : Prop :=
∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, h * g) ⁻¹' A) = μ A
end
namespace measure
variables [measurable_space G]
@[to_additive]
lemma map_mul_left_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map ((*) g) μ = μ) ↔ is_mul_left_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_const_mul g) hA]
end
@[to_additive]
lemma map_mul_right_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map (λ h, h * g) μ = μ) ↔ is_mul_right_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_mul_const g) hA]
end
/-- The measure `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/
@[to_additive "The measure `A ↦ μ (- A)`, where `- A` is the pointwise negation of `A`."]
protected def inv [has_inv G] (μ : measure G) : measure G :=
measure.map inv μ
variables [group G] [topological_space G] [topological_group G] [borel_space G]
@[to_additive]
lemma inv_apply (μ : measure G) {s : set G} (hs : measurable_set s) :
μ.inv s = μ s⁻¹ :=
measure.map_apply measurable_inv hs
@[simp, to_additive] protected lemma inv_inv (μ : measure G) : μ.inv.inv = μ :=
begin
ext1 s hs, rw [μ.inv.inv_apply hs, μ.inv_apply, set.inv_inv],
exact measurable_inv hs
end
variables {μ : measure G}
@[to_additive]
instance regular.inv [t2_space G] [regular μ] : regular μ.inv :=
regular.map (homeomorph.inv G)
end measure
section inv
variables [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G]
{μ : measure G}
@[simp, to_additive] lemma regular_inv_iff [t2_space G] : μ.inv.regular ↔ μ.regular :=
begin
split,
{ introI h,
rw ←μ.inv_inv,
exact measure.regular.inv },
{ introI h,
exact measure.regular.inv }
end
@[to_additive]
lemma is_mul_left_invariant.inv (h : is_mul_left_invariant μ) :
is_mul_right_invariant μ.inv :=
begin
intros g A hA,
rw [μ.inv_apply (measurable_mul_const g hA), μ.inv_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr,
intro h,
simp only [mul_inv_rev, comp_app, inv_inv]
end
@[to_additive]
lemma is_mul_right_invariant.inv (h : is_mul_right_invariant μ) : is_mul_left_invariant μ.inv :=
begin
intros g A hA,
rw [μ.inv_apply (measurable_const_mul g hA), μ.inv_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr,
intro h,
simp only [mul_inv_rev, comp_app, inv_inv]
end
@[simp, to_additive]
lemma is_mul_right_invariant_inv : is_mul_right_invariant μ.inv ↔ is_mul_left_invariant μ :=
⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩
@[simp, to_additive]
lemma is_mul_left_invariant_inv : is_mul_left_invariant μ.inv ↔ is_mul_right_invariant μ :=
⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩
end inv
variables [measurable_space G] [topological_space G] [borel_space G] {μ : measure G}
section group
variables [group G] [topological_group G]
/-! Properties of regular left invariant measures -/
@[to_additive]
lemma is_mul_left_invariant.null_iff_empty [regular μ] (h2μ : is_mul_left_invariant μ)
(h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ :=
begin
obtain ⟨K, hK, h2K⟩ := regular.exists_compact_not_null.mpr h3μ,
refine ⟨λ h, _, λ h, by simp [h]⟩,
apply classical.by_contradiction, -- `by_contradiction` is very slow
refine mt (λ h2s, _) h2K,
rw [← ne.def, ne_empty_iff_nonempty] at h2s, cases h2s with y hy,
obtain ⟨t, -, h1t, h2t⟩ := hK.elim_finite_subcover_image
(show ∀ x ∈ @univ G, is_open ((λ y, x * y) ⁻¹' s),
from λ x _, (continuous_mul_left x).is_open_preimage _ hs) _,
{ rw [← nonpos_iff_eq_zero],
refine (measure_mono h2t).trans _,
refine (measure_bUnion_le h1t.countable _).trans_eq _,
simp_rw [h2μ _ hs.measurable_set], rw [h, tsum_zero] },
{ intros x _,
simp_rw [mem_Union, mem_preimage],
use [y * x⁻¹, mem_univ _],
rwa [inv_mul_cancel_right] }
end
@[to_additive]
lemma is_mul_left_invariant.null_iff [regular μ] (h2μ : is_mul_left_invariant μ)
{s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ ∨ μ = 0 :=
begin
by_cases h3μ : μ = 0, { simp [h3μ] },
simp only [h3μ, or_false],
exact h2μ.null_iff_empty h3μ hs,
end
@[to_additive]
lemma is_mul_left_invariant.measure_ne_zero_iff_nonempty [regular μ]
(h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) :
μ s ≠ 0 ↔ s.nonempty :=
by simp_rw [← ne_empty_iff_nonempty, ne.def, h2μ.null_iff_empty h3μ hs]
/-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function
`f` is 0 iff `f` is 0. -/
@[to_additive]
lemma lintegral_eq_zero_of_is_mul_left_invariant [regular μ]
(h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {f : G → ℝ≥0∞} (hf : continuous f) :
∫⁻ x, f x ∂μ = 0 ↔ f = 0 :=
begin
split, swap, { rintro rfl, simp_rw [pi.zero_apply, lintegral_zero] },
intro h, contrapose h,
simp_rw [funext_iff, not_forall, pi.zero_apply] at h, cases h with x hx,
obtain ⟨r, h1r, h2r⟩ : ∃ r : ℝ≥0∞, 0 < r ∧ r < f x :=
exists_between (pos_iff_ne_zero.mpr hx),
have h3r := hf.is_open_preimage (Ioi r) is_open_Ioi,
let s := Ioi r,
rw [← ne.def, ← pos_iff_ne_zero],
have : 0 < r * μ (f ⁻¹' Ioi r),
{ rw ennreal.mul_pos,
refine ⟨h1r, _⟩,
rw [pos_iff_ne_zero, h2μ.measure_ne_zero_iff_nonempty h3μ h3r],
exact ⟨x, h2r⟩ },
refine this.trans_le _,
rw [← set_lintegral_const, ← lintegral_indicator _ h3r.measurable_set],
apply lintegral_mono,
refine indicator_le (λ y, le_of_lt),
end
end group
section integration
variables [group G] [has_continuous_mul G]
open measure
/-- Translating a function by left-multiplication does not change its `lintegral` with respect to
a left-invariant measure. -/
@[to_additive]
lemma lintegral_mul_left_eq_self (hμ : is_mul_left_invariant μ) (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (g * x) ∂μ = ∫⁻ x, f x ∂μ :=
begin
have : measure.map (has_mul.mul g) μ = μ,
{ rw ← map_mul_left_eq_self at hμ,
exact hμ g },
convert (lintegral_map_equiv f (homeomorph.mul_left g).to_measurable_equiv).symm,
simp [this]
end
/-- Translating a function by right-multiplication does not change its `lintegral` with respect to
a right-invariant measure. -/
@[to_additive]
lemma lintegral_mul_right_eq_self (hμ : is_mul_right_invariant μ) (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (x * g) ∂μ = ∫⁻ x, f x ∂μ :=
begin
have : measure.map (homeomorph.mul_right g) μ = μ,
{ rw ← map_mul_right_eq_self at hμ,
exact hμ g },
convert (lintegral_map_equiv f (homeomorph.mul_right g).to_measurable_equiv).symm,
simp [this]
end
end integration
end measure_theory
|
a62836396120f3a440296c04bc2bcc674c43e772 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/ring/divisibility.lean | c85a65b518d8a19ef78e4343c16342b05993e716 | [
"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 | 4,093 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland
-/
import algebra.divisibility.basic
import algebra.ring.defs
/-!
# Lemmas about divisibility in rings
-/
variables {α β : Type*}
section distrib_semigroup
variables [has_add α] [semigroup α]
theorem dvd_add [left_distrib_class α] {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he])))
end distrib_semigroup
@[simp] theorem two_dvd_bit0 [semiring α] {a : α} : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩
section non_unital_comm_semiring
variables [non_unital_comm_semiring α] [non_unital_comm_semiring β] {a b c : α}
lemma has_dvd.dvd.linear_comb {d x y : α} (hdx : d ∣ x) (hdy : d ∣ y) (a b : α) :
d ∣ (a * x + b * y) :=
dvd_add (hdx.mul_left a) (hdy.mul_left b)
end non_unital_comm_semiring
section semigroup
variables [semigroup α] [has_distrib_neg α] {a b c : α}
theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) :=
let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩
theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) :=
let t := dvd_neg_of_dvd h in by rwa neg_neg at t
/-- An element a of a semigroup with a distributive negation divides the negation of an element b
iff a divides b. -/
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b :=
let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩
theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b :=
let t := neg_dvd_of_dvd h in by rwa neg_neg at t
/-- The negation of an element a of a semigroup with a distributive negation divides
another element b iff a divides b. -/
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
end semigroup
section non_unital_ring
variables [non_unital_ring α] {a b c : α}
theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c :=
by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) }
theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c :=
⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩
theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c :=
by rw add_comm; exact dvd_add_iff_left h
/-- If an element a divides another element c in a commutative ring, a divides the sum of another
element b with c iff a divides b. -/
theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
/-- If an element a divides another element b in a commutative ring, a divides the sum of b and
another element c iff a divides c. -/
theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) :=
begin
split,
{ intro h',
convert dvd_sub h' h,
exact eq.symm (sub_sub_self b c) },
{ intro h',
convert dvd_add h h',
exact eq_add_of_sub_eq rfl }
end
end non_unital_ring
section ring
variables [ring α] {a b c : α}
theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm
/-- An element a divides the sum a + b if and only if a divides b.-/
@[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b :=
dvd_add_right (dvd_refl a)
/-- An element a divides the sum b + a if and only if a divides b.-/
@[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b :=
dvd_add_left (dvd_refl a)
end ring
section non_unital_comm_ring
variables [non_unital_comm_ring α] {a b c : α}
lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) :
k ∣ a * x - b * y :=
begin
convert dvd_add (hxy.mul_left a) (hab.mul_right y),
rw [mul_sub_left_distrib, mul_sub_right_distrib],
simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left],
end
end non_unital_comm_ring
|
70f3e13142b64fa83c6961a9a7078e93780dcea6 | e151e9053bfd6d71740066474fc500a087837323 | /src/hott/algebra/graph.lean | f00d04d84c6b9053d5914e4277df51ff35f25b4f | [
"Apache-2.0"
] | permissive | daniel-carranza/hott3 | 15bac2d90589dbb952ef15e74b2837722491963d | 913811e8a1371d3a5751d7d32ff9dec8aa6815d9 | refs/heads/master | 1,610,091,349,670 | 1,596,222,336,000 | 1,596,222,336,000 | 241,957,822 | 0 | 0 | Apache-2.0 | 1,582,222,839,000 | 1,582,222,838,000 | null | UTF-8 | Lean | false | false | 26,212 | lean | /-
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
Graphs and operations on graphs
Currently we only define the notion of a path in a graph, and prove properties and operations on
paths.
-/
import ..arity ..eq2 .relation ..cubical.pathover2
universes u v w
namespace hott
hott_theory
/-
A path is a list of vertexes which are adjacent. We maybe use a weird ordering of cons, because
the major example where we use this is a category where this ordering makes more sense.
For the operations on paths we use the names from the corresponding operations on lists. Opening
both the list and the paths namespace will lead to many name clashes, so that is not advised.
-/
inductive paths {A : Type u} (R : A → A → Type v) : A → A → Type (max u v)
| nil {} : Π{a : A}, paths a a
| cons : Π{a₁ a₂ a₃ : A} (r : R a₂ a₃), paths a₁ a₂ → paths a₁ a₃
namespace graph
export paths
local notation h :: t := cons h t
local notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
variables {A : Type _} {R : A → A → Type _} {a a' a₁ a₂ a₃ a₄ : A}
@[hott] def concat (r : R a₁ a₂) (l : paths R a₂ a₃) : paths R a₁ a₃ :=
begin
hinduction l with a a₂ a₃ a₄ r' l IH,
{ exact [r]},
{ exact r' :: IH r}
end
@[hott] theorem concat_nil (r : R a₁ a₂) : concat r (@nil A R a₂) = [r] := idp
@[hott] theorem concat_cons (r : R a₁ a₂) (r' : R a₃ a₄) (l : paths R a₂ a₃)
: concat r (r'::l) = r'::(concat r l) := idp
@[hott] def append (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) :
paths R a₁ a₃ :=
begin
hinduction l₂ with a₂ a₂ a₃ a₄ r l₂ IH,
{ exact l₁ },
{ exact cons r (IH l₁) }
end
local infix ` ++ ` := append
@[hott] def nil_append (l : paths R a₁ a₂) : nil ++ l = l := idp
@[hott] def cons_append (r : R a₃ a₄) (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) :
(r :: l₂) ++ l₁ = r :: (l₂ ++ l₁) := idp
@[hott] def singleton_append (r : R a₂ a₃) (l : paths R a₁ a₂) : [r] ++ l = r :: l := idp
@[hott] def append_singleton (l : paths R a₂ a₃) (r : R a₁ a₂) : l ++ [r] = concat r l :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ refl },
{ exact ap (cons r) (IH _) }
end
@[hott] def append_nil (l : paths R a₁ a₂) : l ++ nil = l :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ refl },
{ exact ap (cons r) IH }
end
@[hott] def append_assoc (l₃ : paths R a₃ a₄) (l₂ : paths R a₂ a₃)
(l₁ : paths R a₁ a₂) : (l₃ ++ l₂) ++ l₁ = l₃ ++ (l₂ ++ l₁) :=
begin
hinduction l₃ with a₃ a₃ a₄ a₅ r l₃ IH,
{ refl },
{ refine ap (cons r) (IH _) }
end
@[hott] theorem append_concat (l₂ : paths R a₃ a₄) (l₁ : paths R a₂ a₃) (r : R a₁ a₂) :
l₂ ++ concat r l₁ = concat r (l₂ ++ l₁) :=
begin
hinduction l₂ with a₂ a₂ a₃ a₄ r' l₂ IH,
{ refl },
{ exact ap (cons r') (IH _) }
end
@[hott] def concat_append (l₂ : paths R a₃ a₄) (r : R a₂ a₃) (l₁ : paths R a₁ a₂) :
concat r l₂ ++ l₁ = l₂ ++ r :: l₁ :=
begin
hinduction l₂ with a₂ a₂ a₃ a₄ r' l₂ IH,
{ refl },
{ exact ap (cons r') (IH _) }
end
@[hott] def paths.rec_tail {C : Π⦃a a' : A⦄, paths R a a' → Type _}
(H0 : Π {a : A}, @C a a nil)
(H1 : Π {a₁ a₂ a₃ : A} (r : R a₁ a₂) (l : paths R a₂ a₃), C l → C (concat r l)) :
Π{a a' : A} (l : paths R a a'), C l :=
begin
have : Π{a₁ a₂ a₃ : A} (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) (c : C l₂),
C (l₂ ++ l₁),
begin
intros, revert a₃ l₂ c, hinduction l₁ with a₁ a₁ a₂ a₄ r l₁ IH; intros a₃ l₂ c,
{ rwr append_nil, exact c },
{ rwr [←concat_append], apply IH, apply H1, exact c }
end,
intros, rwr [←nil_append l], apply this, apply H0
end
@[hott] def cons_eq_concat (r : R a₂ a₃) (l : paths R a₁ a₂) :
Σa (r' : R a₁ a) (l' : paths R a a₃), r :: l = concat r' l' :=
begin
revert a₃ r, hinduction l with a₁ a₁ a₂ a₃ r l IH; intros a₃' r',
{ exact ⟨a₃', r', nil, idp⟩ },
{ cases (IH r) with a₄ w, cases w with r₂ w, cases w with l p, clear IH,
exact ⟨a₄, r₂, r' :: l, ap (cons r') p⟩ }
end
@[hott] def length (l : paths R a₁ a₂) : ℕ :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ exact 0 },
{ exact IH.succ }
end
/- If we can reverse edges in the graph we can reverse paths -/
@[hott] def reverse (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂) :
paths R a₂ a₁ :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ exact nil},
{ exact concat (rev r) IH}
end
@[hott] theorem reverse_nil (rev : Π⦃a a'⦄, R a a' → R a' a) : reverse rev (@nil A R a₁) = [] := idp
@[hott] theorem reverse_cons (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₂ a₃) (l : paths R a₁ a₂) :
reverse rev (r::l) = concat (rev r) (reverse rev l) := idp
@[hott] theorem reverse_singleton (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₁ a₂) :
reverse rev [r] = [rev r] := idp
@[hott] theorem reverse_pair (rev : Π⦃a a'⦄, R a a' → R a' a) (r₂ : R a₂ a₃) (r₁ : R a₁ a₂) :
reverse rev [r₂, r₁] = [rev r₁, rev r₂] := idp
@[hott] theorem reverse_concat (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₁ a₂) (l : paths R a₂ a₃) :
reverse rev (concat r l) = rev r :: (reverse rev l) :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ refl },
{ rwr [concat_cons, reverse_cons, IH]}
end
@[hott] theorem reverse_append (rev : Π⦃a a'⦄, R a a' → R a' a) (l₂ : paths R a₂ a₃)
(l₁ : paths R a₁ a₂) : reverse rev (l₂ ++ l₁) = reverse rev l₁ ++ reverse rev l₂ :=
begin
hinduction l₂ with a₂ a₂ a₃ a₄ r l₂ IH,
{ exact (append_nil _)⁻¹ },
{ rwr [cons_append, reverse_cons, reverse_cons, append_concat, IH] }
end
@[hott] def realize (P : A → A → Type _) (f : Π⦃a a'⦄, R a a' → P a a') (ρ : Πa, P a a)
(c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃)
⦃a a' : A⦄ (l : paths R a a') : P a a' :=
begin
hinduction l with a a₁ a₂ a₃ r l IH,
{ exact ρ a },
{ exact c IH (f r) }
end
@[hott, hsimp] def realize_nil (P : A → A → Type _) (f : Π⦃a a'⦄, R a a' → P a a')
(ρ : Πa, P a a) (c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃) (a : A) :
realize P f ρ c nil = ρ a :=
by refl
@[hott, hsimp] def realize_cons (P : A → A → Type _) (f : Π⦃a a'⦄, R a a' → P a a') (ρ : Πa, P a a)
(c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃)
⦃a₁ a₂ a₃ : A⦄ (r : R a₂ a₃) (l : paths R a₁ a₂) :
realize P f ρ c (r :: l) = c (realize P f ρ c l) (f r) :=
by refl
@[hott] theorem realize_singleton {P : A → A → Type _} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a}
{c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃}
(id_left : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c (ρ a₁) p = p)
⦃a₁ a₂ : A⦄ (r : R a₁ a₂) :
realize P f ρ c [r] = f r :=
id_left (f r)
@[hott] theorem realize_pair {P : A → A → Type _} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a}
{c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃}
(id_left : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c (ρ a₁) p = p)
⦃a₁ a₂ a₃ : A⦄ (r₂ : R a₂ a₃) (r₁ : R a₁ a₂) :
realize P f ρ c [r₂, r₁] = c (f r₁) (f r₂) :=
ap (λx, c x (f r₂)) (realize_singleton id_left r₁)
@[hott] def realize_append {P : A → A → Type _} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a}
{c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃}
(assoc : Π⦃a₁ a₂ a₃ a₄⦄ (p : P a₁ a₂) (q : P a₂ a₃) (r : P a₃ a₄), c (c p q) r = c p (c q r))
(id_right : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c p (ρ a₂) = p)
⦃a₁ a₂ a₃ : A⦄ (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) :
realize P f ρ c (l₂ ++ l₁) = c (realize P f ρ c l₁) (realize P f ρ c l₂) :=
begin
hinduction l₂ with a₂ a₂ a₃ a₄ r l₂ IH,
{ exact (id_right _)⁻¹ },
{ rwr [cons_append, realize_cons, realize_cons, IH, assoc] }
end
/-
We sometimes want to take quotients of paths (this library was developed to define the pushout of
categories). The definition paths_rel will - given some basic reduction rules codified by Q -
extend the reduction to a reflexive transitive relation respecting concatenation of paths.
-/
inductive paths_rel {A : Type u} {R : A → A → Type v}
(Q : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type w)
: Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type (max u v w)
| rrefl : Π{a a' : A} (l : paths R a a'), paths_rel l l
| rel : Π{a₁ a₂ a₃ : A} {l₂ l₃ : paths R a₂ a₃} (l : paths R a₁ a₂) (q : Q l₂ l₃),
paths_rel (l₂ ++ l) (l₃ ++ l)
| rcons : Π{a₁ a₂ a₃ : A} {l₁ l₂ : paths R a₁ a₂} (r : R a₂ a₃),
paths_rel l₁ l₂ → paths_rel (cons r l₁) (cons r l₂)
| rtrans : Π{a₁ a₂ : A} {l₁ l₂ l₃ : paths R a₁ a₂},
paths_rel l₁ l₂ → paths_rel l₂ l₃ → paths_rel l₁ l₃
open paths_rel
attribute [refl] rrefl
attribute [trans] rtrans
variables {Q : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type _}
@[hott] def paths_rel_of_Q {l₁ l₂ : paths R a₁ a₂} (q : Q l₁ l₂) :
paths_rel Q l₁ l₂ :=
begin
rwr [←append_nil l₁, ←append_nil l₂], exact rel nil q,
end
@[hott] theorem rel_respect_append_left (l : paths R a₂ a₃) {l₃ l₄ : paths R a₁ a₂}
(H : paths_rel Q l₃ l₄) : paths_rel Q (l ++ l₃) (l ++ l₄) :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ exact H },
{ exact rcons r (IH H) }
end
@[hott] theorem rel_respect_append_right {l₁ l₂ : paths R a₂ a₃} (l : paths R a₁ a₂)
(H₁ : paths_rel Q l₁ l₂) : paths_rel Q (l₁ ++ l) (l₂ ++ l) :=
begin
hinduction H₁ with a₁ a₂ l₁
a₂ a₃ a₄ l₂ l₂' l₁ q
a₂ a₃ a₄ l₁ l₂ r H₁ IH
a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH',
{ refl },
{ rwr [append_assoc, append_assoc], exact rel _ q},
{ exact rcons r (IH l) },
{ exact rtrans (IH l) (IH' l)}
end
@[hott] theorem rel_respect_append {l₁ l₂ : paths R a₂ a₃} {l₃ l₄ : paths R a₁ a₂}
(H₁ : paths_rel Q l₁ l₂) (H₂ : paths_rel Q l₃ l₄) :
paths_rel Q (l₁ ++ l₃) (l₂ ++ l₄) :=
begin
hinduction H₁ with a₁ a₂ l
a₂ a₃ a₄ l₂ l₂' l q
a₂ a₃ a₄ l₁ l₂ r H₁ IH
a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH',
{ exact rel_respect_append_left _ H₂},
{ rwr [append_assoc, append_assoc], transitivity _, exact rel _ q,
apply rel_respect_append_left, apply rel_respect_append_left, exact H₂},
{ exact rcons r (IH H₂) },
{ refine rtrans (IH H₂) _, apply rel_respect_append_right, exact H₁'}
end
/- assuming some extra properties the relation respects reversing -/
@[hott] theorem rel_respect_reverse (rev : Π⦃a a'⦄, R a a' → R a' a) {l₁ l₂ : paths R a₁ a₂}
(H : paths_rel Q l₁ l₂)
(rev_rel : Π⦃a a' : A⦄ {l l' : paths R a a'},
Q l l' → paths_rel Q (reverse rev l) (reverse rev l')) :
paths_rel Q (reverse rev l₁) (reverse rev l₂) :=
begin
hinduction H with a₁ a₂ l
a₂ a₃ a₄ l₂ l₂' l q
a₂ a₃ a₄ l₁ l₂ r H₁ IH
a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH',
{ refl },
{ rwr [reverse_append, reverse_append], apply rel_respect_append_left, apply rev_rel q },
{ rwr [reverse_cons, reverse_cons,←append_singleton, ←append_singleton],
apply rel_respect_append_right, exact IH },
{ exact rtrans IH IH' }
end
@[hott] theorem rel_left_inv (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂)
(li : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [rev r, r] nil) :
paths_rel Q (reverse rev l ++ l) nil :=
begin
hinduction l with a₁ a₁ a₂ a₃ r l IH,
{ refl },
{ rwr [reverse_cons, concat_append],
refine rtrans _ IH, apply rel_respect_append_left,
exact rel_respect_append_right _ (li r)}
end
@[hott] theorem rel_right_inv (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂)
(ri : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [r, rev r] nil) :
paths_rel Q (l ++ reverse rev l) nil :=
begin
hinduction l using paths.rec_tail,
{ refl },
{ rwr [reverse_concat, concat_append],
refine rtrans _ a, apply rel_respect_append_left,
exact rel_respect_append_right _ (ri r)}
end
@[hott] def realize_eq {P : A → A → Type _} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a}
{c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃}
(assoc : Π⦃a₁ a₂ a₃ a₄⦄ (p : P a₁ a₂) (q : P a₂ a₃) (r : P a₃ a₄), c (c p q) r = c p (c q r))
(id_right : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c p (ρ a₂) = p)
(resp_rel : Π⦃a₁ a₂⦄ {l₁ l₂ : paths R a₁ a₂}, Q l₁ l₂ →
realize P f ρ c l₁ = realize P f ρ c l₂)
⦃a a' : A⦄ {l l' : paths R a a'} (H : paths_rel Q l l') :
realize P f ρ c l = realize P f ρ c l' :=
begin
hinduction H with a₁ a₂ l
a₂ a₃ a₄ l₂ l₂' l q
a₂ a₃ a₄ l₁ l₂ r H₁ IH
a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH',
{ refl },
{ rwr [realize_append assoc id_right, realize_append assoc id_right],
apply ap (c _), exact resp_rel q },
{ exact ap (λx, c x (f r)) IH },
{ exact IH ⬝ IH' }
end
end graph
/- the following are words of paths in a graph, which means that for example
(p ++ q) ++ r and p ++ (q ++ r) are different words. Furthermore, the paths can be reversed.
This is used to represent 2-constructors in hit.two_quotient -/
inductive pwords {A : Type u} (R : A → A → Type v) : A → A → Type (max u v)
| of_rel : Π{a a'} (r : R a a'), pwords a a'
| of_path : Π{a a'} (pp : a = a'), pwords a a'
| symm : Π{a a'} (r : pwords a a'), pwords a' a
| trans : Π{a a' a''} (r : pwords a a') (r' : pwords a' a''), pwords a a''
namespace graph
export pwords
infix ` ⬝r `:75 := pwords.trans
postfix `⁻¹ʳ`:(max+10) := pwords.symm
notation `[`:max a `]`:0 := pwords.of_rel a
notation `<`:max p `>`:0 := pwords.of_path _ p
abbreviation rfl {A : Type _} {R : A → A → Type _} {a : A} := of_path R (idpath a)
end graph
namespace graph
section
parameters {A : Type _}
{R : A → A → Type _}
private abbreviation T := pwords R
variables ⦃a a' a'' : A⦄ {s : R a a'} {r : T a a} {B : Type _} {C : Type _}
@[hott] protected def pwords.elim {f : A → B}
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : f a = f a' :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
exact e r,
exact ap f pp,
exact IH⁻¹,
exact IH₁ ⬝ IH₂
end
@[hott, hsimp] protected def pwords.elim_symm {f : A → B}
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') :
pwords.elim e t⁻¹ʳ = (pwords.elim e t)⁻¹ :=
by refl
@[hott, hsimp] protected def pwords.elim_trans {f : A → B}
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') (t' : T a' a'') :
pwords.elim e (t ⬝r t') = pwords.elim e t ⬝ pwords.elim e t' :=
by refl
@[hott] def ap_pwords_elim_h {B C : Type _} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap g (pwords.elim e t) = pwords.elim e' t :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
apply p,
induction pp, refl,
exact ap_inv g (pwords.elim e r) ⬝ inverse2 IH,
exact ap_con g (pwords.elim e r) (pwords.elim e r') ⬝ (IH₁ ◾ IH₂)
end
@[hott, hsimp] def ap_pwords_elim_h_symm {B C : Type _} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') :
ap_pwords_elim_h e p t⁻¹ʳ = ap_inv g (pwords.elim e t) ⬝ (ap_pwords_elim_h e p t)⁻² :=
by refl
@[hott, hsimp] def ap_pwords_elim_h_trans {B C : Type _} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t₁ : T a a') (t₂ : T a' a'') :
ap_pwords_elim_h e p (t₁ ⬝r t₂) = ap_con g (pwords.elim e t₁) (pwords.elim e t₂) ⬝
ap_pwords_elim_h e p t₁ ◾ ap_pwords_elim_h e p t₂ :=
by refl
@[hott] def ap_pwords_elim {B C : Type _} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: ap g (pwords.elim e t) = pwords.elim (λa a' r, ap g (e r)) t :=
ap_pwords_elim_h e (λa a' s, idp) t
@[hott, hsimp] def ap_pwords_elim_symm {B C : Type _} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: ap_pwords_elim g e t⁻¹ʳ = ap_inv g (pwords.elim e t) ⬝ (ap_pwords_elim g e t)⁻² :=
by refl
@[hott, hsimp] def ap_pwords_elim_trans {B C : Type _} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') (t' : T a' a'')
: ap_pwords_elim g e (t ⬝r t') = ap_con g (pwords.elim e t) (pwords.elim e t') ⬝
(ap_pwords_elim g e t ◾ ap_pwords_elim g e t') :=
by refl
@[hott] def pwords_elim_eq {f : A → B}
{e e' : Π⦃a a' : A⦄, R a a' → f a = f a'} (p : e ~3 e') (t : T a a')
: pwords.elim e t = pwords.elim e' t :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
apply p,
refl,
exact IH⁻²,
exact IH₁ ◾ IH₂
end
-- TODO: formulate and prove this without using function extensionality,
-- and modify the proofs using this to also not use function extensionality
-- strategy: use `pwords_elim_eq` instead of `ap ... (eq_of_homotopy3 p)`
@[hott] def ap_pwords_elim_h_eq {B C : Type _} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap_pwords_elim_h e p t =
ap_pwords_elim g e t ⬝ ap (λx, pwords.elim x t) (eq_of_homotopy3 p) :=
begin
fapply homotopy3.rec_on p,
intro q, dsimp at q, hinduction q,
dsimp [ap_pwords_elim],
symmetry, refine whisker_left _ (ap02 _ (by exact eq_of_homotopy3_id _)) ⬝ _,
refl
end
@[hott] def ap_ap_pwords_elim_h {B C D : Type _} {f : A → B}
{g : B → C} (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: square (ap (ap h) (ap_pwords_elim_h e p t))
(ap_pwords_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (pwords.elim e t))⁻¹
(ap_pwords_elim_h e' (λa a' s, (ap (ap h) (p s))⁻¹) t) :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ dsimp,
apply square_of_eq, exact con.right_inv _ ⬝ (con.left_inv _)⁻¹ },
{ induction pp, apply ids},
{ dsimp, rwr [ap_con (ap h)],
refine (transpose (ap_compose_inv _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, ←inv2_inv],
exact ap_inv2 _ ⬝v square_inv2 IH },
{ dsimp, rwr [ap_con (ap h)],
refine (transpose (ap_compose_con _ _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, con2_inv],
refine ap_con2 _ _ ⬝v square_con2 IH₁ IH₂ },
end
@[hott] def ap_ap_pwords_elim {B C D : Type _} {f : A → B}
(g : B → C) (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: square (ap (ap h) (ap_pwords_elim g e t))
(ap_pwords_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (pwords.elim e t))⁻¹
(ap_pwords_elim h (λa a' r, ap g (e r)) t) :=
ap_ap_pwords_elim_h _ _ _ _
@[hott] def ap_pwords_elim_h_compose {B C D : Type _} {f : A → B}
{g : B → C} (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → h (g (f a)) = h (g (f a'))}
(p : Π⦃a a' : A⦄ (s : R a a'), ap (h ∘ g) (e s) = e' s) (t : T a a') :
square (ap02 h (ap_pwords_elim g e t))
(ap_pwords_elim_h e p t)
(ap_compose h g (pwords.elim e t))⁻¹
(ap_pwords_elim_h (λa a' s, ap g (e s)) (λa a' s, (ap_compose h g (e s))⁻¹ ⬝ p s) t) :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ dsimp [ap_pwords_elim_h, ap_pwords_elim, ap02, pwords.elim],
apply square_of_eq, apply idp_con },
{ induction pp, apply ids },
-- the rest of the proof is almost the same as the proof of ap_ap_pwords_elim[_h].
-- Is there a connection between these theorems?
{ dsimp [ap02], rwr [ap_con (ap h)],
refine (transpose (ap_compose_inv _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, ←inv2_inv],
exact ap_inv2 _ ⬝v square_inv2 IH },
{ dsimp [ap02], rwr [ap_con (ap h)],
refine (transpose (ap_compose_con _ _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, con2_inv],
refine ap_con2 _ _ ⬝v square_con2 IH₁ IH₂ },
end
@[hott] def ap_pwords_elim_h_zigzag {B C D : Type _} {f : A → B}
{g : B → C} (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → h (g (f a)) = h (g (f a'))}
(p : Π⦃a a' : A⦄ (s : R a a'), ap (h ∘ g) (e s) = e' s) (t : T a a')
: ap_pwords_elim h (λa a' s, ap g (e s)) t ⬝
(ap_pwords_elim_h e (λa a' s, ap_compose h g (e s)) t)⁻¹ ⬝
ap_pwords_elim_h e p t =
ap_pwords_elim_h (λa a' s, ap g (e s)) (λa a' s, (ap_compose h g (e s))⁻¹ ⬝ p s) t :=
begin
refine whisker_right _ (eq_of_square (ap_ap_pwords_elim g h e t)⁻¹ʰ)⁻¹ ⬝ _,
refine con.assoc _ _ _ ⬝ _, apply inv_con_eq_of_eq_con, apply eq_of_square,
apply transpose,
-- the rest of the proof is almost the same as the proof of ap_ap_pwords_elim[_h].
-- Is there a connection between these theorems?
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ dsimp, apply square_of_eq, apply idp_con },
{ induction pp, apply ids },
{ dsimp, rwr [ap_con (ap h)],
refine (transpose (ap_compose_inv _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, ←inv2_inv],
exact ap_inv2 _ ⬝v square_inv2 IH },
{ dsimp, rwr [ap_con (ap h)],
refine (transpose (ap_compose_con _ _ _ _))⁻¹ᵛ ⬝h _,
rwr [con_inv, eq.inv_inv, con2_inv],
refine ap_con2 _ _ ⬝v square_con2 IH₁ IH₂ },
end
open hott.relation
@[hott] def is_equivalence_pwords : is_equivalence T :=
begin
constructor,
intro a, exact rfl,
intros a a' t, exact t⁻¹ʳ,
intros a a' a'' t t', exact t ⬝r t',
end
/- dependent elimination -/
variables {P : B → Type _} {Q : C → Type _} {f : A → B} {g : B → C} {f' : Π(a : A), P (f a)}
@[hott] protected def pwords.elimo (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a')
: f' a =[pwords.elim p t] f' a' :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
exact po r,
induction pp, constructor,
exact IH⁻¹ᵒ,
exact IH₁ ⬝o IH₂
end
@[hott, hsimp] def elimo_symm (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a')
: pwords.elimo p po t⁻¹ʳ = (pwords.elimo p po t)⁻¹ᵒ :=
by refl
@[hott, hsimp] def elimo_trans (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a') (t' : T a' a'')
: pwords.elimo p po (t ⬝r t') = pwords.elimo p po t ⬝o pwords.elimo p po t' :=
by refl
@[hott] def ap_pwords_elimo_h {g' : Πb, Q (g b)}
(p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), g' (f a) =[p s; Q ∘ g] g' (f a'))
(q : Π⦃a a' : A⦄ (s : R a a'), apd g' (p s) = po s)
(t : T a a') : apd g' (pwords.elim p t) = pwords.elimo p po t :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
apply q,
induction pp, refl,
exact apd_inv g' (pwords.elim p r) ⬝ IH⁻²ᵒ,
exact apd_con g' (pwords.elim p r) (pwords.elim p r') ⬝ (IH₁ ◾o IH₂)
end
@[hott] theorem pwords_elimo_ap {g' : Π(a : A), Q (g (f a))}
(p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), g' a =[ap g (p s)] g' a')
(t : T a a') : pwords.elimo p (λa a' s, pathover_of_pathover_ap Q g (po s)) t =
pathover_of_pathover_ap Q g (change_path (ap_pwords_elim g p t)⁻¹
(pwords.elimo (λa a' r, ap g (p r)) po t)) :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ refl },
{ induction pp; refl },
{ rwr [elimo_symm, ap_pwords_elim_symm, IH, con_inv, change_path_con, ←inv2_inv], dsimp,
rwr [change_path_invo, pathover_of_pathover_ap_invo] },
{ rwr [elimo_trans, elimo_trans, ap_pwords_elim_trans, IH₁, IH₂, con_inv, change_path_con],
dsimp, rwr [con2_inv, change_path_cono, pathover_of_pathover_ap_cono] },
end
end
end graph
end hott |
c695341b6baa85371082fb421e08dc43c5bb731a | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_597.lean | bc2e9b7824f930e8ea69b6ad1e1315f91428848d | [] | 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 | 99 | lean | import data.real.basic
example : ∃ x : ℝ, 2 < x ∧ x < 3 :=
begin
use 5 / 2,
norm_num
end |
0c8805c8431cf8f3adc8d2f4262f963db71bd7fb | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /library/init/logic.lean | ab202e25514ba564ac8e9927eadc163f970cfb21 | [
"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 | 14,068 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.logic
Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn
-/
prelude
import init.datatypes init.reserved_notation
/- implication -/
definition trivial := true.intro
definition not (a : Prop) := a → false
prefix `¬` := not
definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b :=
false.rec b (H2 H1)
/- not -/
theorem not_false : ¬false :=
assume H : false, H
/- eq -/
notation a = b := eq a b
definition rfl {A : Type} {a : A} := eq.refl a
-- proof irrelevance is built in
theorem proof_irrel {a : Prop} (H₁ H₂ : a) : H₁ = H₂ :=
rfl
namespace eq
variables {A : Type}
variables {a b c a': A}
theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b :=
eq.rec H₂ H₁
theorem trans (H₁ : a = b) (H₂ : b = c) : a = c :=
subst H₂ H₁
definition symm (H : a = b) : b = a :=
eq.rec (refl a) H
namespace ops
notation H `⁻¹` := symm H --input with \sy or \-1 or \inv
notation H1 ⬝ H2 := trans H1 H2
notation H1 ▸ H2 := subst H1 H2
end ops
end eq
section
variable {p : Prop}
open eq.ops
theorem of_eq_true (H : p = true) : p :=
H⁻¹ ▸ trivial
theorem not_of_eq_false (H : p = false) : ¬p :=
assume Hp, H ▸ Hp
end
calc_subst eq.subst
calc_refl eq.refl
calc_trans eq.trans
calc_symm eq.symm
/- ne -/
definition ne {A : Type} (a b : A) := ¬(a = b)
notation a ≠ b := ne a b
namespace ne
open eq.ops
variable {A : Type}
variables {a b : A}
theorem intro : (a = b → false) → a ≠ b :=
assume H, H
theorem elim : a ≠ b → a = b → false :=
assume H₁ H₂, H₁ H₂
theorem irrefl : a ≠ a → false :=
assume H, H rfl
theorem symm : a ≠ b → b ≠ a :=
assume (H : a ≠ b) (H₁ : b = a), H (H₁⁻¹)
end ne
section
open eq.ops
variables {A : Type} {a b c : A}
theorem false.of_ne : a ≠ a → false :=
assume H, H rfl
theorem ne.of_eq_of_ne : a = b → b ≠ c → a ≠ c :=
assume H₁ H₂, H₁⁻¹ ▸ H₂
theorem ne.of_ne_of_eq : a ≠ b → b = c → a ≠ c :=
assume H₁ H₂, H₂ ▸ H₁
end
calc_trans ne.of_eq_of_ne
calc_trans ne.of_ne_of_eq
infixl `==`:50 := heq
namespace heq
universe variable u
variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C}
definition to_eq (H : a == a') : a = a' :=
have H₁ : ∀ (Ht : A = A), eq.rec_on Ht a = a, from
λ Ht, eq.refl (eq.rec_on Ht a),
heq.rec_on H H₁ (eq.refl A)
definition elim {A : Type} {a : A} {P : A → Type} {b : A} (H₁ : a == b) (H₂ : P a) : P b :=
eq.rec_on (to_eq H₁) H₂
theorem subst {P : ∀T : Type, T → Prop} (H₁ : a == b) (H₂ : P A a) : P B b :=
heq.rec_on H₁ H₂
theorem symm (H : a == b) : b == a :=
heq.rec_on H (refl a)
theorem of_eq (H : a = a') : a == a' :=
eq.subst H (refl a)
theorem trans (H₁ : a == b) (H₂ : b == c) : a == c :=
subst H₂ H₁
theorem of_heq_of_eq (H₁ : a == b) (H₂ : b = b') : a == b' :=
trans H₁ (of_eq H₂)
theorem of_eq_of_heq (H₁ : a = a') (H₂ : a' == b) : a == b :=
trans (of_eq H₁) H₂
end heq
theorem of_heq_true {a : Prop} (H : a == true) : a :=
of_eq_true (heq.to_eq H)
calc_trans heq.trans
calc_trans heq.of_heq_of_eq
calc_trans heq.of_eq_of_heq
calc_symm heq.symm
/- and -/
notation a /\ b := and a b
notation a ∧ b := and a b
variables {a b c d : Prop}
theorem and.elim (H₁ : a ∧ b) (H₂ : a → b → c) : c :=
and.rec H₂ H₁
/- or -/
notation a `\/` b := or a b
notation a ∨ b := or a b
namespace or
theorem elim (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → c) : c :=
or.rec H₂ H₃ H₁
end or
/- iff -/
definition iff (a b : Prop) := (a → b) ∧ (b → a)
notation a <-> b := iff a b
notation a ↔ b := iff a b
namespace iff
definition intro (H₁ : a → b) (H₂ : b → a) : a ↔ b :=
and.intro H₁ H₂
definition elim (H₁ : (a → b) → (b → a) → c) (H₂ : a ↔ b) : c :=
and.rec H₁ H₂
definition elim_left (H : a ↔ b) : a → b :=
elim (assume H₁ H₂, H₁) H
definition mp := @elim_left
definition elim_right (H : a ↔ b) : b → a :=
elim (assume H₁ H₂, H₂) H
definition mp' := @elim_right
definition refl (a : Prop) : a ↔ a :=
intro (assume H, H) (assume H, H)
definition rfl {a : Prop} : a ↔ a :=
refl a
theorem trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c :=
intro
(assume Ha, elim_left H₂ (elim_left H₁ Ha))
(assume Hc, elim_right H₁ (elim_right H₂ Hc))
theorem symm (H : a ↔ b) : b ↔ a :=
intro
(assume Hb, elim_right H Hb)
(assume Ha, elim_left H Ha)
open eq.ops
theorem of_eq {a b : Prop} (H : a = b) : a ↔ b :=
iff.intro (λ Ha, H ▸ Ha) (λ Hb, H⁻¹ ▸ Hb)
end iff
definition not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b :=
iff.intro
(assume (Hna : ¬ a) (Hb : b), absurd (iff.elim_right H₁ Hb) Hna)
(assume (Hnb : ¬ b) (Ha : a), absurd (iff.elim_left H₁ Ha) Hnb)
theorem of_iff_true (H : a ↔ true) : a :=
iff.mp (iff.symm H) trivial
theorem not_of_iff_false (H : a ↔ false) : ¬a :=
assume Ha : a, iff.mp H Ha
theorem iff_of_eq_of_iff (H₁ : a = b) (H₂ : b ↔ c) : a ↔ c :=
H₁⁻¹ ▸ H₂
theorem iff_of_iff_of_eq (H₁ : a ↔ b) (H₂ : b = c) : a ↔ c :=
H₂ ▸ H₁
calc_refl iff.refl
calc_trans iff.trans
calc_trans iff_of_eq_of_iff
calc_trans iff_of_iff_of_eq
inductive Exists {A : Type} (P : A → Prop) : Prop :=
intro : ∀ (a : A), P a → Exists P
definition exists.intro := @Exists.intro
notation `exists` binders `,` r:(scoped P, Exists P) := r
notation `∃` binders `,` r:(scoped P, Exists P) := r
theorem exists.elim {A : Type} {p : A → Prop} {B : Prop} (H1 : ∃x, p x) (H2 : ∀ (a : A) (H : p a), B) : B :=
Exists.rec H2 H1
/- decidable -/
inductive decidable [class] (p : Prop) : Type :=
| inl : p → decidable p
| inr : ¬p → decidable p
definition decidable_true [instance] : decidable true :=
decidable.inl trivial
definition decidable_false [instance] : decidable false :=
decidable.inr not_false
namespace decidable
variables {p q : Prop}
definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, H4) (λh, !false.rec (h H3))
definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, false.rec _ (H3 h)) (λh, H4)
definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q :=
decidable.rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp)
theorem em (p : Prop) [H : decidable p] : p ∨ ¬p :=
by_cases (λ Hp, or.inl Hp) (λ Hnp, or.inr Hnp)
theorem by_contradiction [Hp : decidable p] (H : ¬p → false) : p :=
by_cases
(assume H1 : p, H1)
(assume H1 : ¬p, false.rec _ (H H1))
end decidable
section
variables {p q : Prop}
open decidable
definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q :=
decidable.rec_on Hp
(assume Hp : p, inl (iff.elim_left H Hp))
(assume Hnp : ¬p, inr (iff.elim_left (not_iff_not_of_iff H) Hnp))
definition decidable_of_decidable_of_eq (Hp : decidable p) (H : p = q) : decidable q :=
decidable_of_decidable_of_iff Hp (iff.of_eq H)
end
section
variables {p q : Prop}
open decidable (rec_on inl inr)
definition decidable_and [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∧ q) :=
rec_on Hp
(assume Hp : p, rec_on Hq
(assume Hq : q, inl (and.intro Hp Hq))
(assume Hnq : ¬q, inr (assume H : p ∧ q, and.rec_on H (assume Hp Hq, absurd Hq Hnq))))
(assume Hnp : ¬p, inr (assume H : p ∧ q, and.rec_on H (assume Hp Hq, absurd Hp Hnp)))
definition decidable_or [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∨ q) :=
rec_on Hp
(assume Hp : p, inl (or.inl Hp))
(assume Hnp : ¬p, rec_on Hq
(assume Hq : q, inl (or.inr Hq))
(assume Hnq : ¬q, inr (assume H : p ∨ q, or.elim H (assume Hp, absurd Hp Hnp) (assume Hq, absurd Hq Hnq))))
definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) :=
rec_on Hp
(assume Hp, inr (λ Hnp, absurd Hp Hnp))
(assume Hnp, inl Hnp)
definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) :=
rec_on Hp
(assume Hp : p, rec_on Hq
(assume Hq : q, inl (assume H, Hq))
(assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq)))
(assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp))
definition decidable_iff [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) :=
show decidable ((p → q) ∧ (q → p)), from _
end
definition decidable_pred [reducible] {A : Type} (R : A → Prop) := Π (a : A), decidable (R a)
definition decidable_rel [reducible] {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b)
definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A)
definition decidable_ne [instance] {A : Type} [H : decidable_eq A] : Π (a b : A), decidable (a ≠ b) :=
show Π x y : A, decidable (x = y → false), from _
namespace bool
definition ff_ne_tt : ff = tt → false
| [none]
end bool
open bool
definition is_dec_eq {A : Type} (p : A → A → bool) : Prop := ∀ ⦃x y : A⦄, p x y = tt → x = y
definition is_dec_refl {A : Type} (p : A → A → bool) : Prop := ∀x, p x x = tt
open decidable
protected definition bool.has_decidable_eq [instance] : ∀a b : bool, decidable (a = b)
| ff ff := inl rfl
| ff tt := inr ff_ne_tt
| tt ff := inr (ne.symm ff_ne_tt)
| tt tt := inl rfl
definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A :=
take x y : A, by_cases
(assume Hp : p x y = tt, inl (H₁ Hp))
(assume Hn : ¬ p x y = tt, inr (assume Hxy : x = y, absurd (H₂ y) (eq.rec_on Hxy Hn)))
/- inhabited -/
inductive inhabited [class] (A : Type) : Type :=
mk : A → inhabited A
protected definition inhabited.value {A : Type} (h : inhabited A) : A :=
inhabited.rec (λa, a) h
protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B :=
inhabited.rec H2 H1
definition default (A : Type) [H : inhabited A] : A :=
inhabited.rec (λa, a) H
opaque definition arbitrary (A : Type) [H : inhabited A] : A :=
inhabited.rec (λa, a) H
definition Prop.is_inhabited [instance] : inhabited Prop :=
inhabited.mk true
definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) :=
inhabited.rec_on H (λb, inhabited.mk (λa, b))
definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] :
inhabited (Πx, B x) :=
inhabited.mk (λa, inhabited.rec_on (H a) (λb, b))
protected definition bool.is_inhabited [instance] : inhabited bool :=
inhabited.mk ff
inductive nonempty [class] (A : Type) : Prop :=
intro : A → nonempty A
protected definition nonempty.elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B :=
nonempty.rec H2 H1
theorem nonempty_of_inhabited [instance] {A : Type} [H : inhabited A] : nonempty A :=
nonempty.intro (default A)
definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A :=
decidable.rec_on H (λ Hc, t) (λ Hnc, e)
definition if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
definition if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e))
H
definition if_t_t (c : Prop) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t))
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t))
H
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
definition dite (c : Prop) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A :=
decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc)
definition dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = t Hc :=
decidable.rec
(λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
definition dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = e Hnc :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e))
H
-- Remark: dite and ite are "definitionally equal" when we ignore the proofs.
theorem dite_ite_eq (c : Prop) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e :=
rfl
definition is_true (c : Prop) [H : decidable c] : Prop :=
if c then true else false
definition is_false (c : Prop) [H : decidable c] : Prop :=
if c then false else true
theorem of_is_true {c : Prop} [H₁ : decidable c] (H₂ : is_true c) : c :=
decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, !false.rec (if_neg Hnc ▸ H₂))
notation `dec_trivial` := of_is_true trivial
theorem not_of_not_is_true {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_true c) : ¬ c :=
decidable.rec_on H₁ (λ Hc, absurd true.intro (if_pos Hc ▸ H₂)) (λ Hnc, Hnc)
theorem not_of_is_false {c : Prop} [H₁ : decidable c] (H₂ : is_false c) : ¬ c :=
decidable.rec_on H₁ (λ Hc, !false.rec (if_pos Hc ▸ H₂)) (λ Hnc, Hnc)
theorem of_not_is_false {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_false c) : c :=
decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, absurd true.intro (if_neg Hnc ▸ H₂))
|
60d14eb19f7576da9e696160037a26c601b4ddfd | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/flat.lean | ffce2a604777cc6f2a5a6f3bf8bc6c463e50edb0 | [
"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,702 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import ring_theory.noetherian
/-!
# Flat modules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A module `M` over a commutative ring `R` is *flat*
if for all finitely generated ideals `I` of `R`,
the canonical map `I ⊗ M →ₗ M` is injective.
This is equivalent to the claim that for all injective `R`-linear maps `f : M₁ → M₂`
the induced map `M₁ ⊗ M → M₂ ⊗ M` is injective.
See <https://stacks.math.columbia.edu/tag/00HD>.
This result is not yet formalised.
## Main declaration
* `module.flat`: the predicate asserting that an `R`-module `M` is flat.
## TODO
* Show that tensoring with a flat module preserves injective morphisms.
Show that this is equivalent to be flat.
See <https://stacks.math.columbia.edu/tag/00HD>.
To do this, it is probably a good idea to think about a suitable
categorical induction principle that should be applied to the category of `R`-modules,
and that will take care of the administrative side of the proof.
* Define flat `R`-algebras
* Define flat ring homomorphisms
- Show that the identity is flat
- Show that composition of flat morphisms is flat
* Show that flatness is stable under base change (aka extension of scalars)
For base change, it will be very useful to have a "characteristic predicate"
instead of relying on the construction `A ⊗ B`.
Indeed, such a predicate should allow us to treat both
`A[X]` and `A ⊗ R[X]` as the base change of `R[X]` to `A`.
(Similar examples exist with `fin n → R`, `R × R`, `ℤ[i] ⊗ ℝ`, etc...)
* Generalize flatness to noncommutative rings.
-/
universes u v
namespace module
open function (injective)
open linear_map (lsmul)
open_locale tensor_product
/-- An `R`-module `M` is flat if for all finitely generated ideals `I` of `R`,
the canonical map `I ⊗ M →ₗ M` is injective. -/
class flat (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : Prop :=
(out : ∀ ⦃I : ideal R⦄ (hI : I.fg), injective (tensor_product.lift ((lsmul R M).comp I.subtype)))
namespace flat
open tensor_product linear_map _root_.submodule
instance self (R : Type u) [comm_ring R] : flat R R :=
⟨begin
intros I hI,
rw ← equiv.injective_comp (tensor_product.rid R I).symm.to_equiv,
convert subtype.coe_injective using 1,
ext x,
simp only [function.comp_app, linear_equiv.coe_to_equiv, rid_symm_apply, comp_apply,
mul_one, lift.tmul, subtype_apply, algebra.id.smul_eq_mul, lsmul_apply]
end⟩
end flat
end module
|
359eb76418a45b463b20cd679a0e1f97a2767356 | 35452ce8e77eaf9e0aa9367a9e20bafbf92730d4 | /src/aux.lean | 1ab294a91e83468075aebf6ebec4f66b034bd1da | [] | no_license | ADedecker/wedderburn | 6935f44f922080df5d673051737881d9f8a94e9c | 1ed28ff8cf64e1652d540557765e379b3901ad19 | refs/heads/master | 1,692,935,097,444 | 1,634,302,432,000 | 1,634,302,432,000 | 412,828,531 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,036 | lean | import linear_algebra
import field_theory.finite.basic
open_locale big_operators
lemma card_subtype_eq_iff (α : Type*) (p : α → Prop) [decidable_pred p] [fintype α] :
fintype.card ({x // p x}) = fintype.card α ↔ ∀ x, p x :=
begin
rw [fintype.card_subtype p, finset.card_eq_iff_eq_univ, finset.eq_univ_iff_forall],
refine forall_congr (λ x, _),
rw [finset.mem_filter],
exact ⟨λ ⟨_, h⟩, h, λ h, ⟨finset.mem_univ x, h⟩⟩
end
lemma set.card_coe_sort_eq_iff (α : Type*) (S : set α) [decidable_pred (λ x, x ∈ S)] [fintype α] :
fintype.card S = fintype.card α ↔ ∀ x, x ∈ S :=
card_subtype_eq_iff α (λ x, x ∈ S)
lemma card_eq_pow_finrank' {K V : Type*} [division_ring K] [add_comm_group V] [module K V] [fintype K] [fintype V] :
fintype.card V = (fintype.card K) ^ (finite_dimensional.finrank K V) :=
begin
let b := is_noetherian.finset_basis K V,
rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b],
end
lemma subsemiring.center_eq_top_iff (R : Type*) [semiring R] :
subsemiring.center R = ⊤ ↔ commutative ((*) : R → R → R) :=
begin
simp_rw [subsemiring.eq_top_iff', subsemiring.mem_center_iff],
rw forall_swap,
refl
end
lemma subring.center_eq_top_iff (R : Type*) [ring R] :
subring.center R = ⊤ ↔ commutative ((*) : R → R → R) :=
begin
simp_rw [subring.eq_top_iff', subring.mem_center_iff],
rw forall_swap,
refl
end
def submonoid.centralizer {M : Type*} [monoid M] (x : M) : submonoid M :=
{ carrier := {y | commute x y},
one_mem' := commute.one_right x,
mul_mem' := λ a b, commute.mul_right }
def subgroup.centralizer {G : Type*} [group G] (x : G) : subgroup G :=
{ inv_mem' := λ a, commute.inv_right,
..submonoid.centralizer x }
def subsemiring.centralizer {R : Type*} [semiring R] (x : R) : subsemiring R :=
{ zero_mem' := commute.zero_right x,
add_mem' := λ a b, commute.add_right,
..submonoid.centralizer x }
def subring.centralizer {R : Type*} [ring R] (x : R) : subring R :=
{ neg_mem' := λ a, commute.neg_right,
..subsemiring.centralizer x }
instance subring.centralizer.division_ring {R : Type*} [division_ring R] (x : R) :
division_ring (subring.centralizer x) :=
{ inv := λ ⟨y, hy⟩, ⟨y⁻¹, commute.inv_right' hy⟩,
mul_inv_cancel := λ ⟨a, ha⟩ h, subtype.ext $ mul_inv_cancel $ subtype.coe_injective.ne h,
inv_zero := subtype.ext inv_zero,
..(subring.centralizer x).nontrivial,
..(subring.centralizer x).to_ring }
def submodule.centralizer {R : Type*} [ring R] (x : R) :
submodule (subring.center R) R :=
{ smul_mem' := λ c y (hy : commute x y),
calc x * c • y
= x * (c * y) : by rw [subring.smul_def, smul_eq_mul]
... = (x * c) * y : by rw mul_assoc
... = (c * x) * y : by have : x * ↑c = ↑c * x := c.2 x; rw this
... = c * (x * y) : by rw mul_assoc
... = c * (y * x) : by rw hy.eq
... = (c * y) * x : by rw mul_assoc
... = c • y * x : by rw [subring.smul_def, smul_eq_mul],
..subring.centralizer x }
def units_submonoid_equiv {M : Type*} [monoid M] (S : submonoid M)
(hS : ∀ x : units M, (x : M) ∈ S → ((x⁻¹ : units M) : M) ∈ S) :
units S ≃ {x : units M // (x : M) ∈ S} :=
{ to_fun := λ x, ⟨units.map S.subtype x, (coe x : S).2⟩,
inv_fun := λ x, ⟨⟨x.1, x.2⟩, ⟨coe (x.1⁻¹), hS x.1 x.2⟩,
by ext; rw submonoid.coe_mul; exact x.1.mul_inv,
by ext; rw submonoid.coe_mul; exact x.1.inv_mul⟩,
left_inv := λ x, by ext; refl,
right_inv := λ x, by ext; refl }
lemma card_units' {A : Type*} [fintype A] [division_ring A] :
fintype.card (units A) = fintype.card A - 1 :=
begin
classical,
rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : A)⟩)],
haveI := set_fintype {a : A | a ≠ 0},
haveI := set_fintype (@set.univ A),
rw [fintype.card_congr (equiv.units_equiv_ne_zero _),
← @set.card_insert _ _ {a : A | a ≠ 0} _ (not_not.2 (eq.refl (0 : A)))
(set.fintype_insert _ _), fintype.card_congr (equiv.set.univ A).symm],
congr; simp [set.ext_iff, classical.em]
end
section class_formula
/-!
## Class formula corollary on the number of fixed points
-/
open fintype mul_action function
variables {G X : Type*} [group G] [mul_action G X] [fintype X] [Π (x : X), fintype (orbit G x)]
[fintype (quotient $ orbit_rel G X)] [fintype (mul_action.fixed_points G X)]
local notation `Ω` := (quotient $ orbit_rel G X)
lemma card_eq_sum_card_orbits' {φ : Ω → X} (hφ : left_inverse quotient.mk' φ) :
card X = ∑ (ω : Ω), card (orbit G (φ ω)) :=
by rw [card_congr (self_equiv_sigma_orbits' G X hφ), card_sigma]
lemma card_eq_card_fixed_points_add_sum_card_nontrivial_orbits'
{φ : Ω → X} (hφ : left_inverse quotient.mk' φ)
[decidable_pred (λ (ω : Ω), φ ω ∈ mul_action.fixed_points G X)] :
card X =
(∑ ω in finset.filter (λ (ω : Ω), φ ω ∉ mul_action.fixed_points G X) finset.univ,
card (orbit G (φ ω))) +
card (mul_action.fixed_points G X) :=
calc card X
= ∑ (ω : Ω), card (orbit G (φ ω)) : card_eq_sum_card_orbits' hφ
... = ∑ ω in finset.filter (λ (ω : Ω), φ ω ∈ mul_action.fixed_points G X) finset.univ,
card (orbit G (φ ω)) +
∑ ω in finset.filter (λ (ω : Ω), φ ω ∉ mul_action.fixed_points G X) finset.univ,
card (orbit G (φ ω)) : (finset.sum_filter_add_sum_filter_not _ _ _).symm
... = ∑ ω in finset.filter (λ (ω : Ω), φ ω ∈ mul_action.fixed_points G X) finset.univ,
1 +
∑ ω in finset.filter (λ (ω : Ω), φ ω ∉ mul_action.fixed_points G X) finset.univ,
card (orbit G (φ ω)) :
by {congr' 1, conv {congr, congr, } }
... = _ : sorry
lemma dvd_card_trivial_orbit'
{φ : Ω → X} (hφ : left_inverse quotient.mk' φ) {n : ℕ} (hn₁ : n ∣ card X)
(hn₂ : ∀ (x : X), x ∉ mul_action.fixed_points G X → n ∣ card (orbit G x)) :
n ∣ card (mul_action.fixed_points G X) :=
begin
end
end class_formula
|
beed06efff07317eb59e05cfef4897b78f210195 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/converter/binders.lean | 9b1300b2974c75d5e30ee16498488fd4e88d8e0a | [
"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 | 7,886 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Binder elimination
-/
import order tactic.converter.old_conv
namespace old_conv
open tactic monad
meta instance : monad_fail old_conv :=
{ fail := λ α s, (λr e, tactic.fail (to_fmt s) : old_conv α), ..old_conv.monad }
meta instance : has_monad_lift tactic old_conv :=
⟨λα, lift_tactic⟩
meta instance (α : Type) : has_coe (tactic α) (old_conv α) :=
⟨monad_lift⟩
meta def current_relation : old_conv name := λr lhs, return ⟨r, lhs, none⟩
meta def head_beta : old_conv unit :=
λ r e, do n ← tactic.head_beta e, return ⟨(), n, none⟩
/- congr should forward data! -/
meta def congr_arg : old_conv unit → old_conv unit := congr_core (return ())
meta def congr_fun : old_conv unit → old_conv unit := λc, congr_core c (return ())
meta def congr_rule (congr : expr) (cs : list (list expr → old_conv unit)) : old_conv unit := λr lhs, do
meta_rhs ← infer_type lhs >>= mk_meta_var, -- is maybe overly restricted for `heq`
t ← mk_app r [lhs, meta_rhs],
((), meta_pr) ← solve_aux t (do
apply congr,
focus $ cs.map $ λc, (do
xs ← intros,
conversion (head_beta >> c xs)),
done),
rhs ← instantiate_mvars meta_rhs,
pr ← instantiate_mvars meta_pr,
return ⟨(), rhs, some pr⟩
meta def congr_binder (congr : name) (cs : expr → old_conv unit) : old_conv unit := do
e ← mk_const congr,
congr_rule e [λbs, do [b] ← return bs, cs b]
meta def funext' : (expr → old_conv unit) → old_conv unit := congr_binder ``_root_.funext
meta def propext' {α : Type} (c : old_conv α) : old_conv α := λr lhs, (do
guard (r = `iff),
c r lhs)
<|> (do
guard (r = `eq),
⟨res, rhs, pr⟩ ← c `iff lhs,
match pr with
| some pr := return ⟨res, rhs, (expr.const `propext [] : expr) lhs rhs pr⟩
| none := return ⟨res, rhs, none⟩
end)
meta def apply (pr : expr) : old_conv unit :=
λ r e, do
sl ← simp_lemmas.mk.add pr,
apply_lemmas sl r e
meta def applyc (n : name) : old_conv unit :=
λ r e, do
sl ← simp_lemmas.mk.add_simp n,
apply_lemmas sl r e
meta def apply' (n : name) : old_conv unit := do
e ← mk_const n,
congr_rule e []
end old_conv
open expr tactic old_conv
/- Binder elimination:
We assume a binder `B : p → Π (α : Sort u), (α → t) → t`, where `t` is a type depending on `p`.
Examples:
∃: there is no `p` and `t` is `Prop`.
⨅, ⨆: here p is `β` and `[complete_lattice β]`, `p` is `β`
Problem: ∀x, _ should be a binder, but is not a constant!
Provide a mechanism to rewrite:
B (x : α) ..x.. (h : x = t), p x = B ..x/t.., p t
Here ..x.. are binders, maybe also some constants which provide commutativity rules with `B`.
-/
meta structure binder_eq_elim :=
(match_binder : expr → tactic (expr × expr)) -- returns the bound type and body
(adapt_rel : old_conv unit → old_conv unit) -- optionally adapt `eq` to `iff`
(apply_comm : old_conv unit) -- apply commutativity rule
(apply_congr : (expr → old_conv unit) → old_conv unit) -- apply congruence rule
(apply_elim_eq : old_conv unit) -- (B (x : β) (h : x = t), s x) = s t
meta def binder_eq_elim.check_eq (b : binder_eq_elim) (x : expr) : expr → tactic unit
| `(@eq %%β %%l %%r) := guard ((l = x ∧ ¬ x.occurs r) ∨ (r = x ∧ ¬ x.occurs l))
| _ := fail "no match"
meta def binder_eq_elim.pull (b : binder_eq_elim) (x : expr) : old_conv unit := do
(β, f) ← lhs >>= (lift_tactic ∘ b.match_binder),
guard (¬ x.occurs β)
<|> b.check_eq x β
<|> (do
b.apply_congr $ λx, binder_eq_elim.pull,
b.apply_comm)
meta def binder_eq_elim.push (b : binder_eq_elim) : old_conv unit :=
b.apply_elim_eq
<|> (do
b.apply_comm,
b.apply_congr $ λx, binder_eq_elim.push)
<|> (do
b.apply_congr $ b.pull,
binder_eq_elim.push)
meta def binder_eq_elim.check (b : binder_eq_elim) (x : expr) : expr → tactic unit
| e := do
(β, f) ← b.match_binder e,
b.check_eq x β
<|> (do
(lam n bi d bd) ← return f,
x ← mk_local' n bi d,
binder_eq_elim.check $ bd.instantiate_var x)
meta def binder_eq_elim.old_conv (b : binder_eq_elim) : old_conv unit := do
(β, f) ← lhs >>= (lift_tactic ∘ b.match_binder),
(lam n bi d bd) ← return f,
x ← mk_local' n bi d,
b.check x (bd.instantiate_var x),
b.adapt_rel b.push
theorem {u v} exists_comm {α : Sort u} {β : Sort v} (p : α → β → Prop) :
(∃a b, p a b) ↔ (∃b a, p a b) :=
⟨λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩, λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩⟩
theorem {u v} exists_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) :
(∃(a':α)(h : a' = a), p a' h) ↔ p a rfl :=
⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩
theorem {u v} exists_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) :
(∃(a':α)(h : a = a'), p a' h) ↔ p a rfl :=
⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩
meta def exists_eq_elim : binder_eq_elim :=
{ match_binder := λe, (do `(@Exists %%β %%f) ← return e, return (β, f)),
adapt_rel := propext',
apply_comm := applyc ``exists_comm,
apply_congr := congr_binder ``exists_congr,
apply_elim_eq := apply' ``exists_elim_eq_left <|> apply' ``exists_elim_eq_right }
theorem {u v} forall_comm {α : Sort u} {β : Sort v} (p : α → β → Prop) :
(∀a b, p a b) ↔ (∀b a, p a b) :=
⟨assume h b a, h a b, assume h b a, h a b⟩
theorem {u v} forall_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) :
(∀(a':α)(h : a' = a), p a' h) ↔ p a rfl :=
⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩
theorem {u v} forall_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) :
(∀(a':α)(h : a = a'), p a' h) ↔ p a rfl :=
⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩
meta def forall_eq_elim : binder_eq_elim :=
{ match_binder := λe, (do (expr.pi n bi d bd) ← return e, return (d, expr.lam n bi d bd)),
adapt_rel := propext',
apply_comm := applyc ``forall_comm,
apply_congr := congr_binder ``forall_congr,
apply_elim_eq := apply' ``forall_elim_eq_left <|> apply' ``forall_elim_eq_right }
meta def supr_eq_elim : binder_eq_elim :=
{ match_binder := λe, (do `(@lattice.supr %%α %%β %%cl %%f) ← return e, return (β, f)),
adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c),
apply_comm := applyc ``lattice.supr_comm,
apply_congr := congr_arg ∘ funext',
apply_elim_eq := applyc ``lattice.supr_supr_eq_left <|> applyc ``lattice.supr_supr_eq_right }
meta def infi_eq_elim : binder_eq_elim :=
{ match_binder := λe, (do `(@lattice.infi %%α %%β %%cl %%f) ← return e, return (β, f)),
adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c),
apply_comm := applyc ``lattice.infi_comm,
apply_congr := congr_arg ∘ funext',
apply_elim_eq := applyc ``lattice.infi_infi_eq_left <|> applyc ``lattice.infi_infi_eq_right }
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} {s t : set α} {a : α}
@[simp] theorem mem_image {f : α → β} {b : β} : b ∈ set.image f s = ∃a, a ∈ s ∧ f a = b := rfl
section
open lattice
variables [complete_lattice α]
theorem Inf_image {s : set β} {f : β → α} : Inf (set.image f s) = (⨅ a ∈ s, f a) :=
begin
simp [Inf_eq_infi, infi_and],
conversion infi_eq_elim.old_conv,
end
theorem Sup_image {s : set β} {f : β → α} : Sup (set.image f s) = (⨆ a ∈ s, f a) :=
begin
simp [Sup_eq_supr, supr_and],
conversion supr_eq_elim.old_conv,
end
end
|
ad1266f443579c6b3d6235ac72e2de3834dfd6c0 | 3c9dc4ea6cc92e02634ef557110bde9eae393338 | /src/Lean/Elab/InfoTree.lean | da26b37f601c0f044d0e957bf39a1722b1d2b9fc | [
"Apache-2.0"
] | permissive | shingtaklam1324/lean4 | 3d7efe0c8743a4e33d3c6f4adbe1300df2e71492 | 351285a2e8ad0cef37af05851cfabf31edfb5970 | refs/heads/master | 1,676,827,679,740 | 1,610,462,623,000 | 1,610,552,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,412 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki, Leonardo de Moura
-/
import Lean.Data.Position
import Lean.Expr
import Lean.Message
import Lean.Data.Json
import Lean.Meta.Basic
import Lean.Meta.PPGoal
namespace Lean.Elab
open Std (PersistentArray PersistentArray.empty PersistentHashMap)
/- Context after executing `liftTermElabM`.
Note that the term information collected during elaboration may contain metavariables, and their
assignments are stored at `mctx`. -/
structure ContextInfo where
env : Environment
mctx : MetavarContext := {}
options : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
deriving Inhabited
structure TermInfo where
lctx : LocalContext -- The local context when the term was elaborated.
expr : Expr
stx : Syntax
deriving Inhabited
/- We store the list of goals before and after the execution of a tactic.
We also store the metavariable context at each time since, we want to unassigned metavariables
at tactic execution time to be displayed as `?m...`. -/
structure TacticInfo where
mctxBefore : MetavarContext
goalsBefore : List MVarId
stx : Syntax
mctxAfter : MetavarContext
goalsAfter : List MVarId
deriving Inhabited
structure MacroExpansionInfo where
lctx : LocalContext -- The local context when the macro was expanded.
before : Syntax
after : Syntax
deriving Inhabited
inductive Info where
| ofTacticInfo (i : TacticInfo)
| ofTermInfo (i : TermInfo)
| ofMacroExpansionInfo (i : MacroExpansionInfo)
deriving Inhabited
inductive InfoTree where
| context (i : ContextInfo) (t : InfoTree) -- The context object is created by `liftTermElabM` at `Command.lean`
| node (i : Info) (children : PersistentArray InfoTree) -- The children contains information for nested term elaboration and tactic evaluation
| ofJson (j : Json) -- For user data
| hole (mvarId : MVarId) -- The elaborator creates holes (aka metavariables) for tactics and postponed terms
deriving Inhabited
structure InfoState where
enabled : Bool := false
assignment : PersistentHashMap MVarId InfoTree := {} -- map from holeId to InfoTree
trees : PersistentArray InfoTree := {}
deriving Inhabited
class MonadInfoTree (m : Type → Type) where
getInfoState : m InfoState
modifyInfoState : (InfoState → InfoState) → m Unit
export MonadInfoTree (getInfoState modifyInfoState)
instance (m n) [MonadInfoTree m] [MonadLift m n] : MonadInfoTree n where
getInfoState := liftM (getInfoState : m _)
modifyInfoState f := liftM (modifyInfoState f : m _)
partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree :=
match tree with
| node i c => node i <| c.map (substitute · assignment)
| context i t => context i (substitute t assignment)
| ofJson j => ofJson j
| hole id => match assignment.find? id with
| none => hole id
| some tree => substitute tree assignment
def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do
let x := x.run { lctx := lctx } { mctx := info.mctx }
let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } { env := info.env }
return a
def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext :=
{ env := info.env, mctx := info.mctx, lctx := lctx,
opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls }
def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do
ppTerm (info.toPPContext lctx) stx
def TermInfo.format (cinfo : ContextInfo) (info : TermInfo) : IO Format := do
cinfo.runMetaM info.lctx do
return f!"{← Meta.ppExpr info.expr} : {← Meta.ppExpr (← Meta.inferType info.expr)}"
def ContextInfo.ppGoals (cinfo : ContextInfo) (goals : List MVarId) : IO Format :=
if goals.isEmpty then
return "no goals"
else
cinfo.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM Meta.ppGoal))
def TacticInfo.format (cinfo : ContextInfo) (info : TacticInfo) : IO Format := do
let cinfoB := { cinfo with mctx := info.mctxBefore }
let cinfoA := { cinfo with mctx := info.mctxAfter }
let goalsBefore ← cinfoB.ppGoals info.goalsBefore
let goalsAfter ← cinfoA.ppGoals info.goalsAfter
return f!"Tactic\nbefore {goalsBefore}\nafter {goalsAfter}"
def MacroExpansionInfo.format (cinfo : ContextInfo) (info : MacroExpansionInfo) : IO Format := do
let before ← cinfo.ppSyntax info.lctx info.before
let after ← cinfo.ppSyntax info.lctx info.after
return f!"Macro expansion\n{before}\n===>\n{after}"
def Info.format (cinfo : ContextInfo) : Info → IO Format
| ofTacticInfo i => i.format cinfo
| ofTermInfo i => i.format cinfo
| ofMacroExpansionInfo i => i.format cinfo
partial def InfoTree.format (tree : InfoTree) (cinfo? : Option ContextInfo := none) : IO Format := do
match tree with
| ofJson j => return toString j
| hole id => return toString id
| context i t => format t i
| node i cs => match cinfo? with
| none => return "<context-not-available>"
| some cinfo =>
if cs.size == 0 then
i.format cinfo
else
return f!"{← i.format cinfo}{Std.Format.nestD <| Std.Format.prefixJoin "\n" (← cs.toList.mapM fun c => format c cinfo?)}"
section
variables [Monad m] [MonadInfoTree m]
@[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
private def getResetInfoTrees : m (PersistentArray InfoTree) := do
let trees := (← getInfoState).trees
modifyInfoTrees fun _ => {}
return trees
def pushInfoTree (t : InfoTree) : m Unit := do
if (← getInfoState).enabled then
modifyInfoTrees fun ts => ts.push t
def mkInfoNode (info : Info) : m Unit := do
if (← getInfoState).enabled then
modifyInfoTrees fun ts => PersistentArray.empty.push <| InfoTree.node info ts
@[inline] def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun a? => do
match a? with
| none => modifyInfoTrees fun _ => treesSaved
| some a => modifyInfoTrees fun trees =>
match (← mkInfo a) with
| Sum.inl info => treesSaved.push <| InfoTree.node info trees
| Sum.inr mvaId => treesSaved.push <| InfoTree.hole mvaId
else
x
@[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α :=
withInfoContext' x fun _ => return Sum.inl (← mkInfo)
def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) :=
return (← getInfoState).assignment[mvarId]
def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do
assert! (← getInfoHoleIdAssignment? mvarId).isNone
modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree }
end
def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (before after : Syntax) (x : m α) : m α :=
let mkInfo : m Info := do
return Info.ofMacroExpansionInfo {
lctx := (← getLCtx)
before := before
after := after
}
withInfoContext x mkInfo
@[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun a? => do
match a? with
| none => modifyInfoTrees fun _ => treesSaved
| some a => modifyInfoState fun s =>
assert! s.trees.size == 1 -- if size is not one, then API is being misused.
{ s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[0] }
else
x
def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit :=
modifyInfoState fun s => { s with enabled := flag }
def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) :=
return (← getInfoState).trees
end Lean.Elab
|
d1a389f1c0d0760633ba243f1e954a00f8916c41 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/back_chaining2.lean | 0a5f423f8c65d55edd05a24bbdd7009e8a4050e9 | [
"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 | 652 | lean | -- Backward chaining with hypotheses
constants {P Q R S T U : Prop}
constants (Huq : U → Q) (Hur : U → R) (Hus : U → S) (Hut : U → T)
attribute Huq [intro]
attribute Hur [intro]
attribute Hus [intro]
attribute Hut [intro]
open tactic
definition lemma1 : (P → Q) → P → Q := by intros >> back_chaining_using_hs
definition lemma2 : (P → Q) → (Q → R) → P → R := by intros >> back_chaining_using_hs
definition lemma3 : (P → Q) → (Q → R) → (R → S) → P → S := by intros >> back_chaining_using_hs
definition lemma4 : (P → Q) → (Q → R) → (R → S) → (S → T) → P → T := by intros >> back_chaining_using_hs
|
28c8fe8c117c8f2e3d4d630740e26c9ce6446f24 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Util/FoldConsts.lean | d45a9fbf3af67c49512d0721a9d45f988ad91956 | [
"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 | 2,514 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.Option
import Init.Lean.Expr
import Init.Lean.Environment
namespace Lean
namespace Expr
namespace FoldConstsImpl
abbrev cacheSize : USize := 8192
structure State :=
(visitedTerms : Array Expr) -- Remark: cache based on pointer address. Our "unsafe" implementation relies on the fact that `()` is not a valid Expr
(visitedConsts : NameHashSet) -- cache based on structural equality
abbrev FoldM := StateM State
@[inline] unsafe def visited (e : Expr) (size : USize) : FoldM Bool := do
s ← get;
let h := ptrAddrUnsafe e;
let i := h % size;
let k := s.visitedTerms.uget i lcProof;
if ptrAddrUnsafe k == h then pure true
else do
modify $ fun s => { visitedTerms := s.visitedTerms.uset i e lcProof, .. s };
pure false
@[specialize] unsafe partial def fold {α : Type} (f : Name → α → α) (size : USize) : Expr → α → FoldM α
| e, acc => condM (liftM $ visited e size) (pure acc) $
match e with
| Expr.forallE _ d b _ => do acc ← fold d acc; fold b acc
| Expr.lam _ d b _ => do acc ← fold d acc; fold b acc
| Expr.mdata _ b _ => fold b acc
| Expr.letE _ t v b _ => do acc ← fold t acc; acc ← fold v acc; fold b acc
| Expr.app f a _ => do acc ← fold f acc; fold a acc
| Expr.proj _ _ b _ => fold b acc
| Expr.const c _ _ => do
s ← get;
if s.visitedConsts.contains c then pure acc
else do
modify $ fun s => { visitedConsts := s.visitedConsts.insert c, .. s };
pure $ f c acc
| _ => pure acc
unsafe def initCache : State :=
{ visitedTerms := mkArray cacheSize.toNat (cast lcProof ()),
visitedConsts := {} }
@[inline] unsafe def foldUnsafe {α : Type} (e : Expr) (init : α) (f : Name → α → α) : α :=
(fold f cacheSize e init).run' initCache
end FoldConstsImpl
/-- Apply `f` to every constant occurring in `e` once. -/
@[implementedBy FoldConstsImpl.foldUnsafe]
constant foldConsts {α : Type} (e : Expr) (init : α) (f : Name → α → α) : α := init
end Expr
def getMaxHeight (env : Environment) (e : Expr) : UInt32 :=
e.foldConsts 0 $ fun constName max =>
match env.find? constName with
| ConstantInfo.defnInfo val =>
match val.hints with
| ReducibilityHints.regular h => if h > max then h else max
| _ => max
| _ => max
end Lean
|
5a6b90a5273824d21d3d50d4f438d504fce0139b | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/smodeq.lean | d7b104a661b9fde8883d6bccee59152561ab0122 | [
"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,412 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import linear_algebra.basic
/-!
# modular equivalence for submodule
-/
open submodule
variables {R : Type*} [ring R]
variables {M : Type*} [add_comm_group M] [module R M] (U U₁ U₂ : submodule R M)
variables {x x₁ x₂ y y₁ y₂ z z₁ z₂ : M}
variables {N : Type*} [add_comm_group N] [module R N] (V V₁ V₂ : submodule R N)
/-- A predicate saying two elements of a module are equivalent modulo a submodule. -/
def smodeq (x y : M) : Prop :=
(submodule.quotient.mk x : U.quotient) = submodule.quotient.mk y
notation x ` ≡ `:50 y ` [SMOD `:50 N `]`:0 := smodeq N x y
variables {U U₁ U₂}
protected lemma smodeq.def : x ≡ y [SMOD U] ↔
(submodule.quotient.mk x : U.quotient) = submodule.quotient.mk y := iff.rfl
namespace smodeq
@[simp] theorem top : x ≡ y [SMOD (⊤ : submodule R M)] :=
(submodule.quotient.eq ⊤).2 mem_top
@[simp] theorem bot : x ≡ y [SMOD (⊥ : submodule R M)] ↔ x = y :=
by rw [smodeq.def, submodule.quotient.eq, mem_bot, sub_eq_zero]
@[mono] theorem mono (HU : U₁ ≤ U₂) (hxy : x ≡ y [SMOD U₁]) : x ≡ y [SMOD U₂] :=
(submodule.quotient.eq U₂).2 $ HU $ (submodule.quotient.eq U₁).1 hxy
@[refl] theorem refl : x ≡ x [SMOD U] := eq.refl _
@[symm] theorem symm (hxy : x ≡ y [SMOD U]) : y ≡ x [SMOD U] := hxy.symm
@[trans] theorem trans (hxy : x ≡ y [SMOD U]) (hyz : y ≡ z [SMOD U]) : x ≡ z [SMOD U] :=
hxy.trans hyz
theorem add (hxy₁ : x₁ ≡ y₁ [SMOD U]) (hxy₂ : x₂ ≡ y₂ [SMOD U]) : x₁ + x₂ ≡ y₁ + y₂ [SMOD U] :=
by { rw smodeq.def at hxy₁ hxy₂ ⊢, simp_rw [quotient.mk_add, hxy₁, hxy₂] }
theorem smul (hxy : x ≡ y [SMOD U]) (c : R) : c • x ≡ c • y [SMOD U] :=
by { rw smodeq.def at hxy ⊢, simp_rw [quotient.mk_smul, hxy] }
theorem zero : x ≡ 0 [SMOD U] ↔ x ∈ U :=
by rw [smodeq.def, submodule.quotient.eq, sub_zero]
theorem map (hxy : x ≡ y [SMOD U]) (f : M →ₗ[R] N) : f x ≡ f y [SMOD U.map f] :=
(submodule.quotient.eq _).2 $ f.map_sub x y ▸ mem_map_of_mem $ (submodule.quotient.eq _).1 hxy
theorem comap {f : M →ₗ[R] N} (hxy : f x ≡ f y [SMOD V]) : x ≡ y [SMOD V.comap f] :=
(submodule.quotient.eq _).2 $ show f (x - y) ∈ V,
from (f.map_sub x y).symm ▸ (submodule.quotient.eq _).1 hxy
end smodeq
|
8cdb06fc33f6f2c4690bac8d3fb733331464399d | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/currying.lean | 486e942a85e7de9324f4853c5dd675f91f59dec4 | [
"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 | 4,223 | 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 category_theory.products.bifunctor
/-!
# Curry and uncurry, as functors.
We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`,
and verify that they provide an equivalence of categories
`currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`.
-/
namespace category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`.
-/
def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) :=
{ obj := λ F,
{ obj := λ X, (F.obj X.1).obj X.2,
map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2,
map_comp' := λ X Y Z f g,
begin
simp only [prod_comp_fst, prod_comp_snd, functor.map_comp,
nat_trans.comp_app, category.assoc],
slice_lhs 2 3 { rw ← nat_trans.naturality },
rw category.assoc,
end },
map := λ F G T,
{ app := λ X, (T.app X.1).app X.2,
naturality' := λ X Y f,
begin
simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc,
functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app],
slice_lhs 2 3 { rw nat_trans.naturality },
slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app] },
rw category.assoc,
end } }.
/--
The object level part of the currying functor. (See `curry` for the functorial version.)
-/
def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) :=
{ obj := λ X,
{ obj := λ Y, F.obj (X, Y),
map := λ Y Y' g, F.map (𝟙 X, g) },
map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } }
/--
The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`.
-/
def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) :=
{ obj := λ F, curry_obj F,
map := λ F G T,
{ app := λ X,
{ app := λ Y, T.app (X, Y),
naturality' := λ Y Y' g,
begin
dsimp [curry_obj],
rw nat_trans.naturality,
end },
naturality' := λ X X' f,
begin
ext, dsimp [curry_obj],
rw nat_trans.naturality,
end } }.
@[simp] lemma uncurry.obj_obj {F : C ⥤ (D ⥤ E)} {X : C × D} :
(uncurry.obj F).obj X = (F.obj X.1).obj X.2 := rfl
@[simp] lemma uncurry.obj_map {F : C ⥤ (D ⥤ E)} {X Y : C × D} {f : X ⟶ Y} :
(uncurry.obj F).map f = ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) := rfl
@[simp] lemma uncurry.map_app {F G : C ⥤ (D ⥤ E)} {α : F ⟶ G} {X : C × D} :
(uncurry.map α).app X = (α.app X.1).app X.2 := rfl
@[simp] lemma curry.obj_obj_obj
{F : (C × D) ⥤ E} {X : C} {Y : D} :
((curry.obj F).obj X).obj Y = F.obj (X, Y) := rfl
@[simp] lemma curry.obj_obj_map
{F : (C × D) ⥤ E} {X : C} {Y Y' : D} {g : Y ⟶ Y'} :
((curry.obj F).obj X).map g = F.map (𝟙 X, g) := rfl
@[simp] lemma curry.obj_map_app {F : (C × D) ⥤ E} {X X' : C} {f : X ⟶ X'} {Y} :
((curry.obj F).map f).app Y = F.map (f, 𝟙 Y) := rfl
@[simp] lemma curry.map_app_app {F G : (C × D) ⥤ E} {α : F ⟶ G} {X} {Y} :
((curry.map α).app X).app Y = α.app (X, Y) := rfl
/--
The equivalence of functor categories given by currying/uncurrying.
-/
@[simps] -- create projection simp lemmas even though this isn't a `{ .. }`.
def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) :=
equivalence.mk uncurry curry
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy))
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, eq_to_iso (by simp)) (by tidy)) (by tidy))
/-- `F.flip` is isomorphic to uncurrying `F`, swapping the variables, and currying. -/
@[simps]
def flip_iso_curry_swap_uncurry (F : C ⥤ D ⥤ E) :
F.flip ≅ curry.obj (prod.swap _ _ ⋙ uncurry.obj F) :=
nat_iso.of_components (λ d, nat_iso.of_components (λ c, eq_to_iso rfl) $ by tidy) $ by tidy
end category_theory
|
c955885af78a88b48acdeff50cedaafb1f0f1aca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/polynomial/monomial.lean | 27bbac66f924d627d0f47759db3d471a8d69d8a2 | [
"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,650 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.basic
/-!
# Univariate monomials
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Preparatory lemmas for degree_basic.
-/
noncomputable theory
namespace polynomial
open_locale polynomial
universes u
variables {R : Type u} {a b : R} {m n : ℕ}
variables [semiring R] {p q r : R[X]}
lemma monomial_one_eq_iff [nontrivial R] {i j : ℕ} :
(monomial i 1 : R[X]) = monomial j 1 ↔ i = j :=
begin
simp_rw [←of_finsupp_single],
exact add_monoid_algebra.of_injective.eq_iff
end
instance [nontrivial R] : infinite R[X] :=
infinite.of_injective (λ i, monomial i 1) $
λ m n h, by simpa [monomial_one_eq_iff] using h
lemma card_support_le_one_iff_monomial {f : R[X]} :
finset.card f.support ≤ 1 ↔ ∃ n a, f = monomial n a :=
begin
split,
{ assume H,
rw finset.card_le_one_iff_subset_singleton at H,
rcases H with ⟨n, hn⟩,
refine ⟨n, f.coeff n, _⟩,
ext i,
by_cases hi : i = n,
{ simp [hi, coeff_monomial] },
{ have : f.coeff i = 0,
{ rw ← not_mem_support_iff,
exact λ hi', hi (finset.mem_singleton.1 (hn hi')) },
simp [this, ne.symm hi, coeff_monomial] } },
{ rintros ⟨n, a, rfl⟩,
rw ← finset.card_singleton n,
apply finset.card_le_of_subset,
exact support_monomial' _ _ }
end
lemma ring_hom_ext {S} [semiring S] {f g : R[X] →+* S}
(h₁ : ∀ a, f (C a) = g (C a)) (h₂ : f X = g X) : f = g :=
begin
set f' := f.comp (to_finsupp_iso R).symm.to_ring_hom with hf',
set g' := g.comp (to_finsupp_iso R).symm.to_ring_hom with hg',
have A : f' = g',
{ ext,
{ simp [h₁, ring_equiv.to_ring_hom_eq_coe] },
{ simpa [ring_equiv.to_ring_hom_eq_coe] using h₂, } },
have B : f = f'.comp (to_finsupp_iso R),
by { rw [hf', ring_hom.comp_assoc], ext x, simp only [ring_equiv.to_ring_hom_eq_coe,
ring_equiv.symm_apply_apply, function.comp_app, ring_hom.coe_comp,
ring_equiv.coe_to_ring_hom] },
have C : g = g'.comp (to_finsupp_iso R),
by { rw [hg', ring_hom.comp_assoc], ext x, simp only [ring_equiv.to_ring_hom_eq_coe,
ring_equiv.symm_apply_apply, function.comp_app, ring_hom.coe_comp,
ring_equiv.coe_to_ring_hom] },
rw [B, C, A]
end
@[ext] lemma ring_hom_ext' {S} [semiring S] {f g : R[X] →+* S}
(h₁ : f.comp C = g.comp C) (h₂ : f X = g X) : f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) h₂
end polynomial
|
cfcde6302bff894125bf6f923412be41aa22a750 | 48eee836fdb5c613d9a20741c17db44c8e12e61c | /src/universal/default.lean | b2160cd18f13e935bc2baca7e4f52d0090427f0d | [
"Apache-2.0"
] | permissive | fgdorais/lean-universal | 06430443a4abe51e303e602684c2977d1f5c0834 | 9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1 | refs/heads/master | 1,592,479,744,136 | 1,589,473,399,000 | 1,589,473,399,000 | 196,287,552 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 255 | lean | -- Copyright © 2019 François G. Dorais. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
import .basic
import .congruence
import .homomorphism
import .identity
import .model
import .proof
import .substitution
|
a657804e5b65697a60d83d95cdd8363caac7c482 | 28be2ab6091504b6ba250b367205fb94d50ab284 | /src/mynat/definition.lean | 4a26128af7df2e00724772e8559df22891959191 | [
"Apache-2.0"
] | permissive | postmasters/natural_number_game | 87304ac22e5e1c5ac2382d6e523d6914dd67a92d | 38a7adcdfdb18c49c87b37831736c8f15300d821 | refs/heads/master | 1,649,856,819,031 | 1,586,444,676,000 | 1,586,444,676,000 | 255,006,061 | 0 | 0 | Apache-2.0 | 1,586,664,599,000 | 1,586,664,598,000 | null | UTF-8 | Lean | false | false | 914 | lean | import tactic.structure_helper
import tactic.nat_num_game
/-
mynat/definition.lean -- definition of mynat.
Supplies:
constants zero : mynat and one : mynat
function S : mynat → mynat
notation 0 for zero and 1 for one.
The below code will be *invisible to the player*
-/
-- definition of "the natural numbers"
inductive mynat
| zero : mynat
| succ (n : mynat) : mynat
namespace mynat
instance : has_zero mynat := ⟨mynat.zero⟩
@[leakage] theorem mynat_zero_eq_zero : mynat.zero = 0 := rfl
def one : mynat := succ 0
instance : has_one mynat := ⟨mynat.one⟩
theorem one_eq_succ_zero : 1 = succ 0 := rfl
lemma zero_ne_succ (m : mynat) : (0 : mynat) ≠ succ m := λ h, by cases h
lemma succ_inj {m n : mynat} (h : succ m = succ n) : m = n := by cases h; refl
end mynat
theorem ne_iff_implies_false ⦃a b : mynat⦄ :
a ≠ b ↔ (a = b) → false := iff.rfl
attribute [symm] ne.symm
|
3d8ddeb5f8466ce26597f2e3d666a0ff2eff7a69 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /hott/types/trunc.hlean | f3212cac371819ce7a8ff6145bec4baf1e8e32a0 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,201 | hlean | /-
Copyright (c) 2015 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Properties of is_trunc and trunctype
-/
-- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .hprop_trunc
import types.pi types.eq types.equiv ..function
open eq sigma sigma.ops pi function equiv is_trunc.trunctype
is_equiv prod is_trunc.trunc_index pointed nat
namespace is_trunc
variables {A B : Type} {n : trunc_index}
/- theorems about trunctype -/
protected definition trunctype.sigma_char.{l} (n : trunc_index) :
(trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) :=
begin
fapply equiv.MK,
{ intro A, exact (⟨carrier A, struct A⟩)},
{ intro S, exact (trunctype.mk S.1 S.2)},
{ intro S, induction S with S1 S2, reflexivity},
{ intro A, induction A with A1 A2, reflexivity},
end
definition trunctype_eq_equiv (n : trunc_index) (A B : n-Type) :
(A = B) ≃ (carrier A = carrier B) :=
calc
(A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B)
: eq_equiv_fn_eq_of_equiv
... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1)
: equiv.symm (!equiv_subtype)
... ≃ (carrier A = carrier B) : equiv.refl
theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B]
(Hn : -1 ≤ n) : is_trunc n A :=
begin
induction n with n,
{exact !empty.elim Hn},
{apply is_trunc_succ_intro, intro a a',
fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)}
end
theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f]
(n : trunc_index) [HA : is_trunc n A] : is_trunc n B :=
begin
revert A B f Hf HA,
induction n with n IH,
{ intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk,
{ exact f (center A)},
{ intro b, apply concat,
{ apply (ap f), exact (center_eq (g b))},
{ apply ε}}},
{ intro A B f Hf HA, induction Hf with g ε,
apply is_trunc_succ_intro, intro b b',
fapply (IH (g b = g b')),
{ intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')},
{ apply (is_retraction.mk (ap g)),
{ intro p, induction p, {rewrite [↑ap, con.left_inv]}}},
{ apply is_trunc_eq}}
end
definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) :=
λf f', !is_equiv_ap_to_fun
theorem is_trunc_trunctype [instance] (n : trunc_index) : is_trunc n.+1 (n-Type) :=
begin
apply is_trunc_succ_intro, intro X Y,
fapply is_trunc_equiv_closed,
{apply equiv.symm, apply trunctype_eq_equiv},
fapply is_trunc_equiv_closed,
{apply equiv.symm, apply eq_equiv_equiv},
induction n,
{apply @is_contr_of_inhabited_hprop,
{apply is_trunc_is_embedding_closed,
{apply is_embedding_to_fun} ,
{exact unit.star}},
{apply equiv_of_is_contr_of_is_contr}},
{apply is_trunc_is_embedding_closed,
{apply is_embedding_to_fun},
{exact unit.star}}
end
/- theorems about decidable equality and axiom K -/
theorem is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A :=
is_hset.mk _ (λa b p q, eq.rec_on q K p)
theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u})
(mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a)
(imp : Π{a b : A}, R a b → a = b) : is_hset A :=
is_hset_of_axiom_K
(λa p,
have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apd,
have H3 : Π(r : R a a), transport (λx, a = x) p (imp r)
= imp (transport (λx, R a x) p r), from
to_fun (equiv.symm !heq_pi) H2,
have H4 : imp (refl a) ⬝ p = imp (refl a), from
calc
imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r
... = imp (transport (λx, R a x) p (refl a)) : H3
... = imp (refl a) : is_hprop.elim,
cancel_left H4)
definition relation_equiv_eq {A : Type} (R : A → A → Type)
(mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a)
(imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b :=
@equiv_of_is_hprop _ _ _
(@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b)
imp
(λp, p ▸ refl a)
local attribute not [reducible]
theorem is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b)
: is_hset A :=
is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H
section
open decidable
--this is proven differently in init.hedberg
theorem is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A :=
is_hset_of_double_neg_elim (λa b, by_contradiction)
end
theorem is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n)
(K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A :=
@is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K))
theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a))
: is_trunc (n.+1) A :=
begin
apply is_trunc_succ_intro, intros a a',
apply is_trunc_of_imp_is_trunc_of_leq Hn, intro p,
induction p, apply Hp
end
theorem is_hprop_iff_is_contr {A : Type} (a : A) :
is_hprop A ↔ is_contr A :=
iff.intro (λH, is_contr.mk a (is_hprop.elim a)) _
theorem is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) :
is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) :=
iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn)
theorem is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type)
: is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](Pointed.mk a)) :=
begin
revert A, induction n with n IH,
{ intro A, esimp [Iterated_loop_space], transitivity _,
{ apply is_trunc_succ_iff_is_trunc_loop, apply le.refl},
{ apply iff.pi_iff_pi, intro a, esimp, apply is_hprop_iff_is_contr, reflexivity}},
{ intro A, esimp [Iterated_loop_space],
transitivity _, apply @is_trunc_succ_iff_is_trunc_loop @n, esimp, constructor,
apply iff.pi_iff_pi, intro a, transitivity _, apply IH,
transitivity _, apply iff.pi_iff_pi, intro p,
rewrite [iterated_loop_space_loop_irrel n p], apply iff.refl, esimp,
apply iff.imp_iff, reflexivity}
end
theorem is_trunc_iff_is_contr_loop (n : ℕ) (A : Type)
: is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) :=
begin
induction n with n,
{ esimp [sub_two,Iterated_loop_space], apply iff.intro,
intro H a, exact is_contr_of_inhabited_hprop a,
intro H, apply is_hprop_of_imp_is_contr, exact H},
{ apply is_trunc_iff_is_contr_loop_succ},
end
theorem is_contr_loop_of_is_trunc (n : ℕ) (A : Type*) [H : is_trunc (n.-2.+1) A] :
is_contr (Ω[n] A) :=
by induction A; exact iff.mp !is_trunc_iff_is_contr_loop _ _
end is_trunc open is_trunc
namespace trunc
variable {A : Type}
protected definition code (n : trunc_index) (aa aa' : trunc n.+1 A) : n-Type :=
trunc.rec_on aa (λa, trunc.rec_on aa' (λa', trunctype.mk' n (trunc n (a = a'))))
protected definition encode (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' → trunc.code n aa aa' :=
begin
intro p, induction p, apply (trunc.rec_on aa),
intro a, esimp [trunc.code,trunc.rec_on], exact (tr idp)
end
protected definition decode (n : trunc_index) (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' :=
begin
eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa),
intro a a' x, esimp [trunc.code, trunc.rec_on] at x,
apply (trunc.rec_on x), intro p, exact (ap tr p)
end
definition trunc_eq_equiv [constructor] (n : trunc_index) (aa aa' : trunc n.+1 A)
: aa = aa' ≃ trunc.code n aa aa' :=
begin
fapply equiv.MK,
{ apply trunc.encode},
{ apply trunc.decode},
{ eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa),
intro a a' x, esimp [trunc.code, trunc.rec_on] at x,
refine (@trunc.rec_on n _ _ x _ _),
intro x, apply is_trunc_eq,
intro p, induction p, reflexivity},
{ intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp},
end
definition tr_eq_tr_equiv [constructor] (n : trunc_index) (a a' : A)
: (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') :=
!trunc_eq_equiv
definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type)
(n m : trunc_index) [H : is_trunc n A] : is_trunc n (trunc m A) :=
begin
revert A m H, eapply (trunc_index.rec_on n),
{ clear n, intro A m H, apply is_contr_equiv_closed,
{ apply equiv.symm, apply trunc_equiv, apply (@is_trunc_of_leq _ -2), exact unit.star} },
{ clear n, intro n IH A m H, induction m with m,
{ apply (@is_trunc_of_leq _ -2), exact unit.star},
{ apply is_trunc_succ_intro, intro aa aa',
apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_hprop)),
eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_hprop)),
intro a a', apply (is_trunc_equiv_closed_rev),
{ apply tr_eq_tr_equiv},
{ exact (IH _ _ _)}}}
end
open equiv.ops
definition unique_choice {P : A → Type} [H : Πa, is_hprop (P a)] (f : Πa, ∥ P a ∥) (a : A)
: P a :=
!trunc_equiv (f a)
/- transport over a truncated family -/
definition trunc_transport {a a' : A} {P : A → Type} (p : a = a') (n : trunc_index) (x : P a)
: transport (λa, trunc n (P a)) p (tr x) = tr (p ▸ x) :=
by induction p; reflexivity
definition image {A B : Type} (f : A → B) (b : B) : hprop := ∃(a : A), f a = b
end trunc open trunc
namespace function
variables {A B : Type}
definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f :=
λb, !center
definition is_equiv_equiv_is_embedding_times_is_surjective [constructor] (f : A → B)
: is_equiv f ≃ (is_embedding f × is_surjective f) :=
equiv_of_is_hprop (λH, (_, _))
(λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding))
end function
|
95156e3c60d259bb4d23a629acadea3f32a9035f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/power_basis_auto.lean | 2258e00c9b8fe158d6893ba3ea0eff88124698d9 | [] | 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 | 16,240 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.field_theory.adjoin
import Mathlib.field_theory.minpoly
import Mathlib.ring_theory.adjoin
import Mathlib.ring_theory.adjoin_root
import Mathlib.ring_theory.algebraic
import Mathlib.PostPort
universes u_8 u_9 l u_2 u_6 u_1 u_4 u_7
namespace Mathlib
/-!
# Power basis
This file defines a structure `power_basis R S`, giving a basis of the
`R`-algebra `S` as a finite list of powers `1, x, ..., x^n`.
There are also constructors for `power_basis` when adjoining an algebraic
element to a ring/field.
## Definitions
* `power_basis R A`: a structure containing an `x` and an `n` such that
`1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module).
* `findim (hf : f ≠ 0) : finite_dimensional.findim K (adjoin_root f) = f.nat_degree`,
the dimension of `adjoin_root f` equals the degree of `f`
* `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same
equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y`
* `power_basis.equiv`: if two power bases satisfy the same equations, they are
equivalent as algebras
## Implementation notes
Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are
`integral_domain`s and `K`, `L`, ... are `field`s.
`S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra.
## Tags
power basis, powerbasis
-/
/-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)`
is a basis for the `R`-algebra `S` (viewed as `R`-module).
This is a structure, not a class, since the same algebra can have many power bases.
For the common case where `S` is defined by adjoining an integral element to `R`,
the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`.
-/
structure power_basis (R : Type u_8) (S : Type u_9) [comm_ring R] [ring S] [algebra R S] where
gen : S
dim : ℕ
is_basis : is_basis R fun (i : fin dim) => gen ^ ↑i
namespace power_basis
/-- Cannot be an instance because `power_basis` cannot be a class. -/
theorem finite_dimensional {S : Type u_2} [comm_ring S] {K : Type u_6} [field K] [algebra K S]
(pb : power_basis K S) : finite_dimensional K S :=
finite_dimensional.of_fintype_basis (is_basis pb)
theorem findim {S : Type u_2} [comm_ring S] {K : Type u_6} [field K] [algebra K S]
(pb : power_basis K S) : finite_dimensional.findim K S = dim pb :=
sorry
/-- TODO: this mixes `polynomial` and `finsupp`, we should hide this behind a
new function `polynomial.of_finsupp`. -/
theorem polynomial.mem_supported_range {R : Type u_1} [comm_ring R] {f : polynomial R} {d : ℕ} :
f ∈ finsupp.supported R R ↑(finset.range d) ↔ polynomial.degree f < ↑d :=
sorry
theorem mem_span_pow' {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] [algebra R S]
{x : S} {y : S} {d : ℕ} :
y ∈ submodule.span R (set.range fun (i : fin d) => x ^ ↑i) ↔
∃ (f : polynomial R), polynomial.degree f < ↑d ∧ y = coe_fn (polynomial.aeval x) f :=
sorry
theorem mem_span_pow {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] [algebra R S] {x : S}
{y : S} {d : ℕ} (hd : d ≠ 0) :
y ∈ submodule.span R (set.range fun (i : fin d) => x ^ ↑i) ↔
∃ (f : polynomial R), polynomial.nat_degree f < d ∧ y = coe_fn (polynomial.aeval x) f :=
sorry
theorem dim_ne_zero {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] [algebra R S]
[nontrivial S] (pb : power_basis R S) : dim pb ≠ 0 :=
sorry
theorem exists_eq_aeval {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] [algebra R S]
[nontrivial S] (pb : power_basis R S) (y : S) :
∃ (f : polynomial R),
polynomial.nat_degree f < dim pb ∧ y = coe_fn (polynomial.aeval (gen pb)) f :=
iff.mp (mem_span_pow (dim_ne_zero pb)) (is_basis.mem_span (is_basis pb) y)
/-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`.
If `A` is not a field, it might not necessarily be *the* minimal polynomial,
however `nat_degree_minpoly` shows its degree is indeed minimal.
-/
def minpoly_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A] [algebra A S]
(pb : power_basis A S) : polynomial A :=
polynomial.X ^ dim pb -
finset.sum finset.univ
fun (i : fin (dim pb)) =>
coe_fn polynomial.C (coe_fn (coe_fn (is_basis.repr sorry) (gen pb ^ dim pb)) i) *
polynomial.X ^ ↑i
@[simp] theorem nat_degree_minpoly_gen {S : Type u_2} [comm_ring S] {A : Type u_4}
[integral_domain A] [algebra A S] (pb : power_basis A S) :
polynomial.nat_degree (minpoly_gen pb) = dim pb :=
sorry
theorem minpoly_gen_monic {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] (pb : power_basis A S) : polynomial.monic (minpoly_gen pb) :=
sorry
@[simp] theorem aeval_minpoly_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] (pb : power_basis A S) :
coe_fn (polynomial.aeval (gen pb)) (minpoly_gen pb) = 0 :=
sorry
theorem is_integral_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] (pb : power_basis A S) : is_integral A (gen pb) :=
Exists.intro (minpoly_gen pb) { left := minpoly_gen_monic pb, right := aeval_minpoly_gen pb }
theorem dim_le_nat_degree_of_root {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0)
(root : coe_fn (polynomial.aeval (gen h)) p = 0) : dim h ≤ polynomial.nat_degree p :=
sorry
@[simp] theorem nat_degree_minpoly {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] (pb : power_basis A S) : polynomial.nat_degree (minpoly A (gen pb)) = dim pb :=
sorry
theorem nat_degree_lt_nat_degree {R : Type u_1} [comm_ring R] {p : polynomial R} {q : polynomial R}
(hp : p ≠ 0) (hpq : polynomial.degree p < polynomial.degree q) :
polynomial.nat_degree p < polynomial.nat_degree q :=
sorry
theorem constr_pow_aeval {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] (pb : power_basis A S) {y : S'}
(hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) (f : polynomial A) :
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i)
(coe_fn (polynomial.aeval (gen pb)) f) =
coe_fn (polynomial.aeval y) f :=
sorry
theorem constr_pow_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A] [algebra A S]
{S' : Type u_8} [comm_ring S'] [algebra A S'] (pb : power_basis A S) {y : S'}
(hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) :
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i) (gen pb) = y :=
sorry
theorem constr_pow_algebra_map {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] (pb : power_basis A S) {y : S'}
(hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) (x : A) :
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i)
(coe_fn (algebra_map A S) x) =
coe_fn (algebra_map A S') x :=
sorry
theorem constr_pow_mul {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A] [algebra A S]
{S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] (pb : power_basis A S) {y : S'}
(hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) (x : S) (x' : S) :
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i) (x * x') =
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i) x *
coe_fn (is_basis.constr (is_basis pb) fun (i : fin (dim pb)) => y ^ ↑i) x' :=
sorry
/-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`,
where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. -/
def lift {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A] [algebra A S]
{S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] (pb : power_basis A S) (y : S')
(hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) : alg_hom A S S' :=
alg_hom.mk (linear_map.to_fun (is_basis.constr sorry fun (i : fin (dim pb)) => y ^ ↑i)) sorry
(constr_pow_mul pb hy) sorry sorry (constr_pow_algebra_map pb hy)
@[simp] theorem lift_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S]
(pb : power_basis A S) (y : S') (hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0) :
coe_fn (lift pb y hy) (gen pb) = y :=
constr_pow_gen pb hy
@[simp] theorem lift_aeval {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S]
(pb : power_basis A S) (y : S') (hy : coe_fn (polynomial.aeval y) (minpoly A (gen pb)) = 0)
(f : polynomial A) :
coe_fn (lift pb y hy) (coe_fn (polynomial.aeval (gen pb)) f) = coe_fn (polynomial.aeval y) f :=
constr_pow_aeval pb hy f
/-- `pb.equiv pb' h` is an equivalence of algebras with the same power basis. -/
def equiv {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A] [algebra A S]
{S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A (gen pb) = minpoly A (gen pb')) :
alg_equiv A S S' :=
alg_equiv.of_alg_hom (lift pb (gen pb') sorry) (lift pb' (gen pb) sorry) sorry sorry
@[simp] theorem equiv_aeval {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A (gen pb) = minpoly A (gen pb'))
(f : polynomial A) :
coe_fn (equiv pb pb' h) (coe_fn (polynomial.aeval (gen pb)) f) =
coe_fn (polynomial.aeval (gen pb')) f :=
lift_aeval pb (gen pb') (Eq.symm h ▸ minpoly.aeval A (gen pb')) f
@[simp] theorem equiv_gen {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A (gen pb) = minpoly A (gen pb')) :
coe_fn (equiv pb pb' h) (gen pb) = gen pb' :=
lift_gen pb (gen pb') (Eq.symm h ▸ minpoly.aeval A (gen pb'))
@[simp] theorem equiv_symm {S : Type u_2} [comm_ring S] {A : Type u_4} [integral_domain A]
[algebra A S] {S' : Type u_8} [comm_ring S'] [algebra A S'] [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A (gen pb) = minpoly A (gen pb')) :
alg_equiv.symm (equiv pb pb' h) = equiv pb' pb (Eq.symm h) :=
rfl
end power_basis
namespace algebra
theorem mem_span_power_basis {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] [algebra R S]
[nontrivial R] {x : S} {y : S} (hx : is_integral R x)
(hy : ∃ (f : polynomial R), y = coe_fn (polynomial.aeval x) f) :
y ∈
submodule.span R
(set.range fun (i : fin (polynomial.nat_degree (minpoly R x))) => x ^ ↑i) :=
sorry
theorem linear_independent_power_basis {S : Type u_2} [comm_ring S] {K : Type u_6} [field K]
[algebra K S] {x : S} (hx : is_integral K x) :
linear_independent K fun (i : fin (polynomial.nat_degree (minpoly K x))) => x ^ ↑i :=
sorry
theorem power_basis_is_basis {S : Type u_2} [comm_ring S] {K : Type u_6} [field K] [algebra K S]
{x : S} (hx : is_integral K x) :
is_basis K
fun (i : fin (polynomial.nat_degree (minpoly K x))) =>
{ val := x, property := subset_adjoin (set.mem_singleton x) } ^ ↑i :=
sorry
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K[x]`,
where `d` is the degree of the minimal polynomial of `x`. -/
def adjoin.power_basis {S : Type u_2} [comm_ring S] {K : Type u_6} [field K] [algebra K S] {x : S}
(hx : is_integral K x) : power_basis K ↥(adjoin K (singleton x)) :=
power_basis.mk { val := x, property := sorry } (polynomial.nat_degree (minpoly K x))
(power_basis_is_basis hx)
end algebra
namespace adjoin_root
theorem power_basis_is_basis {K : Type u_6} [field K] {f : polynomial K} (hf : f ≠ 0) :
is_basis K fun (i : fin (polynomial.nat_degree f)) => root f ^ subtype.val i :=
sorry
/-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
def power_basis {K : Type u_6} [field K] {f : polynomial K} (hf : f ≠ 0) :
power_basis K (adjoin_root f) :=
power_basis.mk (root f) (polynomial.nat_degree f) (power_basis_is_basis hf)
end adjoin_root
namespace intermediate_field
theorem power_basis_is_basis {K : Type u_6} {L : Type u_7} [field K] [field L] [algebra K L] {x : L}
(hx : is_integral K x) :
is_basis K fun (i : fin (polynomial.nat_degree (minpoly K x))) => adjoin_simple.gen K x ^ ↑i :=
sorry
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
def adjoin.power_basis {K : Type u_6} {L : Type u_7} [field K] [field L] [algebra K L] {x : L}
(hx : is_integral K x) : power_basis K ↥(adjoin K (insert.insert ∅ x)) :=
power_basis.mk (adjoin_simple.gen K x) (polynomial.nat_degree (minpoly K x))
(power_basis_is_basis hx)
@[simp] theorem adjoin.power_basis.gen_eq {K : Type u_6} {L : Type u_7} [field K] [field L]
[algebra K L] {x : L} (hx : is_integral K x) :
power_basis.gen (adjoin.power_basis hx) = adjoin_simple.gen K x :=
rfl
theorem adjoin.finite_dimensional {K : Type u_6} {L : Type u_7} [field K] [field L] [algebra K L]
{x : L} (hx : is_integral K x) : finite_dimensional K ↥(adjoin K (insert.insert ∅ x)) :=
power_basis.finite_dimensional (adjoin.power_basis hx)
theorem adjoin.findim {K : Type u_6} {L : Type u_7} [field K] [field L] [algebra K L] {x : L}
(hx : is_integral K x) :
finite_dimensional.findim K ↥(adjoin K (insert.insert ∅ x)) =
polynomial.nat_degree (minpoly K x) :=
sorry
end intermediate_field
namespace power_basis
/-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/
def equiv_adjoin_simple {K : Type u_6} {L : Type u_7} [field K] [field L] [algebra K L]
(pb : power_basis K L) :
alg_equiv K (↥(intermediate_field.adjoin K (intermediate_field.insert.insert ∅ (gen pb)))) L :=
equiv (intermediate_field.adjoin.power_basis sorry) pb sorry
@[simp] theorem equiv_adjoin_simple_aeval {K : Type u_6} {L : Type u_7} [field K] [field L]
[algebra K L] (pb : power_basis K L) (f : polynomial K) :
coe_fn (equiv_adjoin_simple pb)
(coe_fn (polynomial.aeval (intermediate_field.adjoin_simple.gen K (gen pb))) f) =
coe_fn (polynomial.aeval (gen pb)) f :=
equiv_aeval (intermediate_field.adjoin.power_basis (equiv_adjoin_simple._proof_3 pb)) pb
(equiv_adjoin_simple._proof_4 pb) f
@[simp] theorem equiv_adjoin_simple_gen {K : Type u_6} {L : Type u_7} [field K] [field L]
[algebra K L] (pb : power_basis K L) :
coe_fn (equiv_adjoin_simple pb) (intermediate_field.adjoin_simple.gen K (gen pb)) = gen pb :=
equiv_gen (intermediate_field.adjoin.power_basis (equiv_adjoin_simple._proof_3 pb)) pb
(equiv_adjoin_simple._proof_4 pb)
@[simp] theorem equiv_adjoin_simple_symm_aeval {K : Type u_6} {L : Type u_7} [field K] [field L]
[algebra K L] (pb : power_basis K L) (f : polynomial K) :
coe_fn (alg_equiv.symm (equiv_adjoin_simple pb)) (coe_fn (polynomial.aeval (gen pb)) f) =
coe_fn (polynomial.aeval (intermediate_field.adjoin_simple.gen K (gen pb))) f :=
sorry
@[simp] theorem equiv_adjoin_simple_symm_gen {K : Type u_6} {L : Type u_7} [field K] [field L]
[algebra K L] (pb : power_basis K L) :
coe_fn (alg_equiv.symm (equiv_adjoin_simple pb)) (gen pb) =
intermediate_field.adjoin_simple.gen K (gen pb) :=
sorry
end Mathlib |
60b9f35f809017194147c5038221ee52b402b604 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/Frontend.lean | 631e5a8e820b5bb821fba75d57fef98ed8e1de43 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 5,265 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Elab.Import
import Lean.Elab.Command
import Lean.Util.Profile
import Lean.Server.References
namespace Lean.Elab.Frontend
structure State where
commandState : Command.State
parserState : Parser.ModuleParserState
cmdPos : String.Pos
commands : Array Syntax := #[]
structure Context where
inputCtx : Parser.InputContext
abbrev FrontendM := ReaderT Context $ StateRefT State IO
def setCommandState (commandState : Command.State) : FrontendM Unit :=
modify fun s => { s with commandState := commandState }
@[inline] def runCommandElabM (x : Command.CommandElabM α) : FrontendM α := do
let ctx ← read
let s ← get
let cmdCtx : Command.Context := {
cmdPos := s.cmdPos
fileName := ctx.inputCtx.fileName
fileMap := ctx.inputCtx.fileMap
tacticCache? := none
}
match (← liftM <| EIO.toIO' <| (x cmdCtx).run s.commandState) with
| Except.error e => throw <| IO.Error.userError s!"unexpected internal error: {← e.toMessageData.toString}"
| Except.ok (a, sNew) => setCommandState sNew; return a
def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do
runCommandElabM do
Command.elabCommandTopLevel stx
def updateCmdPos : FrontendM Unit := do
modify fun s => { s with cmdPos := s.parserState.pos }
def getParserState : FrontendM Parser.ModuleParserState := do pure (← get).parserState
def getCommandState : FrontendM Command.State := do pure (← get).commandState
def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps }
def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } }
def getInputContext : FrontendM Parser.InputContext := do pure (← read).inputCtx
def processCommand : FrontendM Bool := do
updateCmdPos
let cmdState ← getCommandState
let ictx ← getInputContext
let pstate ← getParserState
let scope := cmdState.scopes.head!
let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls }
match profileit "parsing" scope.opts fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with
| (cmd, ps, messages) =>
modify fun s => { s with commands := s.commands.push cmd }
setParserState ps
setMessages messages
if Parser.isEOI cmd || Parser.isExitCommand cmd then
pure true -- Done
else
profileitM IO.Error "elaboration" scope.opts <| elabCommandAtFrontend cmd
pure false
partial def processCommands : FrontendM Unit := do
let done ← processCommand
unless done do
processCommands
end Frontend
open Frontend
def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do
let (_, s) ← (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos }
pure s
def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do
let fileName := fileName.getD "<input>"
let inputCtx := Parser.mkInputContext input fileName
let s ← IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts)
pure (s.commandState.env, s.commandState.messages)
builtin_initialize
registerOption `printMessageEndPos { defValue := false, descr := "print end position of each message in addition to start position" }
registerTraceClass `Elab.info
def getPrintMessageEndPos (opts : Options) : Bool :=
opts.getBool `printMessageEndPos false
@[export lean_run_frontend]
def runFrontend
(input : String)
(opts : Options)
(fileName : String)
(mainModuleName : Name)
(trustLevel : UInt32 := 0)
(ileanFileName? : Option String := none)
: IO (Environment × Bool) := do
let inputCtx := Parser.mkInputContext input fileName
let (header, parserState, messages) ← Parser.parseHeader inputCtx
let (env, messages) ← processHeader header opts messages inputCtx trustLevel
let env := env.setMainModule mainModuleName
let mut commandState := Command.mkState env messages opts
if ileanFileName?.isSome then
-- Collect InfoTrees so we can later extract and export their info to the ilean file
commandState := { commandState with infoState.enabled := true }
let s ← IO.processCommands inputCtx parserState commandState
for msg in s.commandState.messages.toList do
IO.print (← msg.toString (includeEndPos := getPrintMessageEndPos opts))
if let some ileanFileName := ileanFileName? then
let trees := s.commandState.infoState.trees.toArray
let references := Lean.Server.findModuleRefs inputCtx.fileMap trees (localVars := false)
let ilean := { module := mainModuleName, references : Lean.Server.Ilean }
IO.FS.writeFile ileanFileName $ Json.compress $ toJson ilean
pure (s.commandState.env, !s.commandState.messages.hasErrors)
end Lean.Elab
|
fc5638f02ab1218f0b5875ea305e5f571d35435e | e07b1aca72e83a272dd59d24c6e0fa246034d774 | /src/tutorials/02_iff_if_and.lean | 68fa58d72f63d09954c1c2f3d9df5be4af29497c | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pedrominicz/learn | 637a343bd4f8669d76819ac660a2d2d3e0958710 | b79b802a9846c86c21d4b6f3e17af36e7382f0ef | refs/heads/master | 1,671,746,990,402 | 1,670,778,113,000 | 1,670,778,113,000 | 265,735,177 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,898 | lean | import data.real.basic
/-
In the previous file, we saw how to rewrite using equalities.
The analogue operation with mathematical statements is rewriting using
equivalences. This is also done using the `rw` tactic.
Lean uses ↔ to denote equivalence instead of ⇔.
In the following exercises we will use the lemma:
sub_nonneg {x y : ℝ} : 0 ≤ y - x ↔ x ≤ y
The curly braces around x and y instead of parentheses mean Lean will always try to figure out what
x and y are from context, unless we really insist on telling it (we'll see how to insist much later).
Let's not worry about that for now.
In order to announce an intermediate statement we use:
have my_name : my statement,
This triggers the apparition of a new goal: proving the statement. After this is done,
the statement becomes available under the name `my_name`.
We can focus on the current goal by typing tactics between curly braces.
-/
example {a b c : ℝ} (hab : a ≤ b) : c + a ≤ c + b :=
begin
rw ←sub_nonneg,
have key : (c + b) - (c + a) = b - a, -- Here we introduce an intermediate statement named key
{ ring, }, -- and prove it between curly braces
rw key, -- we can now use the key statement
rw sub_nonneg,
exact hab,
end
/-
Of course the previous lemma is already in the core library, named `add_le_add_left`, so we can use it below.
Let's prove a variation (without invoking commutativity of addition since this would spoil our fun).
-/
example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c :=
by linarith
-- 0009
example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c :=
begin
rwa [←sub_nonneg, show (b + c) - (a + c) = b - a, by ring, sub_nonneg],
end
/-
Let's see how we could use this lemma. It is already in the core library, under the name `add_le_add_right`:
add_le_add_right {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c
This can be read as: "add_le_add_right is a function that will take as input real numbers a and b, an
assumption `hab` claiming a ≤ b and a real number c, and will output a proof of a + c ≤ b + c".
In addition, recall that curly braces around a b mean Lean will figure out those arguments unless we
insist to help. This is because they can be deduced from the next argument `hab`.
So it will be sufficient to feed `hab` and c to this function.
-/
example {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b :=
begin
calc b = 0 + b : by ring
... ≤ a + b : by exact add_le_add_right ha b,
end
/-
In the second line of the above proof, we need to prove 0 + b ≤ a + b.
The proof after the colon says: this is exactly lemma `add_le_add_right` applied to ha and b.
Actually the `calc` block expects proof terms, and the `by` keyword is used to tell Lean we will use tactics
to build such a proof term. But since the only tactic used in this block is `exact`, we can skip
tactics entirely, and write:
-/
example (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b :=
begin
calc b = 0 + b : by ring
... ≤ a + b : add_le_add_right ha b,
end
/- Let's do a variant. -/
-- 0010
example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b :=
begin
calc
a = a + 0 : by ring
... ≤ a + b : add_le_add_left hb a,
end
/-
The two preceding examples are in the core library :
le_add_of_nonneg_left {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b
le_add_of_nonneg_right {a b : ℝ} (hb : 0 ≤ b) : a ≤ a + b
Again, there won't be any need to memorize those names, we will
soon see how to get rid of such goals automatically.
But we can already try to understand how their names are built:
"le_add" describe the conclusion "less or equal than some addition"
It comes first because we are focussed on proving stuff, and
auto-completion works by looking at the beginning of words.
"of" introduces assumptions. "nonneg" is Lean's abbreviation for non-negative.
"left" or "right" disambiguates between the two variations.
Let's use those lemmas by hand for now.
-/
-- 0011
example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b :=
begin
calc
0 ≤ a : ha
... ≤ a + b : le_add_of_nonneg_right hb,
end
/- And let's combine with our earlier lemmas. -/
-- 0012
example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d :=
begin
calc
a + c ≤ b + c : add_le_add_right hab c
... ≤ b + d : add_le_add_left hcd b,
end
/-
In the above examples, we prepared proofs of assumptions of our lemmas beforehand, so
that we could feed them to the lemmas. This is called forward reasonning.
The `calc` proofs also belong to this category.
We can also announce the use of a lemma, and provide proofs after the fact, using
the `apply` tactic. This is called backward reasonning because we get the conclusion
first, and provide proofs later. Using `rw` on the goal (rather than on an assumption
from the local context) is also backward reasonning.
Let's do that using the lemma
mul_nonneg' {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : 0 ≤ x*y
-/
example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c :=
begin
rw ← sub_nonneg,
have key : b*c - a*c = (b - a)*c,
{ ring },
rw key,
apply mul_nonneg', -- Here we don't provide proofs for the lemma's assumptions
-- Now we need to provide the proofs.
{ rw sub_nonneg,
exact hab },
{ exact hc },
end
/-
Let's prove the same statement using only forward reasonning: announcing stuff,
proving it by working with known facts, moving forward.
-/
example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c :=
begin
have hab' : 0 ≤ b - a,
{ rw ← sub_nonneg at hab,
exact hab, },
have h₁ : 0 ≤ (b - a)*c,
{ exact mul_nonneg' hab' hc },
have h₂ : (b - a)*c = b*c - a*c,
{ ring, },
have h₃ : 0 ≤ b*c - a*c,
{ rw h₂ at h₁,
exact h₁, },
rw sub_nonneg at h₃,
exact h₃,
end
/-
One reason why the backward reasoning proof is shorter is because Lean can
infer of lot of things by comparing the goal and the lemma statement. Indeed
in the `apply mul_nonneg'` line, we didn't need to tell Lean that x = b - a
and y = c in the lemma. It was infered by "unification" between the lemma
statement and the goal.
To be fair to the forward reasoning version, we should introduce a convenient
variation on `rw`. The `rwa` tactic performs rewrite and then looks for an
assumption matching the goal. We can use it to rewrite our latest proof as:
-/
example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c :=
begin
have hab' : 0 ≤ b - a,
{ rwa ← sub_nonneg at hab, },
have h₁ : 0 ≤ (b - a)*c,
{ exact mul_nonneg' hab' hc },
have h₂ : (b - a)*c = b*c - a*c,
{ ring, },
have h₃ : 0 ≤ b*c - a*c,
{ rwa h₂ at h₁, },
rwa sub_nonneg at h₃,
end
/-
Let's now combine forward and backward reasonning, to get our most
efficient proof of this statement. Note in particular how unification is used
to know what to prove inside the parentheses in the `mul_nonneg'` arguments.
-/
example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c :=
begin
rw ← sub_nonneg,
calc
0 ≤ (b - a)*c : mul_nonneg' (by rwa sub_nonneg) hc
... = b*c - a*c : by ring,
end
/-
Let's now practice all three styles using:
mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b
sub_nonpos {a b : α} : a - b ≤ 0 ↔ a ≤ b
-/
/- First using mostly backward reasonning -/
-- 0013
example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c :=
begin
rw ←sub_nonneg,
rw (show a * c - b * c = (a - b) * c, by ring),
apply mul_nonneg_of_nonpos_of_nonpos _ hc,
rwa sub_nonpos,
end
/- Using forward reasonning -/
-- 0014
example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c :=
begin
have : a - b ≤ 0, by rwa sub_nonpos,
have : 0 ≤ (a - b) * c, from mul_nonneg_of_nonpos_of_nonpos this hc,
have : a * c - b * c = (a - b) * c, by ring,
have : 0 ≤ a * c - b * c, by rwa this,
show b * c ≤ a * c, by rwa ←sub_nonneg,
end
/-- Using a combination of both, with a `calc` block -/
-- 0015
example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c :=
begin
rw ←sub_nonneg,
calc
0 ≤ (a - b) * c : mul_nonneg_of_nonpos_of_nonpos (by rwa sub_nonpos) hc
... = a * c - b * c : by ring,
end
/-
Let's now move to proving implications. Lean denotes implications using
a simple arrow →, the same it uses for functions (say denoting the type of functions
from ℕ to ℕ by ℕ → ℕ). This is because it sees a proof of P ⇒ Q as a function turning
a proof of P into a proof Q.
Many of the examples that we already met are implications under the hood. For instance we proved
le_add_of_nonneg_left (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b
But this can be rephrased as
le_add_of_nonneg_left (a b : ℝ) : 0 ≤ a → b ≤ a + b
In order to prove P → Q, we use the tactic `intros`, followed by an assumption name.
This creates an assumption with that name asserting that P holds, and turns the goal into Q.
Let's check we can go from our old version of l`e_add_of_nonneg_left` to the new one.
-/
example (a b : ℝ): 0 ≤ a → b ≤ a + b :=
begin
intros ha,
exact le_add_of_nonneg_left ha,
end
/-
Actually Lean doesn't make any difference between those two versions. It is also happy with
-/
example (a b : ℝ): 0 ≤ a → b ≤ a + b :=
le_add_of_nonneg_left
/- No tactic state is shown in the above line because we don't even need to enter
tactic mode using `begin` or `by`.
Let's practise using `intros`. -/
-- 0016
example (a b : ℝ): 0 ≤ b → a ≤ a + b :=
begin
intros hb,
exact le_add_of_nonneg_right hb,
end
/-
What about lemmas having more than one assumption? For instance:
add_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b
A natural idea is to use the conjunction operator (logical AND), which Lean denotes
by ∧. Assumptions built using this operator can be decomposed using the `cases` tactic,
which is a very general assumption-decomposing tactic.
-/
example {a b : ℝ} : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b :=
begin
intros hyp,
cases hyp with ha hb,
exact add_nonneg ha hb,
end
/-
Needing that intermediate line invoking `cases` shows this formulation is not what is used by
Lean. It rather sees `add_nonneg` as two nested implications:
if a is non-negative then if b is non-negative then a+b is non-negative.
It reads funny, but it is much more convenient to use in practice.
-/
example {a b : ℝ} : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) :=
add_nonneg
/-
The above pattern is so common that implications are defined as right-associative operators,
hence parentheses are not needed above.
Let's prove that the naive conjunction version implies the funny Lean version. For this we need
to know how to prove a conjunction. The `split` tactic creates two goals from a conjunction goal.
It can also be used to create two implication goals from an equivalence goal.
-/
example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) :=
begin
intros ha,
intros hb,
apply H,
split,
exact ha,
exact hb,
end
/-
Let's practice `cases` and `split`. In the next exercise, P, Q and R denote
unspecified mathematical statements.
-/
-- 0017
example (P Q R : Prop) : P ∧ Q → Q ∧ P :=
begin
rintros ⟨p, q⟩,
split; assumption,
end
/-
Of course using `split` only to be able to use `exact` twice in a row feels silly. One can
also use the anonymous constructor syntax: ⟨ ⟩
Beware those are not parentheses but angle brackets. This is a generic way of providing
compound objects to Lean when Lean already has a very clear idea of what it is waiting for.
So we could have replaced the last three lines by:
exact ⟨hQ, hP⟩
We can also combine the `intros` steps. We can now compress our earlier proof to:
-/
example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) :=
begin
intros ha hb,
exact H ⟨ha, hb⟩,
end
/-
The anonymous contructor trick actually also works in `intros` provided we use
its recursive version `rintros`. So we can replace
intro h,
cases h with h₁ h₂
by
rintros ⟨h₁, h₂⟩,
Now redo the previous exercise using all those compressing techniques, in exactly two lines. -/
-- 0018
example (P Q R : Prop): P ∧ Q → Q ∧ P :=
by { rintros ⟨p, q⟩, exact ⟨q, p⟩ }
/-
We are ready to come back to the equivalence between the different formulations of
lemmas having two assumptions. Remember the `split` tactic can be used to split
an equivalence into two implications.
-/
-- 0019
example (P Q R : Prop) : (P ∧ Q → R) ↔ (P → (Q → R)) :=
begin
split,
{ intros h p q, exact h ⟨p, q⟩ },
{ rintros h ⟨p, q⟩, exact h p q },
end
/-
If you used more than five lines in the above exercise then try to compress things
(without simply removing line ends).
One last compression technique: given a proof h of a conjunction P ∧ Q, one can get
a proof of P using h.left and a proof of Q using h.right, without using cases.
One can also use the more generic (but less legible) names h.1 and h.2.
Similarly, given a proof h of P ↔ Q, one can get a proof of P → Q using h.mp
and a proof of Q → P using h.mpr (or the generic h.1 and h.2 that are even less legible
in this case).
Before the final exercise in this file, let's make sure we'll be able to leave
without learning 10 lemma names. The `linarith` tactic will prove any equality or
inequality or contradiction that follows by linear combinations of assumptions from the
context (with constant coefficients).
-/
example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b :=
begin
linarith,
end
/-
Now let's enjoy this for a while.
-/
-- 0020
example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b :=
begin
linarith
end
/- And let's combine with our earlier lemmas. -/
-- 0021
example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := add_le_add hab hcd
/-
Final exercise
In the last exercise of this file, we will use the divisibility relation on ℕ,
denoted by ∣ (beware this is a unicode divisibility bar, not the ASCII pipe character),
and the gcd function.
The definitions are the usual ones, but our goal is to avoid using these definitions and
only use the following three lemmas:
dvd_refl (a : ℕ) : a ∣ a
dvd_antisym {a b : ℕ} : a ∣ b → b ∣ a → a = b :=
dvd_gcd_iff {a b c : ℕ} : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b
-/
-- All functions and lemmas below are about natural numbers.
open nat
-- 0022
example (a b : ℕ) : a ∣ b ↔ gcd a b = a :=
begin
have : gcd a b ∣ a ∧ gcd a b ∣ b, by rw ←dvd_gcd_iff,
split; intro h,
{ apply dvd_antisymm,
show gcd a b ∣ a, from this.left,
show a ∣ gcd a b, from dvd_gcd_iff.mpr ⟨by refl, h⟩, },
{ rw ←h, exact this.right },
end |
2aa5df1eb6dd4234055cad6fef25fe6705bfded5 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/algebra_tower.lean | 6208b5f109de1b9923876d3e4d983e3f16d05ecf | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,853 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.restrict_scalars
import algebra.algebra.tower
import algebra.invertible
import linear_algebra.basis
import ring_theory.adjoin.fg
import ring_theory.polynomial.tower
/-!
# Towers of algebras
We set up the basic theory of algebra towers.
An algebra tower A/S/R is expressed by having instances of `algebra A S`,
`algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the
compatibility condition `(r • s) • a = r • (s • a)`.
In `field_theory/tower.lean` we use this to prove the tower law for finite extensions,
that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`.
In this file we prepare the main lemma:
if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis
of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the
base rings to be a field, so we also generalize the lemma to rings in this file.
-/
open_locale pointwise
universes u v w u₁
variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁)
namespace is_scalar_tower
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B]
variables [is_scalar_tower R S A] [is_scalar_tower R S B]
variables (R S A B)
/-- Suppose that `R -> S -> A` is a tower of algebras.
If an element `r : R` is invertible in `S`, then it is invertible in `A`. -/
def invertible.algebra_tower (r : R) [invertible (algebra_map R S r)] :
invertible (algebra_map R A r) :=
invertible.copy (invertible.map (algebra_map S A : S →* A) (algebra_map R S r)) (algebra_map R A r)
(by rw [ring_hom.coe_monoid_hom, is_scalar_tower.algebra_map_apply R S A])
/-- A natural number that is invertible when coerced to `R` is also invertible
when coerced to any `R`-algebra. -/
def invertible_algebra_coe_nat (n : ℕ) [inv : invertible (n : R)] :
invertible (n : A) :=
by { haveI : invertible (algebra_map ℕ R n) := inv, exact invertible.algebra_tower ℕ R A n }
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
end comm_semiring
end is_scalar_tower
namespace algebra
theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) :
adjoin R (algebra_map S (restrict_scalars R S A) '' s) = (adjoin R s).map
((algebra.of_id S (restrict_scalars R S A)).restrict_scalars R) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A]
[is_scalar_tower R S A] (s : set S) :
adjoin R (algebra_map S A '' s) =
subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
lemma adjoin_restrict_scalars (C D E : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E]
[algebra C D] [algebra C E] [algebra D E] [is_scalar_tower C D E] (S : set E) :
(algebra.adjoin D S).restrict_scalars C =
((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)).under
(algebra.adjoin ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) S) :=
begin
suffices : set.range (algebra_map D E) =
set.range (algebra_map ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) E),
{ ext x, change x ∈ subsemiring.closure (_ ∪ S) ↔ x ∈ subsemiring.closure (_ ∪ S), rw this },
ext x,
split,
{ rintros ⟨y, hy⟩,
exact ⟨⟨algebra_map D E y, ⟨y, ⟨algebra.mem_top, rfl⟩⟩⟩, hy⟩ },
{ rintros ⟨⟨y, ⟨z, ⟨h0, h1⟩⟩⟩, h2⟩,
exact ⟨z, eq.trans h1 h2⟩ },
end
lemma adjoin_res_eq_adjoin_res (C D E F : Type*) [comm_semiring C] [comm_semiring D]
[comm_semiring E] [comm_semiring F] [algebra C D] [algebra C E] [algebra C F] [algebra D F]
[algebra E F] [is_scalar_tower C D F] [is_scalar_tower C E F] {S : set D} {T : set E}
(hS : algebra.adjoin C S = ⊤) (hT : algebra.adjoin C T = ⊤) :
(algebra.adjoin E (algebra_map D F '' S)).restrict_scalars C =
(algebra.adjoin D (algebra_map E F '' T)).restrict_scalars C :=
by rw [adjoin_restrict_scalars, adjoin_restrict_scalars, ←hS, ←hT, ←algebra.adjoin_image,
←algebra.adjoin_image, ←alg_hom.coe_to_ring_hom, ←alg_hom.coe_to_ring_hom,
is_scalar_tower.coe_to_alg_hom, is_scalar_tower.coe_to_alg_hom, ←adjoin_union_eq_under,
←adjoin_union_eq_under, set.union_comm]
end algebra
section
open_locale classical
lemma algebra.fg_trans' {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A]
[algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A]
(hRS : (⊤ : subalgebra R S).fg) (hSA : (⊤ : subalgebra S A).fg) :
(⊤ : subalgebra R A).fg :=
let ⟨s, hs⟩ := hRS, ⟨t, ht⟩ := hSA in ⟨s.image (algebra_map S A) ∪ t,
by rw [finset.coe_union, finset.coe_image, algebra.adjoin_union_eq_under,
algebra.adjoin_algebra_map, hs, algebra.map_top, is_scalar_tower.range_under_adjoin, ht,
subalgebra.restrict_scalars_top]⟩
end
section algebra_map_coeffs
variables {R} (A) {ι M : Type*} [comm_semiring R] [semiring A] [add_comm_monoid M]
variables [algebra R A] [module A M] [module R M] [is_scalar_tower R A M]
variables (b : basis ι R M) (h : function.bijective (algebra_map R A))
/-- If `R` and `A` have a bijective `algebra_map R A` and act identically on `M`,
then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. -/
@[simps]
noncomputable def basis.algebra_map_coeffs : basis ι A M :=
b.map_coeffs (ring_equiv.of_bijective _ h) (λ c x, by simp)
lemma basis.algebra_map_coeffs_apply (i : ι) : b.algebra_map_coeffs A h i = b i :=
b.map_coeffs_apply _ _ _
@[simp] lemma basis.coe_algebra_map_coeffs : (b.algebra_map_coeffs A h : ι → M) = b :=
b.coe_map_coeffs _ _
end algebra_map_coeffs
section ring
open finsupp
open_locale big_operators classical
universes v₁ w₁
variables {R S A}
variables [comm_ring R] [ring S] [add_comm_group A]
variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A]
theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A}
(hb : linear_independent R b) (hc : linear_independent S c) :
linear_independent R (λ p : ι × ι', b p.1 • c p.2) :=
begin
rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩,
by_cases hik : (i, k) ∈ s,
{ have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0,
{ rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp,
show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm },
rw [finset.sum_product, finset.sum_comm] at h1,
simp_rw [← smul_assoc, ← finset.sum_smul] at h1,
exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) },
exact hg _ hik
end
/-- `basis.smul (b : basis ι R S) (c : basis ι S A)` is the `R`-basis on `A`
where the `(i, j)`th basis vector is `b i • c j`. -/
noncomputable def basis.smul {ι : Type v₁} {ι' : Type w₁}
(b : basis ι R S) (c : basis ι' S A) : basis (ι × ι') R A :=
basis.of_repr ((c.repr.restrict_scalars R) ≪≫ₗ
((finsupp.lcongr (equiv.refl _) b.repr) ≪≫ₗ
((finsupp_prod_lequiv R).symm ≪≫ₗ
((finsupp.lcongr (equiv.prod_comm ι' ι) (linear_equiv.refl _ _))))))
@[simp] theorem basis.smul_repr {ι : Type v₁} {ι' : Type w₁}
(b : basis ι R S) (c : basis ι' S A) (x ij):
(b.smul c).repr x ij = b.repr (c.repr x ij.2) ij.1 :=
by simp [basis.smul]
theorem basis.smul_repr_mk {ι : Type v₁} {ι' : Type w₁}
(b : basis ι R S) (c : basis ι' S A) (x i j):
(b.smul c).repr x (i, j) = b.repr (c.repr x j) i :=
b.smul_repr c x (i, j)
@[simp] theorem basis.smul_apply {ι : Type v₁} {ι' : Type w₁}
(b : basis ι R S) (c : basis ι' S A) (ij) :
(b.smul c) ij = b ij.1 • c ij.2 :=
begin
obtain ⟨i, j⟩ := ij,
rw basis.apply_eq_iff,
ext ⟨i', j'⟩,
rw [basis.smul_repr, linear_equiv.map_smul, basis.repr_self, finsupp.smul_apply,
finsupp.single_apply],
dsimp only,
split_ifs with hi,
{ simp [hi, finsupp.single_apply] },
{ simp [hi] },
end
lemma basis.algebra_map_injective {ι : Type v₁} [no_zero_divisors R] [nontrivial S]
(b : basis ι R S) :
function.injective (algebra_map R S) :=
have no_zero_smul_divisors R S := b.no_zero_smul_divisors,
by exactI no_zero_smul_divisors.algebra_map_injective R S
end ring
section artin_tate
variables (C : Type*)
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C]
open finset submodule
open_locale classical
lemma exists_subalgebra_of_fg (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) :
∃ B₀ : subalgebra A B, B₀.fg ∧ (⊤ : submodule B₀ C).fg :=
begin
cases hAC with x hx,
cases hBC with y hy, have := hy,
simp_rw [eq_top_iff', mem_span_finset] at this, choose f hf,
let s : finset B := (finset.product (x ∪ (y * y)) y).image (function.uncurry f),
have hsx : ∀ (xi ∈ x) (yj ∈ y), f xi yj ∈ s := λ xi hxi yj hyj,
show function.uncurry f (xi, yj) ∈ s,
from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_left _ hxi, hyj⟩,
have hsy : ∀ (yi yj yk ∈ y), f (yi * yj) yk ∈ s := λ yi yj yk hyi hyj hyk,
show function.uncurry f (yi * yj, yk) ∈ s,
from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_right _ $ finset.mul_mem_mul hyi hyj, hyk⟩,
have hxy : ∀ xi ∈ x, xi ∈ span (algebra.adjoin A (↑s : set B))
(↑(insert 1 y : finset C) : set C) :=
λ xi hxi, hf xi ▸ sum_mem _ (λ yj hyj, smul_mem
(span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C))
⟨f xi yj, algebra.subset_adjoin $ hsx xi hxi yj hyj⟩
(subset_span $ mem_insert_of_mem hyj)),
have hyy : span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) *
span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) ≤
span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C),
{ rw [span_mul_span, span_le, coe_insert], rintros _ ⟨yi, yj, rfl | hyi, rfl | hyj, rfl⟩,
{ rw mul_one, exact subset_span (set.mem_insert _ _) },
{ rw one_mul, exact subset_span (set.mem_insert_of_mem _ hyj) },
{ rw mul_one, exact subset_span (set.mem_insert_of_mem _ hyi) },
{ rw ← hf (yi * yj), exact set_like.mem_coe.2 (sum_mem _ $ λ yk hyk, smul_mem
(span (algebra.adjoin A (↑s : set B)) (insert 1 ↑y : set C))
⟨f (yi * yj) yk, algebra.subset_adjoin $ hsy yi yj yk hyi hyj hyk⟩
(subset_span $ set.mem_insert_of_mem _ hyk : yk ∈ _)) } },
refine ⟨algebra.adjoin A (↑s : set B), subalgebra.fg_adjoin_finset _, insert 1 y, _⟩,
refine restrict_scalars_injective A _ _ _,
rw [restrict_scalars_top, eq_top_iff, ← algebra.top_to_submodule, ← hx,
algebra.adjoin_eq_span, span_le],
refine λ r hr, submonoid.closure_induction hr (λ c hc, hxy c hc)
(subset_span $ mem_insert_self _ _) (λ p q hp hq, hyy $ submodule.mul_mem_mul hp hq)
end
/-- Artin--Tate lemma: if A ⊆ B ⊆ C is a chain of subrings of commutative rings, and
A is noetherian, and C is algebra-finite over A, and C is module-finite over B,
then B is algebra-finite over A.
References: Atiyah--Macdonald Proposition 7.8; Stacks 00IS; Altman--Kleiman 16.17. -/
theorem fg_of_fg_of_fg [is_noetherian_ring A]
(hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg)
(hBCi : function.injective (algebra_map B C)) :
(⊤ : subalgebra A B).fg :=
let ⟨B₀, hAB₀, hB₀C⟩ := exists_subalgebra_of_fg A B C hAC hBC in
algebra.fg_trans' (B₀.fg_top.2 hAB₀) $ subalgebra.fg_of_submodule_fg $
have is_noetherian_ring B₀, from is_noetherian_ring_of_fg hAB₀,
have is_noetherian B₀ C, by exactI is_noetherian_of_fg_of_noetherian' hB₀C,
by exactI fg_of_injective (is_scalar_tower.to_alg_hom B₀ B C).to_linear_map
(linear_map.ker_eq_bot.2 hBCi)
end artin_tate
section alg_hom_tower
variables {A} {C D : Type*} [comm_semiring A] [comm_semiring C] [comm_semiring D]
[algebra A C] [algebra A D]
variables (f : C →ₐ[A] D) (B) [comm_semiring B] [algebra A B] [algebra B C] [is_scalar_tower A B C]
/-- Restrict the domain of an `alg_hom`. -/
def alg_hom.restrict_domain : B →ₐ[A] D := f.comp (is_scalar_tower.to_alg_hom A B C)
/-- Extend the scalars of an `alg_hom`. -/
def alg_hom.extend_scalars : @alg_hom B C D _ _ _ _ (f.restrict_domain B).to_ring_hom.to_algebra :=
{ commutes' := λ _, rfl .. f }
variables {B}
/-- `alg_hom`s from the top of a tower are equivalent to a pair of `alg_hom`s. -/
def alg_hom_equiv_sigma :
(C →ₐ[A] D) ≃ Σ (f : B →ₐ[A] D), @alg_hom B C D _ _ _ _ f.to_ring_hom.to_algebra :=
{ to_fun := λ f, ⟨f.restrict_domain B, f.extend_scalars B⟩,
inv_fun := λ fg,
let alg := fg.1.to_ring_hom.to_algebra in by exactI fg.2.restrict_scalars A,
left_inv := λ f, by { dsimp only, ext, refl },
right_inv :=
begin
rintros ⟨⟨f, _, _, _, _, _⟩, g, _, _, _, _, hg⟩,
have : f = λ x, g (algebra_map B C x) := by { ext, exact (hg x).symm },
subst this,
refl,
end }
end alg_hom_tower
|
2fab64563d5b57b8dfa35199e4cbd35418f4703c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/complete_lattice.lean | c9d2ebf88ea965039b93147535d9316583663bef | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 54,371 | 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 order.bounds
import data.set.bool
import data.nat.basic
/-!
# Theory of complete lattices
## Main definitions
* `Sup` and `Inf` are the supremum and the infimum of a set;
* `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function,
defined as `Sup` and `Inf` of the range of this function;
* `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary
of `s` and `Inf s` is always the greatest lower boundary of `s`;
* `class complete_linear_order`: a linear ordered complete lattice.
## Naming conventions
We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we
also use `bsupr`/`binfi` for "bounded" supremum or infimum, i.e. one of `⨆ i ∈ s, f i`,
`⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`.
## Notation
* `⨆ i, f i` : `supr f`, the supremum of the range of `f`;
* `⨅ i, f i` : `infi f`, the infimum of the range of `f`.
-/
set_option old_structure_cmd true
open set
variables {α β β₂ : Type*} {ι ι₂ : Sort*}
/-- class for the `Sup` operator -/
class has_Sup (α : Type*) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type*) := (Inf : set α → α)
export has_Sup (Sup) has_Inf (Inf)
/-- Supremum of a set -/
add_decl_doc has_Sup.Sup
/-- Infimum of a set -/
add_decl_doc has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s)
@[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩
@[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
/--
Note that we rarely use `complete_semilattice_Sup`
(in fact, any such object is always a `complete_lattice`, so it's usually best to start there).
Nevertheless it is sometimes a useful intermediate step in constructions.
-/
class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
section
variables [complete_semilattice_Sup α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a
lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩
lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
(is_lub_Sup s).mono (is_lub_Sup t) h
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_Sup s)
lemma le_Sup_iff :
a ≤ Sup s ↔ (∀ b, (∀ x ∈ s, x ≤ b) → a ≤ b) :=
⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩
theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t :=
le_of_forall_le' begin
simp only [Sup_le_iff],
introv h₀ h₁,
rcases h _ h₁ with ⟨y,hy,hy'⟩,
solve_by_elim [le_trans hy']
end
-- We will generalize this to conditionally complete lattices in `cSup_singleton`.
theorem Sup_singleton {a : α} : Sup {a} = a :=
is_lub_singleton.Sup_eq
end
/--
Note that we rarely use `complete_semilattice_Inf`
(in fact, any such object is always a `complete_lattice`, so it's usually best to start there).
Nevertheless it is sometimes a useful intermediate step in constructions.
-/
class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α :=
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
section
variables [complete_semilattice_Inf α] {s t : set α} {a b : α}
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a
lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩
lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
(is_glb_Inf s).mono (is_glb_Inf t) h
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_Inf s)
lemma Inf_le_iff :
Inf s ≤ a ↔ (∀ b, (∀ x ∈ s, b ≤ x) → b ≤ a) :=
⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩
theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s :=
le_of_forall_le begin
simp only [le_Inf_iff],
introv h₀ h₁,
rcases h _ h₁ with ⟨y,hy,hy'⟩,
solve_by_elim [le_trans _ hy']
end
-- We will generalize this to conditionally complete lattices in `cInf_singleton`.
theorem Inf_singleton {a : α} : Inf {a} = a :=
is_glb_singleton.Inf_eq
end
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
@[protect_proj]
class complete_lattice (α : Type*) extends
bounded_lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α.
/-- Create a `complete_lattice` from a `partial_order` and `Inf` function
that returns the greatest lower bound of a set. Usually this constructor provides
poor definitional equalities. If other fields are known explicitly, they should be
provided; for example, if `inf` is known explicitly, construct the `complete_lattice`
instance as
```
instance : complete_lattice my_T :=
{ inf := better_inf,
le_inf := ...,
inf_le_right := ...,
inf_le_left := ...
-- don't care to fix sup, Sup, bot, top
..complete_lattice_of_Inf my_T _ }
```
-/
def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α]
[H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) :
complete_lattice α :=
{ bot := Inf univ,
bot_le := λ x, (is_glb_Inf univ).1 trivial,
top := Inf ∅,
le_top := λ a, (is_glb_Inf ∅).2 $ by simp,
sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
inf := λ a b, Inf {a, b},
le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] },
inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _,
sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*],
le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left,
le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right,
le_Inf := λ s a ha, (is_glb_Inf s).2 ha,
Inf_le := λ s a ha, (is_glb_Inf s).1 ha,
Sup := λ s, Inf (upper_bounds s),
le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha,
Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha,
.. H1, .. H2 }
/--
Any `complete_semilattice_Inf` is in fact a `complete_lattice`.
Note that this construction has bad definitional properties:
see the doc-string on `complete_lattice_of_Inf`.
-/
def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] :
complete_lattice α :=
complete_lattice_of_Inf α (λ s, is_glb_Inf s)
/-- Create a `complete_lattice` from a `partial_order` and `Sup` function
that returns the least upper bound of a set. Usually this constructor provides
poor definitional equalities. If other fields are known explicitly, they should be
provided; for example, if `inf` is known explicitly, construct the `complete_lattice`
instance as
```
instance : complete_lattice my_T :=
{ inf := better_inf,
le_inf := ...,
inf_le_right := ...,
inf_le_left := ...
-- don't care to fix sup, Inf, bot, top
..complete_lattice_of_Sup my_T _ }
```
-/
def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α]
[H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) :
complete_lattice α :=
{ top := Sup univ,
le_top := λ x, (is_lub_Sup univ).1 trivial,
bot := Sup ∅,
bot_le := λ x, (is_lub_Sup ∅).2 $ by simp,
sup := λ a b, Sup {a, b},
sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]),
le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _,
le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b},
le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*],
inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left),
inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right),
Inf := λ s, Sup (lower_bounds s),
Sup_le := λ s a ha, (is_lub_Sup s).2 ha,
le_Sup := λ s a ha, (is_lub_Sup s).1 ha,
Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha),
le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha,
.. H1, .. H2 }
/--
Any `complete_semilattice_Sup` is in fact a `complete_lattice`.
Note that this construction has bad definitional properties:
see the doc-string on `complete_lattice_of_Sup`.
-/
def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] :
complete_lattice α :=
complete_lattice_of_Sup α (λ s, is_lub_Sup s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α
namespace order_dual
variable (α)
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α }
instance [complete_linear_order α] : complete_linear_order (order_dual α) :=
{ .. order_dual.complete_lattice α, .. order_dual.linear_order α }
end order_dual
section
variables [complete_lattice α] {s t : set α} {a b : α}
theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
@Sup_inter_le (order_dual α) _ _ _
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
(@is_lub_empty α _ _).Sup_eq
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
(@is_glb_empty α _ _).Inf_eq
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
(@is_lub_univ α _ _).Sup_eq
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
(@is_glb_univ α _ _).Inf_eq
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_Sup s).insert a).Sup_eq
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_Inf s).insert a).Inf_eq
theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t :=
le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq))
theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s :=
le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h)
theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b :=
(@is_lub_pair α _ a b).Sup_eq
theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b :=
(@is_glb_pair α _ a b).Inf_eq
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α}
(h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} :=
by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, }
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
@Inf_eq_top (order_dual α) _ _
lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α}
(h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} :=
by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, }
/--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b`
is larger than all elements of `s`, and that this is not the case of any `w<b`.
See `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete
lattices. -/
theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (_ : ∀a∈s, a ≤ b)
(H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b :=
have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (Sup_le ‹∀a∈s, a ≤ b›),
have ¬(Sup s < b) :=
assume: Sup s < b,
let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/
have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_Sup ‹a ∈ s›),
show false, by finish [lt_irrefl (Sup s)],
show Sup s = b, by finish
/--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b`
is smaller than all elements of `s`, and that this is not the case of any `w>b`.
See `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete
lattices. -/
theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : ∀a∈s, b ≤ a)
(H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b :=
@Sup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ ‹_› ‹_› ‹_›
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
is_glb_lt_iff (is_glb_Inf s)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
lt_is_lub_iff (is_lub_Sup s)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
@Sup_eq_top (order_dual α) _ _
lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
lt_Sup_iff.trans exists_range_iff
lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
Inf_lt_iff.trans exists_range_iff
end complete_linear_order
/-
### supr & infi
-/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _
lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq
lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _
lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) :
f i hi ≤ ⨆ i hi, f i hi :=
le_supr_of_le i $ le_supr (f i) hi
theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) :
a ≤ ⨆ i hi, f i hi :=
le_trans h (le_bsupr i hi)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) :
(⨆ i (hi : p i), f i hi) ≤ a :=
supr_le $ λ i, supr_le $ h i
theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i :=
bsupr_le (λ i hi, le_supr f i)
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi :=
bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi)
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
theorem bsupr_le_bsupr' {p q : ι → Prop} (hpq : ∀ i, p i → q i) {f : ι → α} :
(⨆ i (hpi : p i), f i) ≤ ⨆ i (hqi : q i), f i :=
supr_le_supr $ λ i, supr_le_supr_const (hpq i)
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
(is_lub_le_iff is_lub_supr).trans forall_range_iff
theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b :=
⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_eq_supr' {α} [has_Sup α] (s : set α) : Sup s = ⨆ x : s, (x : α) :=
by rw [supr, subtype.range_coe]
lemma Sup_sUnion {s : set (set α)} :
Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t :=
begin
apply le_antisymm,
{ apply Sup_le (λ b hb, _),
rcases hb with ⟨t, ts, bt⟩,
apply le_trans _ (le_supr _ t),
exact le_trans (le_Sup bt) (le_supr _ ts), },
{ apply supr_le (λ t, _),
exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) }
end
lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) :=
⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩
lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) :
(⨆ i, f (s i)) ≤ f (supr s) :=
supr_le $ λ i, hf $ le_supr _ _
lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
(⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) :=
calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) :
supr_le_supr $ λ i, hf.le_map_supr
... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr
lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
(⨆a∈s, f a) ≤ f (Sup s) :=
by rw [Sup_eq_supr]; exact hf.le_map_supr2 _
lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨆ x, f (g x)) ≤ ⨆ y, f y :=
supr_le_supr2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) :
(⨆ x, f (s x)) = ⨆ y, f y :=
le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi)
lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨆ x, g (f x)) = ⨆ y, g y :=
by simp only [supr, hf.range_comp]
lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂)
(h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y :=
by { convert h1.supr_comp g, exact (funext h2).symm }
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
have := propext pq, subst this,
congr' with x,
apply f
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) :
(⨅ i hi, f i hi) ≤ f i hi :=
infi_le_of_le i $ infi_le (f i) hi
theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) :
(⨅ i hi, f i hi) ≤ a :=
le_trans (binfi_le i hi) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) :
a ≤ ⨅ i hi, f i hi :=
le_infi $ λ i, le_infi $ h i
theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i :=
le_binfi (λ i hi, infi_le f i)
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi :=
le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi)
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
@Sup_eq_supr (order_dual α) _ _
theorem Inf_eq_infi' {α} [has_Inf α] (s : set α) : Inf s = ⨅ a : s, a :=
@Sup_eq_supr' (order_dual α) _ _
lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) :
f (infi s) ≤ (⨅ i, f (s i)) :=
le_infi $ λ i, hf $ infi_le _ _
lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) :=
@monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.dual _ _
lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
f (Inf s) ≤ ⨅ a∈s, f a :=
by rw [Inf_eq_infi]; exact hf.map_infi2_le _
lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨅ y, f y) ≤ ⨅ x, f (g x) :=
infi_le_infi2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) :
(⨅ x, f (s x)) = ⨅ y, f y :=
le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _)
lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨅ x, g (f x)) = ⨅ y, g y :=
@function.surjective.supr_comp _ _ (order_dual α) _ f hf g
lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂)
(h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y :=
@supr_congr _ _ (order_dual α) _ _ _ h h1 h2
@[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
@supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f
lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x :=
supr_le (λ _, le_rfl)
lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) :=
le_infi (λ _, le_rfl)
-- We will generalize this to conditionally complete lattices in `cinfi_const`.
theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, Inf_singleton]
-- We will generalize this to conditionally complete lattices in `csupr_const`.
theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
@infi_const (order_dual α) _ _ _ _
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
@infi_top (order_dual α) _ _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
Inf_eq_top.trans forall_range_iff
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
Sup_eq_bot.trans forall_range_iff
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
/--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b`
is larger than `f i` for all `i`, and that this is not the case of any `w<b`.
See `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete
lattices. -/
theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b)
(h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b :=
Sup_eq_of_forall_le_of_forall_lt_exists_gt (forall_range_iff.mpr h₁)
(λ w hw, exists_range_iff.mpr $ h₂ w hw)
/--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b`
is smaller than `f i` for all `i`, and that this is not the case of any `w>b`.
See `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete
lattices. -/
theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt {f : ι → α} (h₁ : ∀ i, b ≤ f i)
(h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b :=
@supr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ _ ‹_› ‹_› ‹_›
lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨆h:p, a h) = (if h : p then a h else ⊥) :=
by by_cases p; simp [h]
lemma supr_eq_if {p : Prop} [decidable p] (a : α) :
(⨆h:p, a) = (if p then a else ⊥) :=
supr_eq_dif (λ _, a)
lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨅h:p, a h) = (if h : p then a h else ⊤) :=
@supr_eq_dif (order_dual α) _ _ _ _
lemma infi_eq_if {p : Prop} [decidable p] (a : α) :
(⨅h:p, a) = (if p then a else ⊤) :=
infi_eq_dif (λ _, a)
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
@infi_comm (order_dual α) _ _ _ _
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} :
(⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} :
(⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} :
(⨆x, ⨆h : x = b, f x h) = f b rfl :=
@infi_infi_eq_left (order_dual α) _ _ _ _
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} :
(⨆x, ⨆h : b = x, f x h) = f b rfl :=
@infi_infi_eq_right (order_dual α) _ _ _ _
attribute [ematch] le_refl
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) :=
(@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) :
(⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t :=
infi_subtype
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_of_left_le $ infi_le _ _)
(inf_le_of_right_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
by rw [infi_inf_eq, infi_const]
lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf]; simp [inf_comm]
lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩);
rw [infi_subtype', infi_subtype', infi_inf]
lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) :
a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) :=
by simpa only [inf_comm] using binfi_inf h
theorem supr_sup_eq {f g : ι → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
@infi_inf_eq (order_dual α) ι _ _ _
lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) :=
@infi_inf (order_dual α) _ _ _ _ _
lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) :=
@inf_infi (order_dual α) _ _ _ _ _
/-! ### `supr` and `infi` under `Prop` -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
theorem infi_true {s : true → α} : infi s = s trivial :=
infi_pos trivial
theorem supr_true {s : true → α} : supr s = s trivial :=
supr_pos trivial
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} :
(⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} :
(⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
@infi_exists (order_dual α) _ _ _ _
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
/-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/
lemma infi_and' {p q : Prop} {s : p → q → α} :
(⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact infi_and }
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
@infi_and (order_dual α) _ _ _ _
/-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/
lemma supr_and' {p q : Prop} {s : p → q → α} :
(⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact supr_and }
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_of_left_le $ infi_le _ _
| or.inr j := inf_le_of_right_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
@infi_or (order_dual α) _ _ _ _
section
variables (p : ι → Prop) [decidable_pred p]
lemma supr_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) :
(⨆ i, if h : p i then f i h else g i h) = (⨆ i (h : p i), f i h) ⊔ (⨆ i (h : ¬ p i), g i h) :=
begin
rw ←supr_sup_eq,
congr' 1 with i,
split_ifs with h;
simp [h],
end
lemma supr_ite (f g : ι → α) :
(⨆ i, if p i then f i else g i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), g i) :=
supr_dite _ _ _
lemma infi_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) :
(⨅ i, if h : p i then f i h else g i h) = (⨅ i (h : p i), f i h) ⊓ (⨅ i (h : ¬ p i), g i h) :=
supr_dite p (show Π i, p i → order_dual α, from f) g
lemma infi_ite (f g : ι → α) :
(⨅ i, if p i then f i else g i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), g i) :=
infi_dite _ _ _
end
lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range' {α} [has_Sup α] (g : β → α) (f : ι → β) :
(⨆ b : range f, g b) = ⨆ i, g (f i) :=
by rw [supr, supr, ← image_eq_range, ← range_comp]
lemma infi_range' {α} [has_Inf α] (g : β → α) (f : ι → β) :
(⨅ b : range f, g b) = ⨅ i, g (f i) :=
@supr_range' _ _ (order_dual α) _ _ _
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
by rw [← infi_subtype'', infi_range']
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
@infi_range (order_dual α) _ _ _ _ _
theorem Inf_image' {α} [has_Inf α] {s : set β} {f : β → α} :
Inf (f '' s) = (⨅ a : s, f a) :=
by rw [infi, image_eq_range]
theorem Sup_image' {α} [has_Sup α] {s : set β} {f : β → α} :
Sup (f '' s) = (⨆ a : s, f a) :=
@Inf_image' _ (order_dual α) _ _ _
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
by rw [← infi_subtype'', Inf_image']
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
@Inf_image (order_dual α) _ _ _ _
/-
### supr and infi under set constructions
-/
theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
by simp
theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
by simp
theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
by simp
theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
by simp
theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
by simp only [← infi_inf_eq, infi_or]
lemma infi_split (f : β → α) (p : β → Prop) :
(⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) :=
by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i}
lemma infi_split_single (f : β → α) (i₀ : β) :
(⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) :=
by convert infi_split _ _; simp
theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left
theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
@infi_union (order_dual α) _ _ _ _ _
lemma supr_split (f : β → α) (p : β → Prop) :
(⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) :=
@infi_split (order_dual α) _ _ _ _
lemma supr_split_single (f : β → α) (i₀ : β) :
(⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) :=
@infi_split_single (order_dual α) _ _ _ _
theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) :=
@infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h
theorem infi_insert {f : β → α} {s : set β} {b : β} :
(⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
theorem supr_insert {f : β → α} {s : set β} {b : β} :
(⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b :=
by rw [infi_insert, infi_singleton]
theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
@infi_singleton (order_dual α) _ _ _ _
theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b :=
by rw [supr_insert, supr_singleton]
lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) :=
by rw [← Inf_image, ← Inf_image, ← image_comp]
lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) :=
@infi_image (order_dual α) _ _ _ _ _ _
/-!
### `supr` and `infi` under `Type`
-/
theorem supr_of_empty' {α ι} [has_Sup α] [is_empty ι] (f : ι → α) :
supr f = Sup (∅ : set α) :=
congr_arg Sup (range_eq_empty f)
theorem supr_of_empty [is_empty ι] (f : ι → α) : supr f = ⊥ :=
(supr_of_empty' f).trans Sup_empty
theorem infi_of_empty' {α ι} [has_Inf α] [is_empty ι] (f : ι → α) :
infi f = Inf (∅ : set α) :=
congr_arg Inf (range_eq_empty f)
theorem infi_of_empty [is_empty ι] (f : ι → α) : infi f = ⊤ :=
@supr_of_empty (order_dual α) _ _ _ f
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
by rw [supr, bool.range_eq, Sup_pair, sup_comm]
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
@supr_bool_eq (order_dual α) _ _
lemma sup_eq_supr (x y : α) : x ⊔ y = ⨆ b : bool, cond b x y :=
by rw [supr_bool_eq, bool.cond_tt, bool.cond_ff]
lemma inf_eq_infi (x y : α) : x ⊓ y = ⨅ b : bool, cond b x y :=
@sup_eq_supr (order_dual α) _ _ _
lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
@infi_subtype (order_dual α) _ _ _ _
lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) :=
(@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) :
(⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t :=
supr_subtype
lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe)
theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, sigma.forall]
theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
@infi_sigma (order_dual α) _ _ _ _
theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, prod.forall]
theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
@infi_prod (order_dual α) _ _ _ _
theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff, le_infi_iff, sum.forall]
theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
@infi_sum (order_dual α) _ _ _ _
theorem supr_option (f : option β → α) :
(⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) :=
eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall]
theorem infi_option (f : option β → α) :
(⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) :=
@supr_option (order_dual α) _ _ _
/-- A version of `supr_option` useful for rewriting right-to-left. -/
lemma supr_option_elim (a : α) (f : β → α) : (⨆ o : option β, o.elim a f) = a ⊔ ⨆ b, f b :=
by simp [supr_option]
/-- A version of `infi_option` useful for rewriting right-to-left. -/
lemma infi_option_elim (a : α) (f : β → α) : (⨅ o : option β, o.elim a f) = a ⊓ ⨅ b, f b :=
@supr_option_elim (order_dual α) _ _ _ _
/-!
### `supr` and `infi` under `ℕ`
-/
lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) :=
begin
apply le_antisymm;
simp only [supr_le_iff],
{ exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw tsub_add_cancel_of_le hi }⟩ },
{ exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ }
end
lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) :=
@supr_ge_eq_supr_nat_add (order_dual α) _ _ _
lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) :
(⨆ n, f (n + k)) = ⨆ n, f n :=
le_antisymm (supr_le (λ i, (le_refl _).trans (le_supr _ (i + k))))
(supr_le_supr (λ i, hf (nat.le_add_right i k)))
@[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) :
(⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i :=
begin
have hf : monotone (λ n, ⨅ i ≥ n, f i),
from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))),
rw ←monotone.supr_nat_add hf k,
{ simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], },
end
lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i :=
begin
refine eq_of_forall_ge_iff (λ c, _),
simp only [sup_le_iff, supr_le_iff],
refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩,
rintro (_|i),
exacts [h.1, h.2 i]
end
lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i :=
@sup_supr_nat_succ (order_dual α) _ u
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff]
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) :=
by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff]
end complete_linear_order
/-!
### Instances
-/
instance Prop.complete_lattice : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
.. Prop.bounded_distrib_lattice }
@[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
@[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
@[simp] lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
@[simp] lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) :=
⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩
instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) :=
⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩
instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
{ Sup := Sup,
Inf := Inf,
le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i,
le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i,
.. pi.bounded_lattice }
lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)]
{s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅ f : s, (f : Πa, β a) a) :=
rfl
@[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)]
{f : ι → Πa, β a} {a : α} :
(⨅i, f i) a = (⨅i, f i a) :=
by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp]
lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f:s, (f : Πa, β a) a) :=
rfl
lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} :
Sup s a ↔ ∃ (r : α → Prop), r ∈ s ∧ r a :=
by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] }
lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} :
Sup s a b ↔ ∃ (r : α → β → Prop), r ∈ s ∧ r a b :=
by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] }
@[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)]
{f : ι → Πa, β a} {a : α} :
(⨆i, f i) a = (⨆i, f i a) :=
@infi_apply α (λ i, order_dual (β i)) _ _ f a
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h
end complete_lattice
namespace prod
variables (α β)
instance [has_Inf α] [has_Inf β] : has_Inf (α × β) :=
⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩
instance [has_Sup α] [has_Sup β] : has_Sup (α × β) :=
⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩
instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) :=
{ le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩,
Sup_le := assume s p h,
⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1,
Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩,
le_Inf := assume s p h,
⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1,
le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
.. prod.bounded_lattice α β,
.. prod.has_Sup α β,
.. prod.has_Inf α β }
end prod
section complete_lattice
variables [complete_lattice α] {a : α} {s : set α}
/-- This is a weaker version of `sup_Inf_eq` -/
lemma sup_Inf_le_infi_sup :
a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) :=
le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _
/-- This is a weaker version of `Inf_sup_eq` -/
lemma Inf_sup_le_infi_sup :
Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) :=
le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _
/-- This is a weaker version of `inf_Sup_eq` -/
lemma supr_inf_le_inf_Sup :
(⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s :=
supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h)
/-- This is a weaker version of `Sup_inf_eq` -/
lemma supr_inf_le_Sup_inf :
(⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a :=
supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h)
lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) :
disjoint i b :=
(supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _)
lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) :
disjoint b i :=
(supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _)
end complete_lattice
namespace complete_lattice
variables [complete_lattice α]
/-- An independent set of elements in a complete lattice is one in which every element is disjoint
from the `Sup` of the rest. -/
def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a}))
variables {s : set α} (hs : set_independent s)
@[simp]
lemma set_independent_empty : set_independent (∅ : set α) :=
λ x hx, (set.not_mem_empty x hx).elim
theorem set_independent.mono {t : set α} (hst : t ⊆ s) :
set_independent t :=
λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst))
/-- If the elements of a set are independent, then any pair within that set is disjoint. -/
lemma set_independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y :=
disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩)
include hs
/-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some
subset of the rest. -/
lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) :
disjoint x (Sup y) :=
begin
have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _),
rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this,
exact this,
end
omit hs
/-- An independent indexed family of elements in a complete lattice is one in which every element
is disjoint from the `supr` of the rest.
Example: an indexed family of non-zero elements in a
vector space is linearly independent iff the indexed family of subspaces they generate is
independent in this sense.
Example: an indexed family of submodules of a module is independent in this sense if
and only the natural map from the direct sum of the submodules to the module is injective. -/
def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop :=
∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j)
lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) :
set_independent s ↔ independent (coe : s → α) :=
begin
simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr],
apply forall_congr, intro a, apply forall_congr, intro ha,
congr' 2,
convert supr_subtype.symm,
simp [supr_and],
end
variables {t : ι → α} (ht : independent t)
theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) :=
iff.rfl
theorem independent_def' {ι : Type*} {t : ι → α} :
independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) :=
by {simp_rw Sup_image, refl}
theorem independent_def'' {ι : Type*} {t : ι → α} :
independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) :=
by {rw independent_def', tidy}
@[simp]
lemma independent_empty (t : empty → α) : independent t.
@[simp]
lemma independent_pempty (t : pempty → α) : independent t.
/-- If the elements of a set are independent, then any pair within that set is disjoint. -/
lemma independent.disjoint {x y : ι} (h : x ≠ y) : disjoint (t x) (t y) :=
disjoint_Sup_right (ht x) ⟨y, by simp [h.symm]⟩
lemma independent.mono {ι : Type*} {α : Type*} [complete_lattice α]
{s t : ι → α} (hs : independent s) (hst : t ≤ s) :
independent t :=
λ i, (hs i).mono (hst i) (supr_le_supr $ λ j, supr_le_supr $ λ _, hst j)
/-- Composing an independent indexed family with an injective function on the index results in
another indepedendent indexed family. -/
lemma independent.comp {ι ι' : Sort*} {α : Type*} [complete_lattice α]
{s : ι → α} (hs : independent s) (f : ι' → ι) (hf : function.injective f) :
independent (s ∘ f) :=
λ i, (hs (f i)).mono_right begin
refine (supr_le_supr $ λ i, _).trans (supr_comp_le _ f),
exact supr_le_supr_const hf.ne,
end
/-- Composing an indepedent indexed family with an order isomorphism on the elements results in
another indepedendent indexed family. -/
lemma independent.map_order_iso {ι : Sort*} {α β : Type*}
[complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} (ha : independent a) :
independent (f ∘ a) :=
λ i, ((ha i).map_order_iso f).mono_right (f.monotone.le_map_supr2 _)
@[simp] lemma independent_map_order_iso_iff {ι : Sort*} {α β : Type*}
[complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} :
independent (f ∘ a) ↔ independent a :=
⟨ λ h, have hf : f.symm ∘ f ∘ a = a := congr_arg (∘ a) f.left_inv.comp_eq_id,
hf ▸ h.map_order_iso f.symm,
λ h, h.map_order_iso f⟩
/-- If the elements of a set are independent, then any element is disjoint from the `supr` of some
subset of the rest. -/
lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α]
{t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) :
disjoint (t x) (⨆ i ∈ y, t i) :=
disjoint.mono_right (bsupr_le_bsupr' $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x)
end complete_lattice
|
b06731210d59a109a4c2a89c6c0b346c2148dd2d | a4673261e60b025e2c8c825dfa4ab9108246c32e | /src/Init/Data/FloatArray/Basic.lean | b57e99fd89d07d7b8631bee035cc77a7a4e38f29 | [
"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 | 2,001 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.Array.Basic
import Init.Data.Float
import Init.Data.Option.Basic
universes u
structure FloatArray :=
(data : Array Float)
attribute [extern "lean_float_array_mk"] FloatArray.mk
attribute [extern "lean_float_array_data"] FloatArray.data
namespace FloatArray
@[extern "lean_mk_empty_float_array"]
def mkEmpty (c : @& Nat) : FloatArray :=
{ data := #[] }
def empty : FloatArray :=
mkEmpty 0
instance : Inhabited FloatArray := ⟨empty⟩
@[extern "lean_float_array_push"]
def push : FloatArray → Float → FloatArray
| ⟨ds⟩, b => ⟨ds.push b⟩
@[extern "lean_float_array_size"]
def size : (@& FloatArray) → Nat
| ⟨ds⟩ => ds.size
@[extern "lean_float_array_fget"]
def get (ds : @& FloatArray) (i : @& Fin ds.size) : Float :=
match ds, i with
| ⟨ds⟩, i => ds.get i
@[extern "lean_float_array_get"]
def get! : (@& FloatArray) → (@& Nat) → Float
| ⟨ds⟩, i => ds.get! i
def get? (ds : FloatArray) (i : Nat) : Option Float :=
if h : i < ds.size then
ds.get ⟨i, h⟩
else
none
@[extern "lean_float_array_fset"]
def set (ds : FloatArray) (i : @& Fin ds.size) (d : Float) : FloatArray :=
match ds, i with
| ⟨ds⟩, i=> ⟨ds.set i d⟩
@[extern "lean_float_array_set"]
def set! : FloatArray → (@& Nat) → Float → FloatArray
| ⟨ds⟩, i, d => ⟨ds.set! i d⟩
def isEmpty (s : FloatArray) : Bool :=
s.size == 0
partial def toList (ds : FloatArray) : List Float :=
let rec loop (i r) :=
if h : i < ds.size then
loop (i+1) (ds.get ⟨i, h⟩ :: r)
else
r.reverse
loop 0 []
end FloatArray
def List.toFloatArray (ds : List Float) : FloatArray :=
let rec loop
| [], r => r
| b::ds, r => loop ds (r.push b)
loop ds FloatArray.empty
instance : ToString FloatArray := ⟨fun ds => ds.toList.toString⟩
|
e5e8944a75eecc4ac3d77bd1e5ff2595bd21dd10 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/field_theory/splitting_field/construction.lean | 85ec974bcb0017260916489c08b3863a77141011 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 15,117 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import field_theory.normal
/-!
# Splitting fields
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove the existence and uniqueness of splitting fields.
## Main definitions
* `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`.
## Main statements
* `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorphic
to `splitting_field f` and thus, being a splitting field is unique up to isomorphism.
## Implementation details
We construct a `splitting_field_aux` without worrying about whether the instances satisfy nice
definitional equalities. Then the actual `splitting_field` is defined to be a quotient of a
`mv_polynomial` ring by the kernel of the obvious map into `splitting_field_aux`. Because the
actual `splitting_field` will be a quotient of a `mv_polynomial`, it has nice instances on it.
-/
noncomputable theory
open_locale classical big_operators polynomial
universes u v w
variables {F : Type u} {K : Type v} {L : Type w}
namespace polynomial
variables [field K] [field L] [field F]
open polynomial
section splitting_field
/-- Non-computably choose an irreducible factor from a polynomial. -/
def factor (f : K[X]) : K[X] :=
if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X
lemma irreducible_factor (f : K[X]) : irreducible (factor f) :=
begin
rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X }
end
/-- See note [fact non-instances]. -/
lemma fact_irreducible_factor (f : K[X]) : fact (irreducible (factor f)) :=
⟨irreducible_factor f⟩
local attribute [instance] fact_irreducible_factor
theorem factor_dvd_of_not_is_unit {f : K[X]} (hf1 : ¬is_unit f) : factor f ∣ f :=
begin
by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ },
rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)],
exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2
end
theorem factor_dvd_of_degree_ne_zero {f : K[X]} (hf : f.degree ≠ 0) : factor f ∣ f :=
factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf)
theorem factor_dvd_of_nat_degree_ne_zero {f : K[X]} (hf : f.nat_degree ≠ 0) :
factor f ∣ f :=
factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf)
/-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/
def remove_factor (f : K[X]) : polynomial (adjoin_root $ factor f) :=
map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor))
theorem X_sub_C_mul_remove_factor (f : K[X]) (hf : f.nat_degree ≠ 0) :
(X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f :=
let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in
mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg,
adjoin_root.eval₂_root, zero_mul]
theorem nat_degree_remove_factor (f : K[X]) :
f.remove_factor.nat_degree = f.nat_degree - 1 :=
by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map,
nat_degree_X_sub_C]
theorem nat_degree_remove_factor' {f : K[X]} {n : ℕ} (hfn : f.nat_degree = n+1) :
f.remove_factor.nat_degree = n :=
by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel]
/-- Auxiliary construction to a splitting field of a polynomial, which removes
`n` (arbitrarily-chosen) factors.
It constructs the type, proves that is a field and algebra over the base field.
Uses recursion on the degree.
-/
def splitting_field_aux_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : K[X]),
Σ (L : Type u) (inst : field L), by exactI algebra K L :=
nat.rec_on n (λ K inst f, ⟨K, inst, infer_instance⟩) (λ m ih K inst f,
let L := ih (@remove_factor K inst f) in let h₁ := L.2.1 in let h₂ := L.2.2 in
⟨L.1, L.2.1, by
{ exactI (ring_hom.comp (algebra_map _ _) (adjoin_root.of f.factor)).to_algebra }⟩)
/-- Auxiliary construction to a splitting field of a polynomial, which removes
`n` (arbitrarily-chosen) factors. It is the type constructed in `splitting_field_aux_aux`.
-/
def splitting_field_aux (n : ℕ) {K : Type u} [field K] (f : K[X]) : Type u :=
(splitting_field_aux_aux n f).1
instance splitting_field_aux.field (n : ℕ) {K : Type u} [field K] (f : K[X]) :
field (splitting_field_aux n f) :=
(splitting_field_aux_aux n f).2.1
instance (n : ℕ) {K : Type u} [field K] (f : K[X]) : inhabited (splitting_field_aux n f) :=
⟨0⟩
instance splitting_field_aux.algebra (n : ℕ) {K : Type u} [field K] (f : K[X]) :
algebra K (splitting_field_aux n f) :=
(splitting_field_aux_aux n f).2.2
namespace splitting_field_aux
theorem succ (n : ℕ) (f : K[X]) :
splitting_field_aux (n+1) f = splitting_field_aux n f.remove_factor := rfl
instance algebra''' {n : ℕ} {f : K[X]} :
algebra (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor) :=
splitting_field_aux.algebra n _
instance algebra' {n : ℕ} {f : K[X]} :
algebra (adjoin_root f.factor) (splitting_field_aux n.succ f) :=
splitting_field_aux.algebra'''
instance algebra'' {n : ℕ} {f : K[X]} :
algebra K (splitting_field_aux n f.remove_factor) :=
ring_hom.to_algebra (ring_hom.comp (algebra_map _ _) (adjoin_root.of f.factor))
instance scalar_tower' {n : ℕ} {f : K[X]} :
is_scalar_tower K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor) :=
is_scalar_tower.of_algebra_map_eq (λ x, rfl)
theorem algebra_map_succ (n : ℕ) (f : K[X]) :
by exact algebra_map K (splitting_field_aux (n+1) f) =
(algebra_map (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor)).comp
(adjoin_root.of f.factor) :=
rfl
protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI
∀ (f : K[X]) (hfn : f.nat_degree = n),
splits (algebra_map K $ splitting_field_aux n f) f :=
nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _
(le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf,
by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits,
← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })],
exact splits_mul _ (splits_X_sub_C _) (ih _ (nat_degree_remove_factor' hf)) }
theorem adjoin_root_set (n : ℕ) : ∀ {K : Type u} [field K], by exactI
∀ (f : K[X]) (hfn : f.nat_degree = n),
algebra.adjoin K (f.root_set (splitting_field_aux n f)) = ⊤ :=
nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $
λ n ih K _ f hfn, by exactI
have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn },
have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl },
have hmf0 : map (algebra_map K (splitting_field_aux n.succ f)) f ≠ 0 := map_ne_zero hfn0,
begin
simp_rw root_set at ⊢ ih,
rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf,
polynomial.map_mul] at hmf0 ⊢,
rw [roots_mul hmf0, polynomial.map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add,
finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton,
algebra.adjoin_union_eq_adjoin_adjoin, ← set.image_singleton,
algebra.adjoin_algebra_map K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor),
adjoin_root.adjoin_root_eq_top, algebra.map_top,
is_scalar_tower.adjoin_range_to_alg_hom K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor),
ih _ (nat_degree_remove_factor' hfn), subalgebra.restrict_scalars_top]
end
instance (f : K[X]) : is_splitting_field K (splitting_field_aux f.nat_degree f) f :=
⟨splitting_field_aux.splits _ _ rfl, splitting_field_aux.adjoin_root_set _ _ rfl⟩
/-- The natural map from `mv_polynomial (f.root_set (splitting_field_aux f.nat_degree f))`
to `splitting_field_aux f.nat_degree f` sendind a variable to the corresponding root. -/
def of_mv_polynomial (f : K[X]) :
mv_polynomial (f.root_set (splitting_field_aux f.nat_degree f)) K →ₐ[K]
splitting_field_aux f.nat_degree f :=
mv_polynomial.aeval (λ i, i.1)
theorem of_mv_polynomial_surjective (f : K[X]) : function.surjective (of_mv_polynomial f) :=
begin
suffices : alg_hom.range (of_mv_polynomial f) = ⊤,
{ rw [← set.range_iff_surjective]; rwa [set_like.ext'_iff] at this },
rw [of_mv_polynomial, ← algebra.adjoin_range_eq_range_aeval K, eq_top_iff,
← adjoin_root_set _ _ rfl],
exact algebra.adjoin_le (λ α hα, algebra.subset_adjoin ⟨⟨α, hα⟩, rfl⟩)
end
/-- The algebra isomorphism between the quotient of
`mv_polynomial (f.root_set (splitting_field_aux f.nat_degree f)) K` by the kernel of
`of_mv_polynomial f` and `splitting_field_aux f.nat_degree f`. It is used to transport all the
algebraic structures from the latter to `f.splitting_field`, that is defined as the former. -/
def alg_equiv_quotient_mv_polynomial (f : K[X]) :
(mv_polynomial (f.root_set (splitting_field_aux f.nat_degree f)) K ⧸
ring_hom.ker (of_mv_polynomial f).to_ring_hom) ≃ₐ[K]
splitting_field_aux f.nat_degree f :=
(ideal.quotient_ker_alg_equiv_of_surjective (of_mv_polynomial_surjective f) : _)
end splitting_field_aux
/-- A splitting field of a polynomial. -/
def splitting_field (f : K[X]) :=
mv_polynomial (f.root_set (splitting_field_aux f.nat_degree f)) K ⧸
ring_hom.ker (splitting_field_aux.of_mv_polynomial f).to_ring_hom
namespace splitting_field
variables (f : K[X])
instance comm_ring : comm_ring (splitting_field f) :=
ideal.quotient.comm_ring _
instance inhabited : inhabited (splitting_field f) :=
⟨37⟩
instance {S : Type*} [distrib_smul S K] [is_scalar_tower S K K] :
has_smul S (splitting_field f) :=
submodule.quotient.has_smul' _
instance algebra : algebra K (splitting_field f) :=
ideal.quotient.algebra _
instance algebra' {R : Type*} [comm_semiring R] [algebra R K] : algebra R (splitting_field f) :=
ideal.quotient.algebra _
instance is_scalar_tower {R : Type*} [comm_semiring R] [algebra R K] :
is_scalar_tower R K (splitting_field f) :=
ideal.quotient.is_scalar_tower _ _ _
/-- The algebra equivalence with `splitting_field_aux`,
which we will use to construct the field structure. -/
def alg_equiv_splitting_field_aux (f : K[X]) :
splitting_field f ≃ₐ[K] splitting_field_aux f.nat_degree f :=
splitting_field_aux.alg_equiv_quotient_mv_polynomial f
instance : field (splitting_field f) :=
let e := alg_equiv_splitting_field_aux f in
{ rat_cast := λ a, algebra_map K _ (a : K),
inv := λ a, e.symm (e a)⁻¹,
qsmul := (•),
qsmul_eq_mul' := λ a x, quotient.induction_on' x (λ p, congr_arg quotient.mk'
begin
ext,
simp only [mv_polynomial.algebra_map_eq, rat.smul_def, mv_polynomial.coeff_smul,
mv_polynomial.coeff_C_mul],
end),
rat_cast_mk := λ a b h1 h2,
begin
apply e.injective,
change e (algebra_map K _ _) = _,
simp only [map_rat_cast, map_nat_cast, map_mul, map_int_cast, alg_equiv.commutes],
change _ = e ↑a * e (e.symm (e b)⁻¹),
rw [alg_equiv.apply_symm_apply],
convert field.rat_cast_mk a b h1 h2,
all_goals { simp },
end,
exists_pair_ne := ⟨e.symm 0, e.symm 1, λ w, zero_ne_one ((e.symm).injective w)⟩,
mul_inv_cancel := λ a w,
begin
apply e.injective,
rw [map_mul, map_one],
change e a * e (e.symm (e a)⁻¹) = 1,
rw [alg_equiv.apply_symm_apply, mul_inv_cancel],
exact (λ w', w (by simpa only [add_equiv_class.map_eq_zero_iff] using w')),
end,
inv_zero :=
begin
change e.symm (e 0)⁻¹ = 0,
simp
end,
..splitting_field.comm_ring f }
instance [char_zero K] : char_zero (splitting_field f) :=
char_zero_of_injective_algebra_map ((algebra_map K _).injective)
-- The algebra instance deriving from `K` should be definitionally equal to that
-- deriving from the field structure on `splitting_field f`.
example : (add_comm_monoid.nat_module : module ℕ (splitting_field f)) =
@algebra.to_module _ _ _ _ (splitting_field.algebra' f) :=
rfl
example : (add_comm_group.int_module _ : module ℤ (splitting_field f)) =
@algebra.to_module _ _ _ _ (splitting_field.algebra' f) :=
rfl
example [char_zero K] : (splitting_field.algebra' f) = algebra_rat :=
rfl
example {q : ℚ[X]} : algebra_int (splitting_field q) = splitting_field.algebra' q := rfl
instance _root_.polynomial.is_splitting_field.splitting_field (f : K[X]) :
is_splitting_field K (splitting_field f) f :=
is_splitting_field.of_alg_equiv _ f (splitting_field_aux.alg_equiv_quotient_mv_polynomial f).symm
protected theorem splits : splits (algebra_map K (splitting_field f)) f :=
is_splitting_field.splits f.splitting_field f
variables [algebra K L] (hb : splits (algebra_map K L) f)
/-- Embeds the splitting field into any other field that splits the polynomial. -/
def lift : splitting_field f →ₐ[K] L :=
is_splitting_field.lift f.splitting_field f hb
theorem adjoin_root_set : algebra.adjoin K (f.root_set (splitting_field f)) = ⊤ :=
polynomial.is_splitting_field.adjoin_root_set _ f
end splitting_field
end splitting_field
namespace is_splitting_field
variables (K L) [algebra K L]
variables {K}
instance (f : K[X]) : _root_.finite_dimensional K f.splitting_field :=
finite_dimensional f.splitting_field f
instance [fintype K] (f : K[X]) : fintype f.splitting_field :=
finite_dimensional.fintype_of_fintype K _
instance (f : K[X]) : no_zero_smul_divisors K f.splitting_field := infer_instance
/-- Any splitting field is isomorphic to `splitting_field f`. -/
def alg_equiv (f : K[X]) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f :=
begin
refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f)
⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩,
haveI := finite_dimensional (splitting_field f) f,
haveI := finite_dimensional L f,
have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) :=
le_antisymm
(linear_map.finrank_le_finrank_of_injective
(show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from
ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field)))
(linear_map.finrank_le_finrank_of_injective
(show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from
ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))),
change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map,
refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _,
exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field)
end
end is_splitting_field
end polynomial
section normal
instance [field F] (p : F[X]) : normal F p.splitting_field := normal.of_is_splitting_field p
end normal
|
fd1ca304b6e6c24d65afacd1228286f9134d41a7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/computability/NFA.lean | 1026ac008c6fb8295fadf922f5ae303e290aef4b | [
"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 | 5,015 | lean | /-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import computability.DFA
import data.fintype.powerset
/-!
# Nondeterministic Finite Automata
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine
which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular
set by evaluating the string over every possible path.
We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an
exponential number of states.
Note that this definition allows for Automaton with infinite states, a `fintype` instance must be
supplied for true NFA's.
-/
open set
open_locale computability
universes u v
/-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`).
Note the transition function sends a state to a `set` of states. These are the states that it
may be sent to. -/
structure NFA (α : Type u) (σ : Type v) :=
(step : σ → α → set σ)
(start : set σ)
(accept : set σ)
variables {α : Type u} {σ σ' : Type v} (M : NFA α σ)
namespace NFA
instance : inhabited (NFA α σ) := ⟨ NFA.mk (λ _ _, ∅) ∅ ∅ ⟩
/-- `M.step_set S a` is the union of `M.step s a` for all `s ∈ S`. -/
def step_set (S : set σ) (a : α) : set σ := ⋃ s ∈ S, M.step s a
lemma mem_step_set (s : σ) (S : set σ) (a : α) : s ∈ M.step_set S a ↔ ∃ t ∈ S, s ∈ M.step t a :=
mem_Union₂
@[simp] lemma step_set_empty (a : α) : M.step_set ∅ a = ∅ :=
by simp_rw [step_set, Union_false, Union_empty]
/-- `M.eval_from S x` computes all possible paths though `M` with input `x` starting at an element
of `S`. -/
def eval_from (start : set σ) : list α → set σ :=
list.foldl M.step_set start
@[simp] lemma eval_from_nil (S : set σ) : M.eval_from S [] = S := rfl
@[simp] lemma eval_from_singleton (S : set σ) (a : α) : M.eval_from S [a] = M.step_set S a := rfl
@[simp] lemma eval_from_append_singleton (S : set σ) (x : list α) (a : α) :
M.eval_from S (x ++ [a]) = M.step_set (M.eval_from S x) a :=
by simp only [eval_from, list.foldl_append, list.foldl_cons, list.foldl_nil]
/-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of
`M.start`. -/
def eval : list α → set σ := M.eval_from M.start
@[simp] lemma eval_nil : M.eval [] = M.start := rfl
@[simp] lemma eval_singleton (a : α) : M.eval [a] = M.step_set M.start a := rfl
@[simp] lemma eval_append_singleton (x : list α) (a : α) :
M.eval (x ++ [a]) = M.step_set (M.eval x) a :=
eval_from_append_singleton _ _ _ _
/-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/
def accepts : language α :=
λ x, ∃ S ∈ M.accept, S ∈ M.eval x
/-- `M.to_DFA` is an `DFA` constructed from a `NFA` `M` using the subset construction. The
states is the type of `set`s of `M.state` and the step function is `M.step_set`. -/
def to_DFA : DFA α (set σ) :=
{ step := M.step_set,
start := M.start,
accept := {S | ∃ s ∈ S, s ∈ M.accept} }
@[simp] lemma to_DFA_correct :
M.to_DFA.accepts = M.accepts :=
begin
ext x,
rw [accepts, DFA.accepts, eval, DFA.eval],
change list.foldl _ _ _ ∈ {S | _} ↔ _,
split; { exact λ ⟨w, h2, h3⟩, ⟨w, h3, h2⟩ },
end
lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts)
(hlen : fintype.card (set σ) ≤ list.length x) :
∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card (set σ) ∧ b ≠ [] ∧
{a} * {b}∗ * {c} ≤ M.accepts :=
begin
rw ←to_DFA_correct at hx ⊢,
exact M.to_DFA.pumping_lemma hx hlen
end
end NFA
namespace DFA
/-- `M.to_NFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept
states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/
def to_NFA (M : DFA α σ') : NFA α σ' :=
{ step := λ s a, {M.step s a},
start := {M.start},
accept := M.accept }
@[simp] lemma to_NFA_eval_from_match (M : DFA α σ) (start : σ) (s : list α) :
M.to_NFA.eval_from {start} s = {M.eval_from start s} :=
begin
change list.foldl M.to_NFA.step_set {start} s = {list.foldl M.step start s},
induction s with a s ih generalizing start,
{ tauto },
{ rw [list.foldl, list.foldl,
show M.to_NFA.step_set {start} a = {M.step start a}, by simpa [NFA.step_set]],
tauto }
end
@[simp] lemma to_NFA_correct (M : DFA α σ) :
M.to_NFA.accepts = M.accepts :=
begin
ext x,
change (∃ S H, S ∈ M.to_NFA.eval_from {M.start} x) ↔ _,
rw to_NFA_eval_from_match,
split,
{ rintro ⟨ S, hS₁, hS₂ ⟩,
rwa set.mem_singleton_iff.mp hS₂ at hS₁ },
{ exact λ h, ⟨M.eval x, h, rfl⟩ }
end
end DFA
|
6b38caeb4491c7fab99ba32a5608da619a66ccdb | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/zsqrtd/basic.lean | af6b10af5855779bc5299ca81de30cef357efecc | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 27,014 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.basic algebra.associated data.nat.gcd tactic.ring
/-- The ring of integers adjoined with a square root of `d`.
These have the form `a + b √d` where `a b : ℤ`. The components
are called `re` and `im` by analogy to the negative `d` case,
but of course both parts are real here since `d` is nonnegative. -/
structure zsqrtd (d : ℤ) :=
(re : ℤ)
(im : ℤ)
prefix `ℤ√`:100 := zsqrtd
namespace zsqrtd
section
parameters {d : ℤ}
instance : decidable_eq ℤ√d :=
by tactic.mk_dec_eq_instance
theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im
| ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption,
λ ⟨h₁, h₂⟩, by congr; assumption⟩
/-- Convert an integer to a `ℤ√d` -/
def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩
theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl
theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl
/-- The zero of the ring -/
def zero : ℤ√d := of_int 0
instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩
@[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl
@[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl
instance : inhabited ℤ√d := ⟨0⟩
/-- The one of the ring -/
def one : ℤ√d := of_int 1
instance : has_one ℤ√d := ⟨zsqrtd.one⟩
@[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl
@[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl
/-- The representative of `√d` in the ring -/
def sqrtd : ℤ√d := ⟨0, 1⟩
@[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl
@[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl
/-- Addition of elements of `ℤ√d` -/
def add : ℤ√d → ℤ√d → ℤ√d
| ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩
instance : has_add ℤ√d := ⟨zsqrtd.add⟩
@[simp] theorem add_def (x y x' y' : ℤ) :
(⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl
@[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re
| ⟨x, y⟩ ⟨x', y'⟩ := rfl
@[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im
| ⟨x, y⟩ ⟨x', y'⟩ := rfl
@[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _
@[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _
@[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1]
@[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1]
/-- Negation in `ℤ√d` -/
def neg : ℤ√d → ℤ√d
| ⟨x, y⟩ := ⟨-x, -y⟩
instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩
@[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re
| ⟨x, y⟩ := rfl
@[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im
| ⟨x, y⟩ := rfl
/-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/
def conj : ℤ√d → ℤ√d
| ⟨x, y⟩ := ⟨x, -y⟩
@[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re
| ⟨x, y⟩ := rfl
@[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im
| ⟨x, y⟩ := rfl
/-- Multiplication in `ℤ√d` -/
def mul : ℤ√d → ℤ√d → ℤ√d
| ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩
instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩
@[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im
| ⟨x, y⟩ ⟨x', y'⟩ := rfl
@[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re
| ⟨x, y⟩ ⟨x', y'⟩ := rfl
instance : comm_ring ℤ√d := by refine
{ add := (+),
zero := 0,
neg := has_neg.neg,
mul := (*),
one := 1, ..};
{ intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] }
instance : add_comm_monoid ℤ√d := by apply_instance
instance : add_monoid ℤ√d := by apply_instance
instance : monoid ℤ√d := by apply_instance
instance : comm_monoid ℤ√d := by apply_instance
instance : comm_semigroup ℤ√d := by apply_instance
instance : semigroup ℤ√d := by apply_instance
instance : add_comm_semigroup ℤ√d := by apply_instance
instance : add_semigroup ℤ√d := by apply_instance
instance : comm_semiring ℤ√d := by apply_instance
instance : semiring ℤ√d := by apply_instance
instance : ring ℤ√d := by apply_instance
instance : distrib ℤ√d := by apply_instance
instance : zero_ne_one_class ℤ√d :=
{ zero := 0, one := 1, zero_ne_one := dec_trivial }
instance : nonzero_comm_ring ℤ√d :=
{ ..zsqrtd.comm_ring, ..zsqrtd.zero_ne_one_class }
@[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n :=
by induction n; simp *
@[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 :=
by induction n; simp *
theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ :=
by simp [ext]
@[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n :=
by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq]
@[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 :=
by cases n; simp *
theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ :=
by simp [ext]
instance : char_zero ℤ√d :=
{ cast_injective := λ m n, by simp [ext] }
@[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n :=
by simp [ext, of_int_re, of_int_im]
@[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ :=
by simp [ext]
@[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ :=
by simp [ext]
@[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ :=
by simp [ext]
theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y :=
by simp [ext]
theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y :=
by simp [ext, sub_eq_add_neg, mul_comm]
theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b :=
by simp [ext, add_comm]
protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext]
protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext, sub_eq_add_neg]
protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext]
protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n :=
by simpa using congr_arg re h
/-- Read `sq_le a c b d` as `a √c ≤ b √d` -/
def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b
theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d :=
le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $
le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _))
theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) :
c * (x * z) ≤ d * (y * w) :=
nat.mul_self_le_mul_self_iff.2 $
by simpa [mul_comm, mul_left_comm] using
mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _)
theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) :
sq_le (x + z) c (y + w) d :=
begin
have xz := sq_le_add_mixed xy zw,
simp [sq_le, mul_assoc] at xy zw,
simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *]
end
theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d :=
begin
apply le_of_not_gt,
intro l,
refine not_le_of_gt _ h,
simp [sq_le, mul_add, mul_comm, mul_left_comm],
have hm := sq_le_add_mixed zw (le_of_lt l),
simp [sq_le, mul_assoc] at l zw,
exact lt_of_le_of_lt (add_le_add_right zw _)
(add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _)
end
theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d :=
by simpa [sq_le, mul_left_comm, mul_assoc] using
nat.mul_le_mul_left (n * n) xy
theorem sq_le_mul {d x y z w : ℕ} :
(sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧
(sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧
(sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧
(sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) :=
by refine ⟨_, _, _, _⟩; {
intros xy zw,
have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy))
(sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)),
refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _),
convert this,
simp only [one_mul, int.coe_nat_add, int.coe_nat_mul],
ring }
/-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`;
we are interested in the case `c = 1` but this is more symmetric -/
def nonnegg (c d : ℕ) : ℤ → ℤ → Prop
| (a : ℕ) (b : ℕ) := true
| (a : ℕ) -[1+ b] := sq_le (b+1) c a d
| -[1+ a] (b : ℕ) := sq_le (a+1) d b c
| -[1+ a] -[1+ b] := false
theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x :=
by induction x; induction y; refl
theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c
| 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩
| (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl
theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d :=
by rw nonnegg_comm; exact nonnegg_neg_pos
theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b
| (b:nat) h := trivial
| -[1+ b] h := h (b+1) rfl
theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b :=
cast nonnegg_comm (nonnegg_cases_right h)
section norm
def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im
@[simp] lemma norm_zero : norm 0 = 0 := by simp [norm]
@[simp] lemma norm_one : norm 1 = 1 := by simp [norm]
@[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm]
@[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n
@[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m :=
by { simp only [norm, mul_im, mul_re], ring }
lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj :=
by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg]
instance : is_monoid_hom norm :=
{ map_one := norm_one, map_mul := norm_mul }
lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm :=
add_nonneg (mul_self_nonneg _)
(by rw [mul_assoc, neg_mul_eq_neg_mul];
exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _)))
lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x :=
⟨λ h, is_unit_iff_dvd_one.2 $
(le_total 0 (norm x)).cases_on
(λ hx, show x ∣ 1, from ⟨x.conj,
by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx,
← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩)
(λ hx, show x ∣ 1, from ⟨- x.conj,
by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx,
← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg,
eq_comm] at h⟩),
λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin
have := congr_arg (int.nat_abs ∘ norm) hy,
rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul,
norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this,
exact this.1
end⟩
end norm
end
section
parameter {d : ℕ}
/-- Nonnegativity of an element of `ℤ√d`. -/
def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b
protected def le (a b : ℤ√d) : Prop := nonneg (b - a)
instance : has_le ℤ√d := ⟨zsqrtd.le⟩
protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a)
instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩
instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) :=
by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance
instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a)
| ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _
instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _
theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩
| ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩
| ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩
| ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩
| ⟨-[1+ x], -[1+ y]⟩ h := false.elim h
lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) :=
have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z
(λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩)
(λj k, int.sub_nat_nat_elim w y
(λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩)
(λm n xy zw, trivial)
(λm n xy zw, sq_le_cancel zw xy))
(λj k, int.sub_nat_nat_elim w y
(λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩)
(λm n xy zw, sq_le_cancel xy zw)
(λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in
have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t),
absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw),
show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this
theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) :=
begin
rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩;
rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢,
{ trivial },
{ refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) },
{ apply nat.le_add_left } },
{ refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) },
{ apply nat.le_add_left } },
{ refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) },
{ apply nat.le_add_right } },
{ simpa [add_comm] using
nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) },
{ exact nonneg_add_lem ha hb },
{ refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) },
{ apply nat.le_add_right } },
{ rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha },
{ simpa [add_comm] using
nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) },
end
theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp
protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c :=
have nonneg (b - a + (c - b)), from nonneg_add ab bc,
by simpa [sub_eq_add_neg, add_left_comm]
theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp
theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ :=
show nonneg ⟨z - x, w - y⟩, from
match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end
theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n :=
let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with
| ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩
| ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe]⟩
| ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe]⟩
| ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe]⟩
end in begin
refine ⟨x + d*y, zsqrtd.le_trans h _⟩,
rw [← int.cast_coe_nat, ← of_int_eq_coe],
change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩,
cases y with y,
{ simp },
have h : ∀y, sq_le y d (d * y) 1 := λ y,
by simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_right (y * y) (nat.le_mul_self d),
rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp],
exact h (y+1)
end
protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a)
| ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial
| ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial
| ⟨0, -[1+ y]⟩ := or.inr trivial
| ⟨-[1+ x], 0⟩ := or.inr trivial
| ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total
| ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total
protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a :=
let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t
instance : preorder ℤ√d :=
{ le := zsqrtd.le,
le_refl := zsqrtd.le_refl,
le_trans := @zsqrtd.le_trans,
lt := zsqrtd.lt,
lt_iff_le_not_le := λ a b,
(and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm }
protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b :=
show nonneg _, by rw add_sub_add_left_eq_sub; exact ab
protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b :=
by simpa using zsqrtd.add_le_add_left _ _ h (-c)
protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b :=
λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h')
theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) :=
by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with
| ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial
| ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using
nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha)
| ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using
nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha)
end
theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) :=
by refine match a, nonneg_cases ha, ha with
| ._, ⟨x, y, or.inl rfl⟩, ha := trivial
| ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2;
simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha)
| ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2;
simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha)
end
theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) :=
have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl,
by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha)
theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) :=
match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with
| ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial
| ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb
| ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb
| ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha
| ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha
| ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb :=
by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl
... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact
nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb))
| ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb :=
by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl
... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact
nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb))
| ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb :=
by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl
... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact
nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb))
| ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb :=
by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl
... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact
nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb))
end
protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b :=
by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul
theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d :=
not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _
/-- A nonsquare is a natural number that is not equal to the square of an
integer. This is implemented as a typeclass because it's a necessary condition
for much of the Pell equation theory. -/
class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n)
parameter [dnsq : nonsquare d]
include dnsq
theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0)
theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 :=
let g := x.gcd y in or.elim g.eq_zero_or_pos
(λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩)
(λgpos, false.elim $
let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in
begin
rw [hx, hy] at h,
have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos)
(by simpa [mul_comm, mul_left_comm] using h),
have co2 := let co1 := co.mul_right co in co1.mul co1,
exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $
co2.dvd_of_dvd_mul_right $ by simp [this])
end)
theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 :=
by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h;
exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in
⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩
theorem not_divides_square (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) :=
λe, by have t := (divides_sq_eq_zero e).left; contradiction
theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0
| ⟨0, 0⟩ xy yx := rfl
| ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy
| ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx
| ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial)
| ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial)
| ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos)
| ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos)
| ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) :=
let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _)
| ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) :=
let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _)
theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b :=
eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab)
instance : decidable_linear_order ℤ√d :=
{ le_antisymm := @zsqrtd.le_antisymm,
le_total := zsqrtd.le_total,
decidable_le := zsqrtd.decidable_le,
..zsqrtd.preorder }
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0
| ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact
have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1,
have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2,
have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from
λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end,
if z0 : z = 0 then if w0 : w = 0 then
or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end)
else
or.inl $ fin $ eq_of_mul_eq_mul_right w0 $ calc
x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm]
... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm]
else
or.inl $ fin $ eq_of_mul_eq_mul_right z0 $ calc
x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm]
... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm]
instance : integral_domain ℤ√d :=
{ zero_ne_one := zero_ne_one,
eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero,
..zsqrtd.comm_ring }
protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab,
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0))))
(λe, ne_of_gt a0 e)
(λe, ne_of_gt b0 e)
instance : decidable_linear_ordered_comm_ring ℤ√d :=
{ add_le_add_left := @zsqrtd.add_le_add_left,
zero_ne_one := zero_ne_one,
mul_pos := @zsqrtd.mul_pos,
zero_lt_one := dec_trivial,
..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order }
instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance
instance : linear_ordered_semiring ℤ√d := by apply_instance
instance : ordered_semiring ℤ√d := by apply_instance
end
end zsqrtd
|
784198a385f45e2723008e849e2f07e26b59e528 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/fresh_names.lean | eab2d682ea7ed43e8a8562cecac624a80a513eeb | [
"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 | 5,086 | lean | /-
Copyright (c) 2020 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jannis Limperg
-/
import data.sum
import meta.rb_map
import tactic.dependencies
/-!
# Tactics for giving hypotheses fresh names
When introducing hypotheses, we often want to make sure that their names are
fresh, i.e. not used by any other hypothesis in the context. This file provides
tactics which allow you to give a list of possible names for each hypothesis,
with the tactics picking the first name that is not yet used in the context. If
all names are already used, the tactics use a name derived from the first name
in the list.
-/
namespace tactic
-- This implementation is a bit of a hack, but probably fine in practice since
-- we're unlikely to need more than two or three iterations of the loop.
private meta def get_unused_name_reserved_aux (n : name) (reserved : name_set) :
option nat → tactic name :=
λ suffix, do
n ← get_unused_name n suffix,
if ¬ reserved.contains n
then pure n
else do
let new_suffix :=
match suffix with
| none := some 1
| some n := some (n + 1)
end,
get_unused_name_reserved_aux new_suffix
/--
`get_unused_name_reserved ns reserved` returns the first name from `ns` that
occurs neither in `reserved` nor in the environment. If there is no such name in
`ns`, it returns a name of the form `n_i`, where `n` is the first name from `ns`
and `i` is a natural number (like `tactic.get_unused_name`). If `ns` is empty,
it returns an arbitrary name.
For example, assume we operate in the following context:
```
n n_1: ℕ
```
Then we have
```
get_unused_name_reserved [`n, `m, `list, `o] {m} = `o
```
since `n occurs in the context, `m is reserved, `list occurs in the environment
but `o is unused. We also have
```
get_unused_name_reserved [`n, `m, `list] {m} = `n_2
```
since all of the names from the list are taken and `n_2` is the first unused
variation of `n`.
-/
meta def get_unused_name_reserved (ns : list name) (reserved : name_set) :
tactic name := do
let fallback := match ns with | [] := `x | x :: _ := x end,
(first $ ns.map $ λ n, do {
guard (¬ reserved.contains n),
fail_if_success (resolve_name n),
pure n
})
<|>
get_unused_name_reserved_aux fallback reserved none
/--
`intro_fresh_reserved ns reserved` introduces a hypothesis. The hypothesis
receives a fresh name from `ns`, excluding the names in `reserved`. `ns` must be
nonempty. See `tactic.get_unused_name_reserved` for the full algorithm.
-/
meta def intro_fresh_reserved (ns : list name) (reserved : name_set) :
tactic expr :=
get_unused_name_reserved ns reserved >>= intro
/--
`intro_lst_fresh_reserved ns reserved` introduces one hypothesis for every
element of `ns`. If the element is `sum.inl n`, the hypothesis receives the name
`n` (which may or may not be fresh). If the element is `sum.inr ns'`, the
hypothesis receives a fresh name from `ns`, excluding the names in `reserved`.
`ns` must be nonempty. See `tactic.get_unused_name_reserved` for the full
algorithm.
Note that the
order of introductions matters:
`intro_lst_fresh_reserved [sum.inr [`n], sum.inr [`n]]` will introduce
hypotheses `n` and `n_1` (assuming that these names are otherwise unused and not
reserved).
-/
meta def intro_lst_fresh_reserved (ns : list (name ⊕ list name))
(reserved : name_set) :
tactic (list expr) :=
ns.mmap $ λ spec,
match spec with
| sum.inl n := intro n
| sum.inr ns := intro_fresh_reserved ns reserved
end
/--
`rename_fresh renames reserved`, given a map `renames` which associates the
unique names of some hypotheses `hᵢ` with name lists `nsᵢ`, renames each `hᵢ` to
a fresh name from `nsᵢ`, excluding the names in `reserved`. The `nsᵢ` must be
nonempty. See `tactic.get_unused_name_reserved` for the full algorithm.
The hypotheses are renamed in context order, so hypotheses which occur earlier
in the context are renamed before hypotheses that occur later in the context.
This is important because earlier renamings may 'steal' names from later
renamings.
`rename_fresh` returns a list of pairs `(oᵢ, nᵢ)` where the `oᵢ` are hypotheses
from the context in which `rename_fresh` was called and the `nᵢ` are the
corresponding hypotheses from the new context created by `rename_fresh`. The
pairs are returned in context order. Note that the returned list may contain
hypotheses which do not appear in `renames` but had to be temporarily reverted
due to dependencies.
-/
meta def rename_fresh (renames : name_map (list name)) (reserved : name_set) :
tactic (list (expr × expr)) := do
(_, reverted) ← revert_name_set $ name_set.of_list $ renames.keys,
let renames := reverted.map $ λ h,
match renames.find h.local_uniq_name with
| none := sum.inl h.local_pp_name
| some new_names := sum.inr new_names
end,
let reserved := reserved.insert_list $ renames.filter_map sum.get_left,
new_hyps ← intro_lst_fresh_reserved renames reserved,
pure $ reverted.zip new_hyps
end tactic
|
e0e6524694430ae2a9e6be9b96355a6b909387a4 | e9dbaaae490bc072444e3021634bf73664003760 | /src/Problems/2004/IMO_2004_P5.lean | a993358f097a6cbc3d9ac88e64438760e6a7facd | [
"Apache-2.0"
] | permissive | liaofei1128/geometry | 566d8bfe095ce0c0113d36df90635306c60e975b | 3dd128e4eec8008764bb94e18b932f9ffd66e6b3 | refs/heads/master | 1,678,996,510,399 | 1,581,454,543,000 | 1,583,337,839,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 444 | lean | import Geo.Geo.Core
namespace Geo
open Angle Quadrilateral Seg
def IMO_2004_P5 : Prop :=
∀ (A B C D : Point),
convex ⟨A, B, C, D⟩ →
¬isBisector ⟨B, D⟩ ⟨A, B, C⟩ →
¬isBisector ⟨B, D⟩ ⟨C, D, A⟩ →
∀ (P : Point),
inside P (Quadrilateral.mk A B C D) →
uangle ⟨P, B, C⟩ = uangle ⟨D, B, A⟩ →
uangle ⟨P, D, C⟩ = uangle ⟨B, D, A⟩ →
cyclic ⟨A, B, C, D⟩ ↔ cong ⟨A, P⟩ ⟨C, P⟩
end Geo
|
b6473e4a29e3f2ddb627fcb35ca35254bf092022 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/discrete_quotient.lean | e1b31901b9b35e93db2f40d77ef5d9ae0f781697 | [
"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 | 12,946 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Calle Sönne, Adam Topaz
-/
import topology.separation
import topology.subset_properties
import topology.locally_constant.basic
/-!
# Discrete quotients of a topological space.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the type of discrete quotients of a topological space,
denoted `discrete_quotient X`. To avoid quantifying over types, we model such
quotients as setoids whose equivalence classes are clopen.
## Definitions
1. `discrete_quotient X` is the type of discrete quotients of `X`.
It is endowed with a coercion to `Type`, which is defined as the
quotient associated to the setoid in question, and each such quotient
is endowed with the discrete topology.
2. Given `S : discrete_quotient X`, the projection `X → S` is denoted
`S.proj`.
3. When `X` is compact and `S : discrete_quotient X`, the space `S` is
endowed with a `fintype` instance.
## Order structure
The type `discrete_quotient X` is endowed with an instance of a `semilattice_inf` with `order_top`.
The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`.
The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed
to a point. Given `h : A ≤ B`, the map `A → B` is `discrete_quotient.of_le h`.
Whenever `X` is a locally connected space, the type `discrete_quotient X` is also endowed with an
instance of a `order_bot`, where the bot element `⊥` is given by the `connectedComponentSetoid`,
i.e., `x ~ y` means that `x` and `y` belong to the same connected component. In particular, if `X`
is a discrete topological space, then `x ~ y` is equivalent (propositionally, not definitionally) to
`x = y`.
Given `f : C(X, Y)`, we define a predicate `discrete_quotient.le_comap f A B` for `A :
discrete_quotient X` and `B : discrete_quotient Y`, asserting that `f` descends to `A → B`. If
`cond : discrete_quotient.le_comap h A B`, the function `A → B` is obtained by
`discrete_quotient.map f cond`.
## Theorems
The two main results proved in this file are:
1. `discrete_quotient.eq_of_forall_proj_eq` which states that when `X` is compact, T₂, and totally
disconnected, any two elements of `X` are equal if their projections in `Q` agree for all
`Q : discrete_quotient X`.
2. `discrete_quotient.exists_of_compat` which states that when `X` is compact, then any
system of elements of `Q` as `Q : discrete_quotient X` varies, which is compatible with
respect to `discrete_quotient.of_le`, must arise from some element of `X`.
## Remarks
The constructions in this file will be used to show that any profinite space is a limit
of finite discrete spaces.
-/
open set function
variables {α X Y Z : Type*} [topological_space X] [topological_space Y]
[topological_space Z]
/-- The type of discrete quotients of a topological space. -/
@[ext]
structure discrete_quotient (X : Type*) [topological_space X] extends setoid X :=
(is_open_set_of_rel : ∀ x, is_open (set_of (to_setoid.rel x)))
namespace discrete_quotient
variables (S : discrete_quotient X)
/-- Construct a discrete quotient from a clopen set. -/
def of_clopen {A : set X} (h : is_clopen A) : discrete_quotient X :=
{ to_setoid := ⟨λ x y, x ∈ A ↔ y ∈ A, λ _, iff.rfl, λ _ _, iff.symm, λ _ _ _, iff.trans⟩,
is_open_set_of_rel := λ x,
by by_cases hx : x ∈ A; simp [setoid.rel, hx, h.1, h.2, ← compl_set_of] }
lemma refl : ∀ x, S.rel x x := S.refl'
lemma symm {x y : X} : S.rel x y → S.rel y x := S.symm'
lemma trans {x y z} : S.rel x y → S.rel y z → S.rel x z := S.trans'
/-- The setoid whose quotient yields the discrete quotient. -/
add_decl_doc to_setoid
instance : has_coe_to_sort (discrete_quotient X) Type* :=
⟨λ S, quotient S.to_setoid⟩
instance : topological_space S := quotient.topological_space
/-- The projection from `X` to the given discrete quotient. -/
def proj : X → S := quotient.mk'
lemma fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = set_of (S.rel x) :=
set.ext $ λ y, eq_comm.trans quotient.eq'
lemma proj_surjective : function.surjective S.proj := quotient.surjective_quotient_mk'
lemma proj_quotient_map : quotient_map S.proj := quotient_map_quot_mk
lemma proj_continuous : continuous S.proj := S.proj_quotient_map.continuous
instance : discrete_topology S :=
singletons_open_iff_discrete.1 $ S.proj_surjective.forall.2 $ λ x,
by { rw [← S.proj_quotient_map.is_open_preimage, fiber_eq], exact S.is_open_set_of_rel _ }
lemma proj_is_locally_constant : is_locally_constant S.proj :=
(is_locally_constant.iff_continuous S.proj).2 S.proj_continuous
lemma is_clopen_preimage (A : set S) : is_clopen (S.proj ⁻¹' A) :=
(is_clopen_discrete A).preimage S.proj_continuous
lemma is_open_preimage (A : set S) : is_open (S.proj ⁻¹' A) := (S.is_clopen_preimage A).1
lemma is_closed_preimage (A : set S) : is_closed (S.proj ⁻¹' A) := (S.is_clopen_preimage A).2
theorem is_clopen_set_of_rel (x : X) : is_clopen (set_of (S.rel x)) :=
by { rw [← fiber_eq], apply is_clopen_preimage }
instance : has_inf (discrete_quotient X) :=
⟨λ S₁ S₂, ⟨S₁.1 ⊓ S₂.1, λ x, (S₁.2 x).inter (S₂.2 x)⟩⟩
instance : semilattice_inf (discrete_quotient X) :=
injective.semilattice_inf to_setoid ext (λ _ _, rfl)
instance : order_top (discrete_quotient X) :=
{ top := ⟨⊤, λ _, is_open_univ⟩,
le_top := λ a, by tauto }
instance : inhabited (discrete_quotient X) := ⟨⊤⟩
instance inhabited_quotient [inhabited X] : inhabited S := ⟨S.proj default⟩
instance [nonempty X] : nonempty S := nonempty.map S.proj ‹_›
section comap
variables (g : C(Y, Z)) (f : C(X, Y))
/-- Comap a discrete quotient along a continuous map. -/
def comap (S : discrete_quotient Y) : discrete_quotient X :=
{ to_setoid := setoid.comap f S.1,
is_open_set_of_rel := λ y, (S.2 _).preimage f.continuous }
@[simp]
lemma comap_id : S.comap (continuous_map.id X) = S := by { ext, refl }
@[simp]
lemma comap_comp (S : discrete_quotient Z) : S.comap (g.comp f) = (S.comap g).comap f := rfl
@[mono]
lemma comap_mono {A B : discrete_quotient Y} (h : A ≤ B) : A.comap f ≤ B.comap f :=
by tauto
end comap
section of_le
variables {A B C : discrete_quotient X}
/-- The map induced by a refinement of a discrete quotient. -/
def of_le (h : A ≤ B) : A → B := quotient.map' (λ x, x) h
@[simp] lemma of_le_refl : of_le (le_refl A) = id := by { ext ⟨⟩, refl }
lemma of_le_refl_apply (a : A) : of_le (le_refl A) a = a := by simp
@[simp] lemma of_le_of_le (h₁ : A ≤ B) (h₂ : B ≤ C) (x : A) :
of_le h₂ (of_le h₁ x) = of_le (h₁.trans h₂) x := by { rcases x with ⟨⟩, refl }
@[simp] lemma of_le_comp_of_le (h₁ : A ≤ B) (h₂ : B ≤ C) :
of_le h₂ ∘ of_le h₁ = of_le (le_trans h₁ h₂) :=
funext $ of_le_of_le _ _
lemma of_le_continuous (h : A ≤ B) : continuous (of_le h) :=
continuous_of_discrete_topology
@[simp] lemma of_le_proj (h : A ≤ B) (x : X) : of_le h (A.proj x) = B.proj x :=
quotient.sound' (B.refl _)
@[simp] lemma of_le_comp_proj (h : A ≤ B) : of_le h ∘ A.proj = B.proj :=
funext $ of_le_proj _
end of_le
/-- When `X` is a locally connected space, there is an `order_bot` instance on
`discrete_quotient X`. The bottom element is given by `connected_component_setoid X`
-/
instance [locally_connected_space X] : order_bot (discrete_quotient X) :=
{ bot :=
{ to_setoid := connected_component_setoid X,
is_open_set_of_rel := λ x,
begin
have : connected_component x = {y | (connected_component_setoid X).rel x y},
{ ext y,
simpa only [connected_component_setoid, ← connected_component_eq_iff_mem] using eq_comm },
rw [← this],
exact is_open_connected_component
end },
bot_le := λ S x y (h : connected_component x = connected_component y),
(S.is_clopen_set_of_rel x).connected_component_subset (S.refl _) $
h.symm ▸ mem_connected_component }
@[simp] theorem proj_bot_eq [locally_connected_space X] {x y : X} :
proj ⊥ x = proj ⊥ y ↔ connected_component x = connected_component y :=
quotient.eq'
theorem proj_bot_inj [discrete_topology X] {x y : X} :
proj ⊥ x = proj ⊥ y ↔ x = y := by simp
theorem proj_bot_injective [discrete_topology X] :
injective (⊥ : discrete_quotient X).proj := λ _ _, proj_bot_inj.1
theorem proj_bot_bijective [discrete_topology X] :
bijective (⊥ : discrete_quotient X).proj :=
⟨proj_bot_injective, proj_surjective _⟩
section map
variables (f : C(X, Y)) (A A' : discrete_quotient X) (B B' : discrete_quotient Y)
/-- Given `f : C(X, Y)`, `le_comap cont A B` is defined as `A ≤ B.comap f`. Mathematically this
means that `f` descends to a morphism `A → B`. -/
def le_comap : Prop := A ≤ B.comap f
theorem le_comap_id : le_comap (continuous_map.id X) A A := λ _ _, id
variables {A A' B B'} {f} {g : C(Y, Z)} {C : discrete_quotient Z}
@[simp] theorem le_comap_id_iff : le_comap (continuous_map.id X) A A' ↔ A ≤ A' := iff.rfl
theorem le_comap.comp :
le_comap g B C → le_comap f A B → le_comap (g.comp f) A C := by tauto
theorem le_comap.mono (h : le_comap f A B) (hA : A' ≤ A) (hB : B ≤ B') : le_comap f A' B' :=
hA.trans $ le_trans h $ comap_mono _ hB
/-- Map a discrete quotient along a continuous map. -/
def map (f : C(X, Y)) (cond : le_comap f A B) : A → B := quotient.map' f cond
theorem map_continuous (cond : le_comap f A B) : continuous (map f cond) :=
continuous_of_discrete_topology
@[simp] theorem map_comp_proj (cond : le_comap f A B) : map f cond ∘ A.proj = B.proj ∘ f := rfl
@[simp]
theorem map_proj (cond : le_comap f A B) (x : X) : map f cond (A.proj x) = B.proj (f x) := rfl
@[simp] theorem map_id : map _ (le_comap_id A) = id := by ext ⟨⟩; refl
@[simp] theorem map_comp (h1 : le_comap g B C) (h2 : le_comap f A B) :
map (g.comp f) (h1.comp h2) = map g h1 ∘ map f h2 :=
by { ext ⟨⟩, refl }
@[simp] theorem of_le_map (cond : le_comap f A B) (h : B ≤ B') (a : A) :
of_le h (map f cond a) = map f (cond.mono le_rfl h) a :=
by { rcases a with ⟨⟩, refl }
@[simp] theorem of_le_comp_map (cond : le_comap f A B) (h : B ≤ B') :
of_le h ∘ map f cond = map f (cond.mono le_rfl h) :=
funext $ of_le_map cond h
@[simp] theorem map_of_le (cond : le_comap f A B) (h : A' ≤ A) (c : A') :
map f cond (of_le h c) = map f (cond.mono h le_rfl) c :=
by { rcases c with ⟨⟩, refl }
@[simp] theorem map_comp_of_le (cond : le_comap f A B) (h : A' ≤ A) :
map f cond ∘ of_le h = map f (cond.mono h le_rfl) :=
funext $ map_of_le cond h
end map
lemma eq_of_forall_proj_eq [t2_space X] [compact_space X] [disc : totally_disconnected_space X]
{x y : X} (h : ∀ Q : discrete_quotient X, Q.proj x = Q.proj y) : x = y :=
begin
rw [← mem_singleton_iff, ← connected_component_eq_singleton, connected_component_eq_Inter_clopen,
mem_Inter],
rintro ⟨U, hU1, hU2⟩,
exact (quotient.exact' (h (of_clopen hU1))).mpr hU2
end
lemma fiber_subset_of_le {A B : discrete_quotient X} (h : A ≤ B) (a : A) :
A.proj ⁻¹' {a} ⊆ B.proj ⁻¹' {of_le h a} :=
begin
rcases A.proj_surjective a with ⟨a, rfl⟩,
rw [fiber_eq, of_le_proj, fiber_eq],
exact λ _ h', h h'
end
lemma exists_of_compat [compact_space X] (Qs : Π (Q : discrete_quotient X), Q)
(compat : ∀ (A B : discrete_quotient X) (h : A ≤ B), of_le h (Qs _) = Qs _) :
∃ x : X, ∀ Q : discrete_quotient X, Q.proj x = Qs _ :=
begin
obtain ⟨x,hx⟩ : (⋂ Q, proj Q ⁻¹' {Qs Q}).nonempty :=
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
(λ (Q : discrete_quotient X), Q.proj ⁻¹' {Qs _}) (directed_of_inf $ λ A B h, _)
(λ Q, (singleton_nonempty _).preimage Q.proj_surjective)
(λ i, (is_closed_preimage _ _).is_compact) (λ i, is_closed_preimage _ _),
{ refine ⟨x, λ Q, _⟩,
exact hx _ ⟨Q,rfl⟩ },
{ rw [← compat _ _ h],
exact fiber_subset_of_le _ _ },
end
instance [compact_space X] : finite S :=
begin
have : compact_space S := quotient.compact_space,
rwa [← is_compact_univ_iff, is_compact_iff_finite, finite_univ_iff] at this
end
end discrete_quotient
namespace locally_constant
variables {X} (f : locally_constant X α)
/-- Any locally constant function induces a discrete quotient. -/
def discrete_quotient : discrete_quotient X :=
{ to_setoid := setoid.comap f ⊥,
is_open_set_of_rel := λ x, f.is_locally_constant _ }
/-- The (locally constant) function from the discrete quotient associated to a locally constant
function. -/
def lift : locally_constant f.discrete_quotient α :=
⟨λ a, quotient.lift_on' a f (λ a b, id), λ A, is_open_discrete _⟩
@[simp] lemma lift_comp_proj : f.lift ∘ f.discrete_quotient.proj = f := by { ext, refl }
end locally_constant
|
fdca4a4dc8c308e81b3227b38381581cdd5006c8 | a339bc2ac96174381fb610f4b2e1ba42df2be819 | /hott/algebra/group_theory.hlean | 6e4f5eb2d3180430b816a57b86b38a2bad025528 | [
"Apache-2.0"
] | permissive | kalfsvag/lean2 | 25b2dccc07a98e5aa20f9a11229831f9d3edf2e7 | 4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7 | refs/heads/master | 1,610,513,122,164 | 1,483,135,198,000 | 1,483,135,198,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,375 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Basic group theory
This file will be rewritten in the future, when we develop are more systematic notation for
describing homomorphisms
-/
import algebra.category.category algebra.bundled
open eq algebra pointed function is_trunc pi equiv is_equiv
set_option class.force_new true
namespace group
definition pointed_Group [instance] [constructor] (G : Group) : pointed G :=
pointed.mk 1
definition Group.struct' [instance] [reducible] (G : Group) : group G :=
Group.struct G
definition ab_group_Group_of_AbGroup [instance] [constructor] [priority 900]
(G : AbGroup) : ab_group (Group_of_AbGroup G) :=
begin esimp, exact _ end
definition ab_group_pSet_of_Group [instance] (G : AbGroup) : ab_group (pSet_of_Group G) :=
AbGroup.struct G
definition group_pSet_of_Group [instance] [priority 900] (G : Group) :
group (pSet_of_Group G) :=
Group.struct G
/- group homomorphisms -/
definition is_homomorphism [class] [reducible]
{G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g * h) = φ g * φ h
section
variables {G G₁ G₂ G₃ : Type} {g h : G₁} (ψ : G₂ → G₃) {φ₁ φ₂ : G₁ → G₂} (φ : G₁ → G₂)
[group G] [group G₁] [group G₂] [group G₃]
[is_homomorphism ψ] [is_homomorphism φ₁] [is_homomorphism φ₂] [is_homomorphism φ]
definition respect_mul {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂)
[is_homomorphism φ] : Π(g h : G₁), φ (g * h) = φ g * φ h :=
by assumption
theorem respect_one /- φ -/ : φ 1 = 1 :=
mul.right_cancel
(calc
φ 1 * φ 1 = φ (1 * 1) : respect_mul φ
... = φ 1 : ap φ !one_mul
... = 1 * φ 1 : one_mul)
theorem respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
eq_inv_of_mul_eq_one (!respect_mul⁻¹ ⬝ ap φ !mul.left_inv ⬝ !respect_one)
definition is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
begin
apply function.is_embedding_of_is_injective,
intro g g' p,
apply eq_of_mul_inv_eq_one,
apply H,
refine !respect_mul ⬝ _,
rewrite [respect_inv φ, p],
apply mul.right_inv
end
definition is_homomorphism_compose {ψ : G₂ → G₃} {φ : G₁ → G₂}
(H1 : is_homomorphism ψ) (H2 : is_homomorphism φ) : is_homomorphism (ψ ∘ φ) :=
λg h, ap ψ !respect_mul ⬝ !respect_mul
definition is_homomorphism_id (G : Type) [group G] : is_homomorphism (@id G) :=
λg h, idp
end
section additive
definition is_add_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_add G₁] [has_add G₂]
(φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g + h) = φ g + φ h
variables {G₁ G₂ : Type} (φ : G₁ → G₂) [add_group G₁] [add_group G₂] [is_add_homomorphism φ]
definition respect_add /- φ -/ : Π(g h : G₁), φ (g + h) = φ g + φ h :=
by assumption
theorem respect_zero /- φ -/ : φ 0 = 0 :=
add.right_cancel
(calc
φ 0 + φ 0 = φ (0 + 0) : respect_add φ
... = φ 0 : ap φ !zero_add
... = 0 + φ 0 : zero_add)
theorem respect_neg /- φ -/ (g : G₁) : φ (-g) = -(φ g) :=
eq_neg_of_add_eq_zero (!respect_add⁻¹ ⬝ ap φ !add.left_inv ⬝ !respect_zero)
end additive
structure homomorphism (G₁ G₂ : Group) : Type :=
(φ : G₁ → G₂)
(p : is_homomorphism φ)
infix ` →g `:55 := homomorphism
definition group_fun [unfold 3] [coercion] := @homomorphism.φ
definition homomorphism.struct [unfold 3] [instance] [priority 900] {G₁ G₂ : Group}
(φ : G₁ →g G₂) : is_homomorphism φ :=
homomorphism.p φ
definition homomorphism.mulstruct [instance] [priority 2000] {G₁ G₂ : Group} (φ : G₁ →g G₂)
: is_homomorphism φ :=
homomorphism.p φ
definition homomorphism.addstruct [instance] [priority 2000] {G₁ G₂ : AddGroup} (φ : G₁ →g G₂)
: is_add_homomorphism φ :=
homomorphism.p φ
variables {G G₁ G₂ G₃ : Group} {g h : G₁} {ψ : G₂ →g G₃} {φ₁ φ₂ : G₁ →g G₂} (φ : G₁ →g G₂)
definition to_respect_mul /- φ -/ (g h : G₁) : φ (g * h) = φ g * φ h :=
respect_mul φ g h
theorem to_respect_one /- φ -/ : φ 1 = 1 :=
respect_one φ
theorem to_respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
respect_inv φ g
definition to_is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
is_embedding_homomorphism φ @H
variables (G₁ G₂)
definition is_set_homomorphism [instance] : is_set (G₁ →g G₂) :=
begin
have H : G₁ →g G₂ ≃ Σ(f : G₁ → G₂), Π(g₁ g₂ : G₁), f (g₁ * g₂) = f g₁ * f g₂,
begin
fapply equiv.MK,
{ intro φ, induction φ, constructor, assumption},
{ intro v, induction v, constructor, assumption},
{ intro v, induction v, reflexivity},
{ intro φ, induction φ, reflexivity}
end,
apply is_trunc_equiv_closed_rev, exact H
end
variables {G₁ G₂}
definition pmap_of_homomorphism [constructor] /- φ -/ : G₁ →* G₂ :=
pmap.mk φ begin esimp, exact respect_one φ end
definition homomorphism_change_fun [constructor] {G₁ G₂ : Group}
(φ : G₁ →g G₂) (f : G₁ → G₂) (p : φ ~ f) : G₁ →g G₂ :=
homomorphism.mk f (λg h, (p (g * h))⁻¹ ⬝ to_respect_mul φ g h ⬝ ap011 mul (p g) (p h))
definition homomorphism_eq (p : group_fun φ₁ ~ group_fun φ₂) : φ₁ = φ₂ :=
begin
induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p,
exact ap (homomorphism.mk φ₁) !is_prop.elim
end
section additive
variables {H₁ H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_add /- χ -/ (g h : H₁) : χ (g + h) = χ g + χ h :=
respect_add χ g h
theorem to_respect_zero /- χ -/ : χ 0 = 0 :=
respect_zero χ
theorem to_respect_neg /- χ -/ (g : H₁) : χ (-g) = -(χ g) :=
respect_neg χ g
end additive
section add_mul
variables {H₁ : AddGroup} {H₂ : Group} (χ : H₁ →g H₂)
definition to_respect_add_mul /- χ -/ (g h : H₁) : χ (g + h) = χ g * χ h :=
to_respect_mul χ g h
theorem to_respect_zero_one /- χ -/ : χ 0 = 1 :=
to_respect_one χ
theorem to_respect_neg_inv /- χ -/ (g : H₁) : χ (-g) = (χ g)⁻¹ :=
to_respect_inv χ g
end add_mul
section mul_add
variables {H₁ : Group} {H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_mul_add /- χ -/ (g h : H₁) : χ (g * h) = χ g + χ h :=
to_respect_mul χ g h
theorem to_respect_one_zero /- χ -/ : χ 1 = 0 :=
to_respect_one χ
theorem to_respect_inv_neg /- χ -/ (g : H₁) : χ g⁻¹ = -(χ g) :=
to_respect_inv χ g
end mul_add
/- categorical structure of groups + homomorphisms -/
definition homomorphism_compose [constructor] [trans] (ψ : G₂ →g G₃) (φ : G₁ →g G₂) : G₁ →g G₃ :=
homomorphism.mk (ψ ∘ φ) (is_homomorphism_compose _ _)
variable (G)
definition homomorphism_id [constructor] [refl] : G →g G :=
homomorphism.mk (@id G) (is_homomorphism_id G)
variable {G}
abbreviation gid [constructor] := @homomorphism_id
infixr ` ∘g `:75 := homomorphism_compose
notation 1 := homomorphism_id _
structure isomorphism (A B : Group) :=
(to_hom : A →g B)
(is_equiv_to_hom : is_equiv to_hom)
infix ` ≃g `:25 := isomorphism
attribute isomorphism.to_hom [coercion]
attribute isomorphism.is_equiv_to_hom [instance]
attribute isomorphism._trans_of_to_hom [unfold 3]
definition equiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃ G₂ :=
equiv.mk φ _
definition pequiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) :
G₁ ≃* G₂ :=
pequiv.mk φ begin esimp, exact _ end begin esimp, exact respect_one φ end
definition isomorphism_of_equiv [constructor] (φ : G₁ ≃ G₂)
(p : Πg₁ g₂, φ (g₁ * g₂) = φ g₁ * φ g₂) : G₁ ≃g G₂ :=
isomorphism.mk (homomorphism.mk φ p) !to_is_equiv
definition isomorphism_of_eq [constructor] {G₁ G₂ : Group} (φ : G₁ = G₂) : G₁ ≃g G₂ :=
isomorphism_of_equiv (equiv_of_eq (ap Group.carrier φ))
begin intros, induction φ, reflexivity end
definition pequiv_of_isomorphism_of_eq {G₁ G₂ : Group} (p : G₁ = G₂) :
pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_Group p) :=
begin
induction p,
apply pequiv_eq,
fapply pmap_eq,
{ intro g, reflexivity},
{ apply is_prop.elim}
end
definition to_ginv [constructor] (φ : G₁ ≃g G₂) : G₂ →g G₁ :=
homomorphism.mk φ⁻¹
abstract begin
intro g₁ g₂, apply eq_of_fn_eq_fn' φ,
rewrite [respect_mul φ, +right_inv φ]
end end
variable (G)
definition isomorphism.refl [refl] [constructor] : G ≃g G :=
isomorphism.mk 1 !is_equiv_id
variable {G}
definition isomorphism.symm [symm] [constructor] (φ : G₁ ≃g G₂) : G₂ ≃g G₁ :=
isomorphism.mk (to_ginv φ) !is_equiv_inv
definition isomorphism.trans [trans] [constructor] (φ : G₁ ≃g G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
isomorphism.mk (ψ ∘g φ) !is_equiv_compose
definition isomorphism.eq_trans [trans] [constructor]
{G₁ G₂ : Group} {G₃ : Group} (φ : G₁ = G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
proof isomorphism.trans (isomorphism_of_eq φ) ψ qed
definition isomorphism.trans_eq [trans] [constructor]
{G₁ : Group} {G₂ G₃ : Group} (φ : G₁ ≃g G₂) (ψ : G₂ = G₃) : G₁ ≃g G₃ :=
isomorphism.trans φ (isomorphism_of_eq ψ)
postfix `⁻¹ᵍ`:(max + 1) := isomorphism.symm
infixl ` ⬝g `:75 := isomorphism.trans
infixl ` ⬝gp `:75 := isomorphism.trans_eq
infixl ` ⬝pg `:75 := isomorphism.eq_trans
definition pmap_of_isomorphism [constructor] (φ : G₁ ≃g G₂) :
G₁ →* G₂ :=
pequiv_of_isomorphism φ
/- category of groups -/
section
open category
definition precategory_group [constructor] : precategory Group :=
precategory.mk homomorphism
@homomorphism_compose
@homomorphism_id
(λG₁ G₂ G₃ G₄ φ₃ φ₂ φ₁, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
end
-- TODO
-- definition category_group : category Group :=
-- category.mk precategory_group
-- begin
-- intro G₁ G₂,
-- fapply adjointify,
-- { intro φ, fapply Group_eq, },
-- { },
-- { }
-- end
/- given an equivalence A ≃ B we can transport a group structure on A to a group structure on B -/
section
parameters {A B : Type} (f : A ≃ B) [group A]
definition group_equiv_mul (b b' : B) : B := f (f⁻¹ᶠ b * f⁻¹ᶠ b')
definition group_equiv_one : B := f one
definition group_equiv_inv (b : B) : B := f (f⁻¹ᶠ b)⁻¹
local infix * := group_equiv_mul
local postfix ^ := group_equiv_inv
local notation 1 := group_equiv_one
theorem group_equiv_mul_assoc (b₁ b₂ b₃ : B) : (b₁ * b₂) * b₃ = b₁ * (b₂ * b₃) :=
by rewrite [↑group_equiv_mul, +left_inv f, mul.assoc]
theorem group_equiv_one_mul (b : B) : 1 * b = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, one_mul, right_inv f]
theorem group_equiv_mul_one (b : B) : b * 1 = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, mul_one, right_inv f]
theorem group_equiv_mul_left_inv (b : B) : b^ * b = 1 :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, ↑group_equiv_inv,
+left_inv f, mul.left_inv]
definition group_equiv_closed : group B :=
⦃group,
mul := group_equiv_mul,
mul_assoc := group_equiv_mul_assoc,
one := group_equiv_one,
one_mul := group_equiv_one_mul,
mul_one := group_equiv_mul_one,
inv := group_equiv_inv,
mul_left_inv := group_equiv_mul_left_inv,
is_set_carrier := is_trunc_equiv_closed 0 f⦄
end
variable (G)
/- the trivial group -/
open unit
definition trivial_group [constructor] : group unit :=
group.mk (λx y, star) _ (λx y z, idp) star (unit.rec idp) (unit.rec idp) (λx, star) (λx, idp)
definition Trivial_group [constructor] : Group :=
Group.mk _ trivial_group
abbreviation G0 := Trivial_group
definition trivial_group_of_is_contr [H : is_contr G] : G ≃g G0 :=
begin
fapply isomorphism_of_equiv,
{ apply equiv_unit_of_is_contr},
{ intros, reflexivity}
end
variable {G}
/-
A group where the point in the pointed type corresponds with 1 in the group.
We need this structure when we are given a pointed type, and want to say that there is a group
structure on it which is compatible with the point. This is used in chain complexes.
-/
structure pgroup [class] (X : Type*) extends semigroup X, has_inv X :=
(pt_mul : Πa, mul pt a = a)
(mul_pt : Πa, mul a pt = a)
(mul_left_inv_pt : Πa, mul (inv a) a = pt)
definition group_of_pgroup [reducible] [instance] (X : Type*) [H : pgroup X]
: group X :=
⦃group, H,
one := pt,
one_mul := pgroup.pt_mul ,
mul_one := pgroup.mul_pt,
mul_left_inv := pgroup.mul_left_inv_pt⦄
definition pgroup_of_group (X : Type*) [H : group X] (p : one = pt :> X) : pgroup X :=
begin
cases X with X x, esimp at *, induction p,
exact ⦃pgroup, H,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv⦄
end
definition Group_of_pgroup (G : Type*) [pgroup G] : Group :=
Group.mk G _
definition pgroup_Group [instance] (G : Group) : pgroup G :=
⦃ pgroup, Group.struct G,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv ⦄
/- equality of groups and abelian groups -/
definition group.to_has_mul {A : Type} (H : group A) : has_mul A := _
definition group.to_has_inv {A : Type} (H : group A) : has_inv A := _
definition group.to_has_one {A : Type} (H : group A) : has_one A := _
local attribute group.to_has_mul group.to_has_inv [coercion]
universe variable l
variables {A B : Type.{l}}
definition group_eq {G H : group A} (same_mul' : Π(g h : A), @mul A G g h = @mul A H g h)
: G = H :=
begin
have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g,
from λg, !mul_inv_cancel_right⁻¹,
cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4,
cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4,
rewrite [↑[semigroup.to_has_mul,group.to_has_inv] at (same_mul',foo)],
have same_mul : Gm = Hm, from eq_of_homotopy2 same_mul',
cases same_mul,
have same_one : G1 = H1, from calc
G1 = Hm G1 H1 : Hh3
... = H1 : Gh2,
have same_inv : Gi = Hi, from eq_of_homotopy (take g, calc
Gi g = Hm (Hm (Gi g) g) (Hi g) : foo
... = Hm G1 (Hi g) : by rewrite Gh4
... = Hi g : Gh2),
cases same_one, cases same_inv,
have ps : Gs = Hs, from !is_prop.elim,
have ph1 : Gh1 = Hh1, from !is_prop.elim,
have ph2 : Gh2 = Hh2, from !is_prop.elim,
have ph3 : Gh3 = Hh3, from !is_prop.elim,
have ph4 : Gh4 = Hh4, from !is_prop.elim,
cases ps, cases ph1, cases ph2, cases ph3, cases ph4, reflexivity
end
definition group_pathover {G : group A} {H : group B} {p : A = B}
(resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H :=
begin
induction p,
apply pathover_idp_of_eq, exact group_eq (resp_mul)
end
definition Group_eq_of_eq {G H : Group} (p : Group.carrier G = Group.carrier H)
(resp_mul : Π(g h : G), cast p (g * h) = cast p g * cast p h) : G = H :=
begin
cases G with Gc G, cases H with Hc H,
apply (apd011 Group.mk p),
exact group_pathover resp_mul
end
definition Group_eq {G H : Group} (f : Group.carrier G ≃ Group.carrier H)
(resp_mul : Π(g h : G), f (g * h) = f g * f h) : G = H :=
Group_eq_of_eq (ua f) (λg h, !cast_ua ⬝ resp_mul g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹)
definition eq_of_isomorphism {G₁ G₂ : Group} (φ : G₁ ≃g G₂) : G₁ = G₂ :=
Group_eq (equiv_of_isomorphism φ) (respect_mul φ)
definition ab_group.to_has_mul {A : Type} (H : ab_group A) : has_mul A := _
local attribute ab_group.to_has_mul [coercion]
definition ab_group_eq {A : Type} {G H : ab_group A}
(same_mul : Π(g h : A), @mul A G g h = @mul A H g h)
: G = H :=
begin
have g_eq : @ab_group.to_group A G = @ab_group.to_group A H, from group_eq same_mul,
cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4 Gh5,
cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4 Hh5,
have pm : Gm = Hm, from ap (@mul _ ∘ group.to_has_mul) g_eq,
have pi : Gi = Hi, from ap (@inv _ ∘ group.to_has_inv) g_eq,
have p1 : G1 = H1, from ap (@one _ ∘ group.to_has_one) g_eq,
induction pm, induction pi, induction p1,
have ps : Gs = Hs, from !is_prop.elim,
have ph1 : Gh1 = Hh1, from !is_prop.elim,
have ph2 : Gh2 = Hh2, from !is_prop.elim,
have ph3 : Gh3 = Hh3, from !is_prop.elim,
have ph4 : Gh4 = Hh4, from !is_prop.elim,
have ph5 : Gh5 = Hh5, from !is_prop.elim,
induction ps, induction ph1, induction ph2, induction ph3, induction ph4, induction ph5,
reflexivity
end
definition ab_group_pathover {A B : Type} {G : ab_group A} {H : ab_group B} {p : A = B}
(resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H :=
begin
induction p,
apply pathover_idp_of_eq, exact ab_group_eq (resp_mul)
end
definition AbGroup_eq_of_isomorphism {G₁ G₂ : AbGroup} (φ : G₁ ≃g G₂) : G₁ = G₂ :=
begin
induction G₁, induction G₂,
apply apd011 AbGroup.mk (ua (equiv_of_isomorphism φ)),
apply ab_group_pathover,
intro g h, exact !cast_ua ⬝ respect_mul φ g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹
end
definition trivial_group_of_is_contr' (G : Group) [H : is_contr G] : G = G0 :=
eq_of_isomorphism (trivial_group_of_is_contr G)
end group
|
d1f834739b26c7b0e6fa8cecd33c4e0b521803fd | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/1723.lean | ad962fc91b6ea78d301ae6424face858314e2712 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 170 | lean | #reduce int.shiftl (-1) (-1)
#eval int.shiftl (-1) (-1)
#reduce int.shiftl (-4) (-2)
#eval int.shiftl (-4) (-2)
#reduce int.shiftl (-5) (-2)
#eval int.shiftl (-5) (-2)
|
3de427eecfba73ae81ce6218b0533f0c9343b028 | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/Util/Trace.lean | dcaed0cd86015494a0f04e48272f5812658cb606 | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,707 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Message
import Lean.MonadEnv
universe u
namespace Lean
open Std (PersistentArray)
structure TraceElem where
ref : Syntax
msg : MessageData
deriving Inhabited
structure TraceState where
enabled : Bool := true
traces : PersistentArray TraceElem := {}
deriving Inhabited
namespace TraceState
private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format :=
traces.size.foldM
(fun i r => do
let curr ← (traces.get! i).msg.format
pure $ if i > 0 then r ++ sep ++ curr else r ++ curr)
Format.nil
end TraceState
class MonadTrace (m : Type → Type) where
modifyTraceState : (TraceState → TraceState) → m Unit
getTraceState : m TraceState
export MonadTrace (getTraceState modifyTraceState)
instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where
modifyTraceState := fun f => liftM (modifyTraceState f : m _)
getTraceState := liftM (getTraceState : m _)
variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m]
def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do
let traceState ← getTraceState
traceState.traces.forM fun m => do
let d ← m.msg.format
IO.println d
def resetTraceState {m} [MonadTrace m] : m Unit :=
modifyTraceState (fun _ => {})
private def checkTraceOptionAux (opts : Options) : Name → Bool
| n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p)
| _ => false
def checkTraceOption (opts : Options) (cls : Name) : Bool :=
if opts.isEmpty then false
else checkTraceOptionAux opts (`trace ++ cls)
private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do
let opts ← getOptions
pure $ checkTraceOption opts cls
@[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do
let s ← getTraceState
if !s.enabled then pure false
else checkTraceOptionM cls
@[inline] def enableTracing (b : Bool) : m Bool := do
let s ← getTraceState
let oldEnabled := s.enabled
modifyTraceState fun s => { s with enabled := b }
pure oldEnabled
@[inline] def getTraces : m (PersistentArray TraceElem) := do
let s ← getTraceState
pure s.traces
@[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit :=
modifyTraceState fun s => { s with traces := f s.traces }
@[inline] def setTraceState (s : TraceState) : m Unit :=
modifyTraceState fun _ => s
private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit :=
modifyTraces fun traces =>
if traces.isEmpty then
oldTraces
else
let d := MessageData.tagged cls m!"[{cls}] {MessageData.node (traces.toArray.map fun elem => elem.msg)}"
oldTraces.push { ref := ref, msg := d }
private def getResetTraces : m (PersistentArray TraceElem) := do
let oldTraces ← getTraces
modifyTraces fun _ => {}
pure oldTraces
section
variable [MonadRef m] [AddMessageContext m] [MonadOptions m]
def addTrace (cls : Name) (msg : MessageData) : m Unit := do
let ref ← getRef
let msg ← addMessageContext msg
let msg := addTraceOptions msg
modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls m!"[{cls}] {msg}" }
where
addTraceOptions : MessageData → MessageData
| MessageData.withContext ctx msg => MessageData.withContext { ctx with opts := ctx.opts.setBool `pp.analyze false } msg
| msg => msg
@[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
addTrace cls (msg ())
@[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
let msg ← mkMsg
addTrace cls msg
@[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do
let b ← isTracingEnabledFor cls
if !b then
let old ← enableTracing false
try ctx finally enableTracing old
else
let ref ← getRef
let oldCurrTraces ← getResetTraces
try ctx finally addNode oldCurrTraces cls ref
-- TODO: delete after fix old frontend
def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit :=
Lean.trace cls msg
end
def registerTraceClass (traceClassName : Name) : IO Unit :=
registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" }
macro "trace[" id:ident "]" s:(interpolatedStr(term) <|> term) : doElem => do
let msg ← if s.getKind == interpolatedStrKind then `(m! $s) else `(($s : MessageData))
`(doElem| do
let cls := $(quote id.getId)
if (← Lean.isTracingEnabledFor cls) then
Lean.addTrace cls $msg)
private def withNestedTracesFinalizer [Monad m] [MonadTrace m] (ref : Syntax) (currTraces : PersistentArray TraceElem) : m Unit := do
modifyTraces fun traces =>
if traces.size == 0 then
currTraces
else if traces.size == 1 && traces[0].msg.isNest then
currTraces ++ traces -- No nest of nest
else
let d := traces.foldl (init := MessageData.nil) fun d elem =>
if d.isNil then elem.msg else m!"{d}\n{elem.msg}"
currTraces.push { ref := ref, msg := MessageData.nestD d }
@[inline] def withNestedTraces [Monad m] [MonadFinally m] [MonadTrace m] [MonadRef m] (x : m α) : m α := do
let currTraces ← getTraces
modifyTraces fun _ => {}
let ref ← getRef
try x finally withNestedTracesFinalizer ref currTraces
end Lean
|
44be522dd81f9ce8a45e53a92607f9b40638e434 | e5c11e5a7d990ce404047c2bd848eeafac3c0a85 | /src/admissible_absolute_value.lean | 75d486da86f728167d4cbefe1963fc5967ea947b | [
"LPPL-1.3c"
] | permissive | lean-forward/class-number | 9ec63c24845e46efc8fa8b15324d0815918292c7 | 4fccf36d5e0e16accae84c16df77a3839ad964e4 | refs/heads/main | 1,686,927,014,542 | 1,624,886,724,000 | 1,624,886,724,000 | 327,319,245 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,283 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen
-/
import analysis.special_functions.pow
import algebraic_number_theory.class_number.euclidean_absolute_value
import algebraic_number_theory.class_number.finset
import combinatorics.pigeonhole
import field_theory.finite.basic
/-!
# Admissible absolute values
This file defines a structure `admissible_absolute_value` which we use to show the class number
of the ring of integers of a global field is finite.
-/
section admissible
variables {R : Type*} [euclidean_domain R]
/-- An `admissible_absolute_value R` is a Euclidean absolute value `R → ℤ`,
such that a large enough set of elements in `R^n` will contain a pair of elements
whose remainders are pointwise close together. -/
structure admissible_absolute_value (R : Type*) [euclidean_domain R]
extends euclidean_absolute_value R ℤ :=
(card : ℝ → ℕ)
(exists_partition' : ∀ (n : ℕ) {ε : ℝ} (hε : 0 < ε) (b : R) (hb : b ≠ 0) (A : fin n → R),
∃ (t : fin n → fin (card ε)),
∀ i₀ i₁, t i₀ = t i₁ → (to_fun (A i₁ % b - A i₀ % b) : ℝ) < to_fun b • ε)
variables (abs : admissible_absolute_value R)
namespace admissible_absolute_value
instance : has_coe_to_fun (admissible_absolute_value R) :=
{ F := _,
coe := λ abs, abs.to_fun }
instance : has_coe (admissible_absolute_value R) (euclidean_absolute_value R ℤ) :=
⟨λ abs, abs.to_euclidean_absolute_value⟩
instance : has_coe (admissible_absolute_value R) (absolute_value R ℤ) :=
⟨λ abs, abs.to_euclidean_absolute_value.to_absolute_value⟩
lemma nonneg (x : R) : 0 ≤ abs x := abs.to_euclidean_absolute_value.nonneg x
@[simp]
lemma eq_zero_iff {x : R} : abs x = 0 ↔ x = 0 :=
abs.to_euclidean_absolute_value.map_eq_zero_iff' x
@[simp]
lemma map_zero : abs 0 = 0 :=
abs.to_euclidean_absolute_value.map_zero
lemma map_ne_zero {x : R} : abs x ≠ 0 ↔ x ≠ 0 :=
abs.to_euclidean_absolute_value.map_ne_zero
lemma pos {x : R} (hx : x ≠ 0) : 0 < abs x :=
abs.to_euclidean_absolute_value.pos hx
@[simp]
lemma map_mul (x y : R) : abs (x * y) = abs x * abs y :=
abs.to_euclidean_absolute_value.map_mul x y
lemma le_add (x y : R) : abs (x + y) ≤ abs x + abs y :=
abs.to_euclidean_absolute_value.le_add x y
@[simp]
lemma map_lt_map_iff {x y : R} : abs x < abs y ↔ euclidean_domain.r x y :=
abs.to_euclidean_absolute_value.map_lt_map_iff
lemma mod_lt (a : R) {b : R} (hb : b ≠ 0) :
abs (a % b) < abs b :=
abs.to_euclidean_absolute_value.sub_mod_lt a hb
@[simp]
lemma map_sub_eq_zero_iff (a b : R) :
abs (a - b) = 0 ↔ a = b :=
abs.to_euclidean_absolute_value.map_sub_eq_zero_iff a b
/-- We can partition a finite family into `card ε` sets, such that the remainders
in each set are close together. -/
lemma exists_partition (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin n → R) :
∃ (t : fin n → fin (abs.card ε)),
∀ i₀ i₁, t i₀ = t i₁ → (abs (A i₁ % b - A i₀ % b) : ℝ) < abs b • ε :=
abs.exists_partition' n hε b hb A
/-- Any large enough family of vectors in `R^n` has a pair of elements
whose remainders are close together, pointwise. -/
lemma exists_approx (n : ℕ) :
∀ {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin (abs.card ε ^ n).succ → (fin n → R)),
∃ (i₀ i₁), (i₀ ≠ i₁) ∧ ∀ k, (abs (A i₁ k % b - A i₀ k % b) : ℝ) < abs b • ε :=
begin
haveI := classical.dec_eq R,
induction n with n ih,
{ intros ε hε b hb A,
refine ⟨0, 1, _, _⟩,
{ simp },
rintros ⟨i, ⟨⟩⟩ },
intros ε hε b hb A,
by_cases hA : ∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₀ = A i₁,
{ obtain ⟨i₀, i₁, h, eq⟩ := hA,
refine ⟨i₀, i₁, h, λ k, _⟩,
rw [eq, sub_self, abs.map_zero, algebra.smul_def, int.cast_zero, ring_hom.eq_int_cast],
exact mul_pos (int.cast_pos.mpr (abs.pos hb)) hε },
have A_inj : function.injective A,
{ simp only [not_exists, not_and, ne.def, not_imp_not] at hA,
exact λ x y h, hA x y h },
set M := abs.card ε with hM,
-- By the "nicer" pigeonhole principle, we can find a collection `s`
-- of more than `M^n` elements where the first components lie close together:
obtain ⟨s, s_inj, hs⟩ : ∃ s : fin (M ^ n).succ → fin (M ^ n.succ).succ,
function.injective s ∧
∀ i₀ i₁, (abs (A (s i₁) 0 % b - A (s i₀) 0 % b) : ℝ) < abs b • ε,
{ -- We can partition the `A`s into `m` subsets where
-- the first components lie close together:
obtain ⟨t, ht⟩ : ∃ (t : fin (M ^ n.succ).succ → fin M),
∀ i₀ i₁, t i₀ = t i₁ → (abs (A i₁ 0 % b - A i₀ 0 % b) : ℝ) < abs b • ε :=
abs.exists_partition _ hε hb (λ x, A x 0),
-- Since the `M` subsets contain more than `M * M^n` elements total,
-- there must be a subset that contains more than `M^n` elements.
obtain ⟨s, hs⟩ := @fintype.exists_lt_card_fiber_of_mul_lt_card _ _ _ _ _ t (M ^ n)
(by simpa only [fintype.card_fin, pow_succ] using nat.lt_succ_self (M ^ n.succ) ),
refine ⟨finset.to_vec _ hs, finset.to_vec_injective _ hs, λ i₀ i₁, ht _ _ _⟩,
have := finset.to_vec_mem (finset.univ.filter (λ x, t x = s)) hs,
obtain ⟨_, h₀⟩ := finset.mem_filter.mp (this i₀),
obtain ⟨_, h₁⟩ := finset.mem_filter.mp (this i₁),
exact h₀.trans h₁.symm },
-- Since `s` is large enough, there are two elements of `A ∘ s`
-- where the second components lie close together.
obtain ⟨k₀, k₁, hk, h⟩ := ih hε hb (λ x, fin.tail (A (s x))),
refine ⟨s k₀, s k₁, λ h, hk (s_inj h), λ i, fin.cases _ (λ i, _) i⟩,
{ exact hs k₀ k₁ },
{ exact h i },
end
end admissible_absolute_value
end admissible
namespace int
/-- We can partition a finite family of integers between `0` and `b` into `partition_card ε` sets,
such that the elements of each set are within `b * ε` of each other. -/
noncomputable def partition_card (ε : ℝ) : ℕ := nat_ceil (1 / ε)
lemma le_partition_card (ε : ℝ) : 1 / ε ≤ partition_card ε :=
le_nat_ceil _
/-- We can partition a finite family into `partition_card ε` sets, such that the remainders
in each set are close together. -/
lemma exists_partition (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : ℤ} (hb : b ≠ 0) (A : fin n → ℤ) :
∃ (t : fin n → fin (partition_card ε)),
∀ i₀ i₁, t i₀ = t i₁ → ↑(abs (A i₁ % b - A i₀ % b)) < abs b • ε :=
begin
have hb' : (0 : ℝ) < ↑(abs b) := int.cast_pos.mpr (abs_pos.mpr hb),
have hbε : 0 < abs b • ε,
{ rw algebra.smul_def,
exact mul_pos hb' hε },
have hfloor : ∀ i, 0 ≤ floor ((A i % b : ℤ) / (abs b • ε) : ℝ),
{ intro i,
exact floor_nonneg.mpr (div_nonneg (cast_nonneg.mpr (mod_nonneg _ hb)) hbε.le) },
refine ⟨λ i, ⟨nat_abs (floor ((A i % b : ℤ) / (abs b • ε) : ℝ)), _⟩, _⟩,
{ rw [← coe_nat_lt, nat_abs_of_nonneg (hfloor i), floor_lt],
apply lt_of_lt_of_le _ (le_partition_card _),
rw [algebra.smul_def, ring_hom.eq_int_cast, ← div_div_eq_div_mul, div_lt_div_right hε,
div_lt_iff hb', one_mul, cast_lt],
exact mod_lt _ hb },
intros i₀ i₁ hi,
have hi : (⌊↑(A i₀ % b) / abs b • ε⌋.nat_abs : ℤ) = ⌊↑(A i₁ % b) / abs b • ε⌋.nat_abs :=
congr_arg (coe : ℕ → ℤ) (subtype.mk_eq_mk.mp hi),
rw [nat_abs_of_nonneg (hfloor i₀), nat_abs_of_nonneg (hfloor i₁)] at hi,
have hi := abs_sub_lt_one_of_floor_eq_floor hi,
rw [abs_sub, ← sub_div, abs_div, abs_of_nonneg hbε.le, div_lt_iff hbε, one_mul] at hi,
rwa [int.cast_abs, int.cast_sub]
end
/-- `abs : ℤ → ℤ` is an admissible absolute value -/
noncomputable def admissible_abs : admissible_absolute_value ℤ :=
{ card := partition_card,
exists_partition' := λ n ε hε b hb, exists_partition n hε hb,
.. euclidean_absolute_value.abs }
noncomputable instance : inhabited (admissible_absolute_value ℤ) := ⟨admissible_abs⟩
end int
namespace polynomial
open absolute_value real
variables {K : Type*} [field K] {c : ℤ} (hc : 1 < c)
section
variables (K)
lemma one_lt_card [fintype K] : 1 < fintype.card K :=
begin
obtain ⟨p, n, hp, hpn⟩ : ∃ p n, _ ∧ fintype.card K = _ := finite_field.card',
rw hpn,
exact pow_lt_pow hp.one_lt n.2
end
/-- `card_pow_degree` is the absolute value on `𝔽_q[t]` sending `f` to `q ^ deg f`. -/
noncomputable def card_pow_degree [fintype K] [decidable_eq K] :
absolute_value (polynomial K) ℤ :=
pow_degree (nat.cast_lt.mpr (one_lt_card K))
end
lemma card_pow_degree_apply [fintype K] [decidable_eq K] {f : polynomial K} (hf : f ≠ 0) :
card_pow_degree K f = fintype.card K ^ nat_degree f :=
by { simp only [card_pow_degree, pow_degree, int.nat_cast_eq_coe_nat], exact if_neg hf }
lemma lt_nat_degree_of_lt_degree {f : polynomial K} {n : ℕ} (h : (n : with_bot ℕ) < degree f) :
n < nat_degree f :=
with_bot.coe_lt_coe.mp (lt_of_lt_of_le h degree_le_nat_degree)
lemma nat_degree_lt_of_degree_lt {f : polynomial K} (hf : f ≠ 0) {n : ℕ} (h : degree f < n) :
nat_degree f < n :=
by rwa [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hf]
variables [fintype K]
/-- If `A` is a family of enough elements, there is a pair of equal elements in `A`. -/
lemma exists_eq {d : ℕ} {m : ℕ} (hm : fintype.card K ^ d ≤ m) (b : polynomial K)
(hb : nat_degree b ≤ d) (A : fin m.succ → polynomial K) (hA : ∀ i, degree (A i) < degree b) :
∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ :=
begin
-- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients,
-- there must be two elements of A with the same coefficients at
-- `0`, ... `degree b - 1` ≤ `d - 1`.
-- In other words, the following map is not injective:
set f : fin m.succ → (fin d → K) := λ i j, (A i).coeff j,
have : fintype.card (fin d → K) < fintype.card (fin m.succ),
{ simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) },
-- Therefore, the differences have all coefficients higher than `deg b - d` equal.
obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this,
use [i₀, i₁, i_ne],
ext j,
-- The coefficients higher than `deg b` are the same because they are equal to 0.
by_cases hbj : degree b ≤ j,
{ rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj),
coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] },
-- So we only need to look for the coefficients between `0` and `deg b`.
rw not_le at hbj,
apply congr_fun i_eq.symm ⟨j, _⟩,
exact lt_of_lt_of_le (lt_nat_degree_of_lt_degree hbj) hb
end
/-- If `A` is a family of enough elements, there is a pair of elements in `A`
(not necessarily distinct), such that their difference has small degree. -/
lemma exists_approx_aux {d : ℕ} {m : ℕ} (hm : fintype.card K ^ d ≤ m) (b : polynomial K)
(A : fin m.succ → polynomial K)
(hA : ∀ i, degree (A i) < degree b):
∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) :=
begin
have hb : b ≠ 0,
{ rintro rfl,
specialize hA 0,
rw degree_zero at hA,
exact not_lt_of_le bot_le hA },
-- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients,
-- there must be two elements of A with the same coefficients at
-- `degree b - 1`, ... `degree b - d`.
-- In other words, the following map is not injective:
set f : fin m.succ → (fin d → K) := λ i j, (A i).coeff (nat_degree b - j.succ),
have : fintype.card (fin d → K) < fintype.card (fin m.succ),
{ simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) },
-- Therefore, the differences have all coefficients higher than `deg b - d` equal.
obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this,
use [i₀, i₁, i_ne],
refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _),
-- The coefficients higher than `deg b` are the same because they are equal to 0.
by_cases hbj : degree b ≤ j,
{ refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj),
exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) },
-- So we only need to look for the coefficients between `deg b - d` and `deg b`.
rw [coeff_sub, sub_eq_zero],
rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj,
have hj : nat_degree b - j.succ < d,
{ by_cases hd : nat_degree b < d,
{ exact lt_of_le_of_lt (nat.sub_le_self _ _) hd },
{ rw not_lt at hd,
have := lt_of_le_of_lt hj (nat.lt_succ_self j),
rwa [nat.sub_lt_iff hd hbj] at this } },
have : j = b.nat_degree - (nat_degree b - j.succ).succ,
{ rw [← nat.succ_sub hbj, nat.succ_sub_succ, nat.sub_sub_self hbj.le] },
convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩
end
/-- If `A` is a family of enough elements, there is a pair of elements in `A`
(not necessarily distinct), such that their difference has small degree. -/
lemma exists_approx [decidable_eq K] {b : polynomial K} (hb : b ≠ 0) {ε : ℝ} (hε : 0 < ε)
(A : fin (fintype.card K ^ (nat_ceil (- log ε / log (fintype.card K)))).succ → polynomial K) :
∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree K (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree K b • ε :=
begin
have hbε : 0 < card_pow_degree K b • ε,
{ rw [algebra.smul_def, ring_hom.eq_int_cast],
exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε },
by_cases le_b : b.nat_degree ≤ nat_ceil (-log ε / log ↑(fintype.card K)),
{ obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq (le_refl _) b le_b (λ i, A i % b)
(λ i, euclidean_domain.mod_lt (A i) hb),
refine ⟨i₀, i₁, i_ne, _⟩,
simp only at mod_eq,
rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] },
rw not_le at le_b,
obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_aux (le_refl _) b (λ i, A i % b)
(λ i, euclidean_domain.mod_lt (A i) hb),
use [i₀, i₁, i_ne],
by_cases h : A i₁ % b = A i₀ % b,
{ rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] },
have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h,
rw [card_pow_degree_apply h', int.cast_pow, int.cast_coe_nat, card_pow_degree_apply hb,
algebra.smul_def, ring_hom.eq_int_cast, int.cast_pow, int.cast_coe_nat],
have deg_lt' : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) <
b.nat_degree + log ε / log (fintype.card K),
{ refine lt_of_lt_of_le (nat.cast_lt.mpr (nat_degree_lt_of_degree_lt h' deg_lt)) _,
rw [← sub_neg_eq_add, neg_div],
refine le_trans _ (sub_le_sub_left (le_nat_ceil _) (b.nat_degree : ℝ)),
rw ← neg_div,
exact le_of_eq (nat.cast_sub le_b.le) },
rw [← rpow_nat_cast, ← rpow_nat_cast],
refine lt_of_lt_of_le (rpow_lt_rpow_of_exponent_lt _ deg_lt') _,
{ simpa using one_lt_card K },
conv_rhs { rw ← exp_log hε },
have hK' : (0 : ℝ) < fintype.card K,
{ rw [← @nat.cast_zero ℝ, nat.cast_lt, fintype.card_pos_iff],
exact ⟨0⟩ },
rw [rpow_def_of_pos hK', rpow_def_of_pos hK', ← exp_add, mul_add, mul_div_cancel'],
refine ne_of_gt (log_pos _),
rw [← nat.cast_one, nat.cast_lt],
exact one_lt_card K
end
lemma card_pow_degree_anti_archimedean [decidable_eq K] {x y z : polynomial K} {a : ℝ}
(hxy : (card_pow_degree K (x - y) : ℝ) < a) (hyz : (card_pow_degree K (y - z) : ℝ) < a) :
(card_pow_degree K (x - z) : ℝ) < a :=
begin
have ha : 0 < a := lt_of_le_of_lt (int.cast_nonneg.mpr (absolute_value.nonneg _ _)) hxy,
by_cases hxy' : x = y,
{ rwa hxy' },
by_cases hyz' : y = z,
{ rwa ← hyz' },
by_cases hxz' : x = z,
{ rwa [hxz', sub_self, absolute_value.map_zero, int.cast_zero] },
rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz',
refine lt_of_le_of_lt _ (max_lt hxy hyz),
rw [card_pow_degree_apply hxz', card_pow_degree_apply hxy', card_pow_degree_apply hyz'],
have : (1 : ℝ) ≤ fintype.card K := by simpa using (one_lt_card K).le,
simp only [int.cast_pow, int.cast_coe_nat, le_max_iff],
refine or.imp (pow_le_pow this) (pow_le_pow this) _,
rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff,
← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'],
convert degree_add_le (x - y) (y - z) using 2,
exact (sub_add_sub_cancel _ _ _).symm
end
/-- A slightly stronger version of `exists_partition` on which we perform induction on `n`. -/
lemma exists_partition_aux [decidable_eq K] (n : ℕ) {ε : ℝ} (hε : 0 < ε)
{b : polynomial K} (hb : b ≠ 0) (A : fin n → polynomial K) :
∃ (t : fin n → fin (fintype.card K ^ nat_ceil (-log ε / log ↑(fintype.card K)))),
∀ (i₀ i₁ : fin n),
t i₀ = t i₁ ↔ (card_pow_degree K (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree K b • ε :=
begin
have hbε : 0 < card_pow_degree K b • ε,
{ rw [algebra.smul_def, ring_hom.eq_int_cast],
exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε },
induction n with n ih,
{ refine ⟨fin_zero_elim, fin_zero_elim⟩ },
obtain ⟨t', ht'⟩ := ih (fin.tail A),
suffices : ∃ j,
∀ i, t' i = j ↔ (card_pow_degree K (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree K b • ε,
{ obtain ⟨j, hj⟩ := this,
refine ⟨fin.cons j t', λ i₀ i₁, _⟩,
refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁,
{ simpa using hbε },
{ rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.sub_comm],
exact hj i₁ },
{ rw [fin.cons_succ, fin.cons_zero],
exact hj i₀ },
{ rw [fin.cons_succ, fin.cons_succ],
exact ht' i₀ i₁ } },
have approx_of_approx : ∀ (i : fin n),
(card_pow_degree K (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree K b • ε →
∀ i', t' i' = t' i →
(card_pow_degree K (A 0 % b - A i'.succ % b) : ℝ) < card_pow_degree K b • ε,
{ intros i hi i' hi',
exact card_pow_degree_anti_archimedean hi ((ht' _ _).mp hi') },
by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧
∀ i, t' i = j → (card_pow_degree K (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree K b • ε,
{ obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j,
refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩,
apply card_pow_degree_anti_archimedean _ hi',
rw absolute_value.sub_comm,
exact hj _ hi },
obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j →
(card_pow_degree K (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree K b • ε,
{ by_contra this,
push_neg at this,
obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx hb hε
(fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))),
revert j_ne approx,
refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁,
{ exact absurd rfl j_ne },
{ rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.sub_comm] at approx,
have := (classical.some_spec (this j₁)).2,
contradiction },
{ rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx,
have := (classical.some_spec (this j₀)).2,
contradiction },
{ rw [fin.cons_succ, fin.cons_succ] at approx,
rw [ne.def, fin.succ_inj] at j_ne,
have : j₀ = j₁ :=
trans (classical.some_spec (this j₀)).1.symm
(trans ((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx)
(classical.some_spec (this j₁)).1),
contradiction } },
refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩,
have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, approx_of_approx _ hi⟩,
contradiction
end
lemma exists_partition [decidable_eq K] (n : ℕ) {ε : ℝ} (hε : 0 < ε)
{b : polynomial K} (hb : b ≠ 0) (A : fin n → polynomial K) :
∃ (t : fin n → fin (fintype.card K ^ nat_ceil (-log ε / log ↑(fintype.card K)))),
∀ (i₀ i₁ : fin n), t i₀ = t i₁ →
(card_pow_degree K (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree K b • ε :=
begin
obtain ⟨t, ht⟩ := exists_partition_aux n hε hb A,
exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩
end
/-- `λ p, fintype.card K ^ degree p` is an admissible absolute value.
We set `admissible_card_pow_degree 0 = 0`. -/
noncomputable def admissible_card_pow_degree [decidable_eq K] :
admissible_absolute_value (polynomial K) :=
{ map_lt_map_iff' := λ p q, begin
by_cases hp : p = 0; by_cases hq : q = 0,
{ simp [hp, hq, euclidean_domain.r] },
{ simp [hp, hq, euclidean_domain.r, absolute_value.pos_iff, bot_lt_iff_ne_bot, degree_eq_bot] },
{ simpa [hp, hq, euclidean_domain.r, absolute_value.pos_iff, bot_lt_iff_ne_bot, degree_eq_bot]
using (card_pow_degree K).nonneg p },
{ simp only [card_pow_degree_apply hp, card_pow_degree_apply hq, euclidean_domain.r,
mul_hom.to_fun_eq_coe, coe_to_mul_hom],
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe, pow_lt_pow_iff],
exact_mod_cast one_lt_card K },
end,
card := λ ε, fintype.card K ^ (nat_ceil (- log ε / log (fintype.card K))),
exists_partition' := λ n ε hε b hb, exists_partition n hε hb,
.. card_pow_degree K }
end polynomial
|
1376e5ec8a03f282e8b81af91817d6257fbc9432 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/ring_theory/power_series.lean | de615c27a232dbc16ed2c41ca545e58f859d736f | [
"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 | 58,303 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kenny Lau
-/
import data.finsupp order.complete_lattice algebra.ordered_group data.mv_polynomial
import algebra.order_functions
import ring_theory.ideal_operations
/-!
# Formal power series
This file defines (multivariate) formal power series
and develops the basic properties of these objects.
A formal power series is to a polynomial like an infinite sum is to a finite sum.
We provide the natural inclusion from polynomials to formal power series.
## Generalities
The file starts with setting up the (semi)ring structure on multivariate power series.
`trunc n φ` truncates a formal power series to the polynomial
that has the same coefficients as φ, for all m ≤ n, and 0 otherwise.
If the constant coefficient of a formal power series is invertible,
then this formal power series is invertible.
Formal power series over a local ring form a local ring.
## Formal power series in one variable
We prove that if the ring of coefficients is an integral domain,
then formal power series in one variable form an integral domain.
The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`.
If the coefficients form an integral domain, then `order` is a valuation
(`order_mul`, `order_add_ge`).
## Implementation notes
In this file we define multivariate formal power series with
variables indexed by `σ` and coefficients in `α` as
mv_power_series σ α := (σ →₀ ℕ) → α.
Unfortunately there is not yet enough API to show that they are the completion
of the ring of multivariate polynomials. However, we provide most of the infrastructure
that is needed to do this. Once I-adic completion (topological or algebraic) is available
it should not be hard to fill in the details.
Formal power series in one variable are defined as
power_series α := mv_power_series unit α.
This allows us to port a lot of proofs and properties
from the multivariate case to the single variable case.
However, it means that formal power series are indexed by (unit →₀ ℕ),
which is of course canonically isomorphic to ℕ.
We then build some glue to treat formal power series as if they are indexed by ℕ.
Occasionally this leads to proofs that are uglier than expected.
-/
noncomputable theory
open_locale classical
/-- Multivariate formal power series, where `σ` is the index set of the variables
and `α` is the coefficient ring.-/
def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α
namespace mv_power_series
open finsupp
variables {σ : Type*} {α : Type*}
instance [inhabited α] : inhabited (mv_power_series σ α) := ⟨λ _, default _⟩
instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero
instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid
instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group
instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid
instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group
section add_monoid
variables [add_monoid α]
variables (α)
/-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/
def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α :=
{ to_fun := λ a m, if m = n then a else 0,
map_zero' := funext $ λ m, by { split_ifs; refl },
map_add' := λ a b, funext $ λ m,
show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0),
from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] }
/-- The `n`th coefficient of a multivariate formal power series.-/
def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α :=
{ to_fun := λ φ, φ n,
map_zero' := rfl,
map_add' := λ _ _, rfl }
variables {α}
/-- Two multivariate formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) :
φ = ψ :=
funext h
/-- Two multivariate formal power series are equal
if and only if all their coefficients are equal.-/
lemma ext_iff {φ ψ : mv_power_series σ α} :
φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) :=
⟨λ h n, congr_arg (coeff α n) h, ext⟩
lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) :
coeff α m (monomial α n a) = if m = n then a else 0 := rfl
@[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) :
coeff α n (monomial α n a) = a := if_pos rfl
@[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) :
(coeff α n).comp (monomial α n) = add_monoid_hom.id α :=
add_monoid_hom.ext $ coeff_monomial' n
@[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl
end add_monoid
section semiring
variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α)
instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩
lemma coeff_one :
coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl
@[simp, priority 1100] lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 :=
coeff_monomial' 0 1
instance : has_mul (mv_power_series σ α) :=
⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩
lemma coeff_mul : coeff α n (φ * ψ) =
(finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl
protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma mul_zero : φ * 0 = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ :=
ext $ λ n,
begin
rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)];
simp [mem_antidiagonal_support, coeff_one],
show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) →
(if i = 0 then coeff α j φ else 0) = 0,
intros i j hij h,
rw [if_neg],
contrapose! h,
simpa [h] using hij,
end
protected lemma mul_one : φ * 1 = φ :=
ext $ λ n,
begin
rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))],
rotate,
{ rintros ⟨i, j⟩ hij h,
rw [coeff_one, if_neg, mul_zero],
rw mem_antidiagonal_support at hij,
contrapose! h,
simpa [h] using hij },
all_goals { simp [mem_antidiagonal_support, coeff_one] }
end
protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) :
φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add]
protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) :
(φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add]
protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) :
(φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) :=
ext $ λ n,
begin
simp only [coeff_mul],
have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support
(λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃),
convert this.symm using 1; clear this,
{ apply finset.sum_congr rfl,
intros p hp, exact finset.sum_mul },
have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support
(λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)),
convert this.symm using 1; clear this,
{ apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum },
apply finset.sum_bij,
swap 5,
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H,
simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, rw mul_assoc },
{ rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂,
simp only [finset.mem_sigma, mem_antidiagonal_support,
and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢,
finish },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩;
{ simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } }
end
instance : semiring (mv_power_series σ α) :=
{ mul_one := mv_power_series.mul_one,
one_mul := mv_power_series.one_mul,
mul_assoc := mv_power_series.mul_assoc,
mul_zero := mv_power_series.mul_zero,
zero_mul := mv_power_series.zero_mul,
left_distrib := mv_power_series.mul_add,
right_distrib := mv_power_series.add_mul,
.. mv_power_series.has_one,
.. mv_power_series.has_mul,
.. mv_power_series.add_comm_monoid }
end semiring
instance [comm_semiring α] : comm_semiring (mv_power_series σ α) :=
{ mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap)
(λ p hp, swap_mem_antidiagonal_support hp)
(λ p hp, mul_comm _ _)
(λ p q hp hq H, by simpa using congr_arg prod.swap H)
(λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩),
.. mv_power_series.semiring }
instance [ring α] : ring (mv_power_series σ α) :=
{ .. mv_power_series.semiring,
.. mv_power_series.add_comm_group }
instance [comm_ring α] : comm_ring (mv_power_series σ α) :=
{ .. mv_power_series.comm_semiring,
.. mv_power_series.add_comm_group }
section semiring
variables [semiring α]
lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) :
monomial α m a * monomial α n b = monomial α (m + n) (a * b) :=
begin
ext k, rw [coeff_mul, coeff_monomial], split_ifs with h,
{ rw [h, finset.sum_eq_single (m,n)],
{ rw [coeff_monomial', coeff_monomial'] },
{ rintros ⟨i,j⟩ hij hne,
rw [ne.def, prod.mk.inj_iff, not_and] at hne,
by_cases H : i = m,
{ rw [coeff_monomial j n b, if_neg (hne H), mul_zero] },
{ rw [coeff_monomial, if_neg H, zero_mul] } },
{ intro H, rw finsupp.mem_antidiagonal_support at H,
exfalso, exact H rfl } },
{ rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij,
rw finsupp.mem_antidiagonal_support at hij,
by_cases H : i = m,
{ subst i, have : j ≠ n, { rintro rfl, exact h hij.symm },
{ rw [coeff_monomial j n b, if_neg this, mul_zero] } },
{ rw [coeff_monomial, if_neg H, zero_mul] } }
end
variables (σ) (α)
/-- The constant multivariate formal power series.-/
def C : α →+* mv_power_series σ α :=
{ map_one' := rfl,
map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm,
.. monomial α (0 : σ →₀ ℕ) }
variables {σ} {α}
@[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl
@[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl
lemma coeff_C (n : σ →₀ ℕ) (a : α) :
coeff α n (C σ α a) = if n = 0 then a else 0 := rfl
@[simp, priority 1100]
lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a :=
coeff_monomial' 0 a
/-- The variables of the multivariate formal power series ring.-/
def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1
lemma coeff_X (n : σ →₀ ℕ) (s : σ) :
coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl
lemma coeff_index_single_X (s t : σ) :
coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 :=
by { simp only [coeff_X, single_right_inj one_ne_zero], split_ifs; refl }
@[simp] lemma coeff_index_single_self_X (s : σ) :
coeff α (single s 1) (X s : mv_power_series σ α) = 1 :=
if_pos rfl
@[simp, priority 1100]
lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 :=
by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) }
lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl
lemma X_pow_eq (s : σ) (n : ℕ) :
(X s : mv_power_series σ α)^n = monomial α (single s n) 1 :=
begin
induction n with n ih,
{ rw [pow_zero, finsupp.single_zero], refl },
{ rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] }
end
lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) :
coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 :=
by rw [X_pow_eq s n, coeff_monomial]
@[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ α) (a : α) :
coeff α n (φ * (C σ α a)) = (coeff α n φ) * a :=
begin
rw [coeff_mul n φ], rw [finset.sum_eq_single (n,(0 : σ →₀ ℕ))],
{ rw [coeff_C, if_pos rfl] },
{ rintro ⟨i,j⟩ hij hne,
rw finsupp.mem_antidiagonal_support at hij,
by_cases hj : j = 0,
{ subst hj, simp at *, contradiction },
{ rw [coeff_C, if_neg hj, mul_zero] } },
{ intro h, exfalso, apply h,
rw finsupp.mem_antidiagonal_support,
apply add_zero }
end
lemma coeff_zero_mul_X (φ : mv_power_series σ α) (s : σ) :
coeff α (0 : σ →₀ ℕ) (φ * X s) = 0 :=
begin
rw [coeff_mul _ φ, finset.sum_eq_zero],
rintro ⟨i,j⟩ hij,
obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0,
{ rw finsupp.mem_antidiagonal_support at hij,
simpa using hij },
simp,
end
variables (σ) (α)
/-- The constant coefficient of a formal power series.-/
def constant_coeff : (mv_power_series σ α) →+* α :=
{ to_fun := coeff α (0 : σ →₀ ℕ),
map_one' := coeff_zero_one,
map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero],
.. coeff α (0 : σ →₀ ℕ) }
variables {σ} {α}
@[simp] lemma coeff_zero_eq_constant_coeff :
coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl
@[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) :
coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl
@[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl
@[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl
@[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s
/-- If a multivariate formal power series is invertible,
then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) :
is_unit (constant_coeff σ α φ) :=
h.map' (constant_coeff σ α)
instance : semimodule α (mv_power_series σ α) :=
{ smul := λ a φ, C σ α a * φ,
one_smul := λ φ, one_mul _,
mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc],
smul_add := λ a φ ψ, mul_add _ _ _,
smul_zero := λ a, mul_zero _,
add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul],
zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] }
end semiring
instance [ring α] : module α (mv_power_series σ α) :=
{ ..mv_power_series.semimodule }
instance [comm_ring α] : algebra α (mv_power_series σ α) :=
{ to_fun := C σ α,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, rfl,
.. mv_power_series.module }
section map
variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ]
variables (f : α →+* β) (g : β →+* γ)
variable (σ)
/-- The map between multivariate formal power series induced by a map on the coefficients.-/
def map : mv_power_series σ α →+* mv_power_series σ β :=
{ to_fun := λ φ n, f $ coeff α n φ,
map_zero' := ext $ λ n, f.map_zero,
map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1,
by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] },
map_add' := λ φ ψ, ext $ λ n,
show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp,
map_mul' := λ φ ψ, ext $ λ n, show f _ = _,
begin
rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [f.map_mul], refl,
end }
variable {σ}
@[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl
lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl
@[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) :
coeff β n (map σ f φ) = f (coeff α n φ) := rfl
@[simp] lemma constant_coeff_map (φ : mv_power_series σ α) :
constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl
end map
section trunc
variables [comm_semiring α] (n : σ →₀ ℕ)
-- Auxiliary definition for the truncation function.
def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α :=
{ support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0),
to_fun := λ m, if m ≤ n then coeff α m φ else 0,
mem_support_to_fun := λ m,
begin
suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n,
{ rw [finset.mem_filter, this], split,
{ intro h, rw [if_pos h.1], exact h.2 },
{ intro h, split_ifs at h with H H,
{ exact ⟨H, h⟩ },
{ exfalso, exact h rfl } } },
rw finset.mem_image, split,
{ rintros ⟨⟨i,j⟩, h, rfl⟩ s,
rw finsupp.mem_antidiagonal_support at h,
rw ← h, exact nat.le_add_right _ _ },
{ intro h, refine ⟨(m, n-m), _, rfl⟩,
rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) }
end }
variable (α)
/-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/
def trunc : mv_power_series σ α →+ mv_polynomial σ α :=
{ to_fun := trunc_fun n,
map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl },
map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m,
begin
rw mv_polynomial.coeff_add,
change ite _ _ _ = ite _ _ _ + ite _ _ _,
split_ifs with H, {refl}, {rw [zero_add]}
end }
variable {α}
lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) :
mv_polynomial.coeff m (trunc α n φ) =
if m ≤ n then coeff α m φ else 0 := rfl
@[simp] lemma trunc_one : trunc α n 1 = 1 :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H',
{ subst m, erw mv_polynomial.coeff_C 0, simp },
{ symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), },
{ symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _,
intro H', apply H, subst m, intro s, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *},
exfalso, apply H, subst m, intro s, exact nat.zero_le _
end
end trunc
section comm_semiring
variable [comm_semiring α]
lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} :
(X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 :=
begin
split,
{ rintros ⟨φ, rfl⟩ m h,
rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul],
contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij,
rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ },
{ intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩,
ext m, by_cases H : m - single s n + single s n = m,
{ rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)],
{ rw [coeff_X_pow, if_pos rfl, one_mul],
simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm },
{ rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩,
ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] },
{ exact zero_mul _ } },
{ intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } },
{ rw [h, coeff_mul, finset.sum_eq_zero],
{ rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply H, rw [← hij, hi], ext t,
simp only [nat.add_sub_cancel_left, add_comm,
finsupp.add_apply, add_right_inj, finsupp.nat_sub_apply] },
{ exact zero_mul _ } },
{ classical, contrapose! H, ext t,
by_cases hst : s = t,
{ subst t, simpa using nat.sub_add_cancel H },
{ simp [finsupp.single_apply, hst] } } } }
end
lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} :
(X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 :=
begin
rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff],
split; intros h m hm,
{ exact h m (hm.symm ▸ zero_lt_one) },
{ exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) }
end
end comm_semiring
section ring
variables [ring α]
/-
The inverse of a multivariate formal power series is defined by
well-founded recursion on the coeffients of the inverse.
-/
/-- Auxiliary definition that unifies
the totalised inverse formal power series `(_)⁻¹` and
the inverse formal power series that depends on
an inverse of the constant coefficient `inv_of_unit`.-/
protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α
| n := if n = 0 then a else
- a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0)
using_well_founded
{ rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩],
dec_tac := tactic.assumption }
lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) :
coeff α n (inv.aux a φ) = if n = 0 then a else
- a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) :=
show inv.aux a φ n = _, by { rw inv.aux, refl }
/-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α :=
inv.aux (↑u⁻¹) φ
lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) :
coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) :=
coeff_inv_aux n (↑u⁻¹) φ
@[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) :
constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) :
φ * inv_of_unit φ u = 1 :=
ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], }
else
begin
have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support,
{ rw [finsupp.mem_antidiagonal_support, zero_add] },
rw [coeff_one, if_neg H, coeff_mul,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H,
neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm,
← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij,
cases hij with h₁ h₂,
subst n, rw if_pos,
suffices : (0 : _) + j < i + j, {simpa},
apply add_lt_add_right,
split,
{ intro s, exact nat.zero_le _ },
{ intro H, apply h₁,
suffices : i = 0, {simp [this]},
ext1 s, exact nat.eq_zero_of_le_zero (H s) }
end
end ring
section comm_ring
variable [comm_ring α]
/-- Multivariate formal power series over a local ring form a local ring.-/
lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) :=
begin
split,
{ have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H,
simpa using congr_arg (constant_coeff σ α) H },
{ intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right];
{ refine is_unit_of_mul_one _ _ (mul_inv_of_unit _ u _),
simpa using h } }
end
-- TODO(jmc): once adic topology lands, show that this is complete
end comm_ring
section nonzero_comm_ring
variables [nonzero_comm_ring α]
instance : nonzero_comm_ring (mv_power_series σ α) :=
{ zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h,
.. mv_power_series.comm_ring }
lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t :=
⟨begin
intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h,
split_ifs at h with H,
{ rw finsupp.single_eq_single_iff at H,
cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } },
{ exfalso, exact one_ne_zero h }
end, congr_arg X⟩
end nonzero_comm_ring
section local_ring
variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f]
instance : local_ring (mv_power_series σ α) :=
local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩
instance map.is_local_ring_hom : is_local_ring_hom (map σ f) :=
⟨begin
rintros φ ⟨ψ, h⟩,
replace h := congr_arg (constant_coeff σ β) h,
rw constant_coeff_map at h,
have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ),
rw ← h at this,
rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩,
exact is_unit_of_mul_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc)
end⟩
end local_ring
section field
variables [field α]
protected def inv (φ : mv_power_series σ α) : mv_power_series σ α :=
inv.aux (constant_coeff σ α φ)⁻¹ φ
instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩
lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) :
coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else
- (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) :=
coeff_inv_aux n _ φ
@[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) :
constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl]
lemma inv_eq_zero {φ : mv_power_series σ α} :
φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 :=
⟨λ h, by simpa using congr_arg (constant_coeff σ α) h,
λ h, ext $ λ n, by { rw coeff_inv, split_ifs;
simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩
@[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl
@[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) :
inv_of_unit φ u = φ⁻¹ :=
begin
rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero),
congr' 1, rw [units.ext_iff], exact h.symm,
end
@[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) :
φ * φ⁻¹ = 1 :=
by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl]
@[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) :
φ⁻¹ * φ = 1 :=
by rw [mul_comm, φ.mul_inv h]
end field
end mv_power_series
namespace mv_polynomial
open finsupp
variables {σ : Type*} {α : Type*} [comm_semiring α]
/-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/
instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) :=
⟨λ φ n, coeff n φ⟩
@[simp, elim_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) :
mv_power_series.coeff α n ↑φ = coeff n φ := rfl
@[simp, elim_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) :
(monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a :=
mv_power_series.ext $ λ m,
begin
rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial],
split_ifs with h₁ h₂; refl <|> subst m; contradiction
end
@[simp, elim_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl
@[simp, elim_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 :=
coe_monomial _ _
@[simp, elim_cast] lemma coe_add (φ ψ : mv_polynomial σ α) :
((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl
@[simp, elim_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) :
((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ :=
mv_power_series.ext $ λ n,
by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul]
@[simp, elim_cast] lemma coe_C (a : α) :
((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a :=
coe_monomial _ _
@[simp, elim_cast] lemma coe_X (s : σ) :
((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s :=
coe_monomial _ _
namespace coe_to_mv_power_series
instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) :=
{ map_zero := coe_zero,
map_one := coe_one,
map_add := coe_add,
map_mul := coe_mul }
end coe_to_mv_power_series
end mv_polynomial
/-- Formal power series over the coefficient ring `α`.-/
def power_series (α : Type*) := mv_power_series unit α
namespace power_series
open finsupp (single)
variable {α : Type*}
instance [inhabited α] : inhabited (power_series α) := by delta power_series; apply_instance
instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance
instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance
instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance
instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance
instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance
instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance
instance [ring α] : ring (power_series α) := by delta power_series; apply_instance
instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance
instance [nonzero_comm_ring α] : nonzero_comm_ring (power_series α) := by delta power_series; apply_instance
instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance
instance [ring α] : module α (power_series α) := by delta power_series; apply_instance
instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance
section add_monoid
variables (α) [add_monoid α]
/-- The `n`th coefficient of a formal power series.-/
def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n)
/-- The `n`th monomial with coefficient `a` as formal power series.-/
def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n)
variables {α}
lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) :
coeff α n = mv_power_series.coeff α s :=
by erw [coeff, ← h, ← finsupp.unique_single s]
/-- Two formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) :
φ = ψ :=
mv_power_series.ext $ λ n,
by { rw ← coeff_def, { apply h }, refl }
/-- Two formal power series are equal if all their coefficients are equal.-/
lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) :=
⟨λ h n, congr_arg (coeff α n) h, ext⟩
/-- Constructor for formal power series.-/
def mk (f : ℕ → α) : power_series α := λ s, f (s ())
@[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n :=
congr_arg f finsupp.single_eq_same
lemma coeff_monomial (m n : ℕ) (a : α) :
coeff α m (monomial α n a) = if m = n then a else 0 :=
calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _
... = if m = n then a else 0 :
by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl }
lemma monomial_eq_mk (n : ℕ) (a : α) :
monomial α n a = mk (λ m, if m = n then a else 0) :=
ext $ λ m, by { rw [coeff_monomial, coeff_mk] }
@[simp] lemma coeff_monomial' (n : ℕ) (a : α) :
coeff α n (monomial α n a) = a :=
by convert if_pos rfl
@[simp] lemma coeff_comp_monomial (n : ℕ) :
(coeff α n).comp (monomial α n) = add_monoid_hom.id α :=
add_monoid_hom.ext $ coeff_monomial' n
end add_monoid
section semiring
variable [semiring α]
variable (α)
/--The constant coefficient of a formal power series. -/
def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α
/-- The constant formal power series.-/
def C : α →+* power_series α := mv_power_series.C unit α
variable {α}
/-- The variable of the formal power series ring.-/
def X : power_series α := mv_power_series.X ()
@[simp] lemma coeff_zero_eq_constant_coeff :
coeff α 0 = constant_coeff α :=
begin
rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl
end
@[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) :
coeff α 0 φ = constant_coeff α φ :=
by rw [coeff_zero_eq_constant_coeff]; refl
@[simp] lemma monomial_zero_eq_C : monomial α 0 = C α :=
by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C]
@[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a :=
by rw [monomial_zero_eq_C]; refl
lemma coeff_C (n : ℕ) (a : α) :
coeff α n (C α a : power_series α) = if n = 0 then a else 0 :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial]
@[simp] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a]
lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl
lemma coeff_X (n : ℕ) :
coeff α n (X : power_series α) = if n = 1 then 1 else 0 :=
by rw [X_eq, coeff_monomial]
@[simp] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 :=
by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X]
@[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 :=
by rw [coeff_X, if_pos rfl]
lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 :=
mv_power_series.X_pow_eq _ n
lemma coeff_X_pow (m n : ℕ) :
coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 :=
by rw [X_pow_eq, coeff_monomial]
@[simp] lemma coeff_X_pow_self (n : ℕ) :
coeff α n ((X : power_series α)^n) = 1 :=
by rw [coeff_X_pow, if_pos rfl]
@[simp] lemma coeff_one (n : ℕ) :
coeff α n (1 : power_series α) = if n = 0 then 1 else 0 :=
calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _
... = if n = 0 then 1 else 0 :
by { simp only [finsupp.single_eq_zero], split_ifs; refl }
@[simp] lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 :=
coeff_zero_C 1
lemma coeff_mul (n : ℕ) (φ ψ : power_series α) :
coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) :=
begin
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij, refl },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal_support at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
@[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series α) (a : α) :
coeff α n (φ * (C α a)) = (coeff α n φ) * a :=
mv_power_series.coeff_mul_C _ φ a
@[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series α) :
coeff α (n+1) (φ * X) = coeff α n φ :=
begin
rw [coeff_mul _ φ, finset.sum_eq_single (n,1)],
{ rw [coeff_X, if_pos rfl, mul_one] },
{ rintro ⟨i,j⟩ hij hne,
by_cases hj : j = 1,
{ subst hj, simp at *, contradiction },
{ simp [coeff_X, hj] } },
{ intro h, exfalso, apply h, simp },
end
@[simp] lemma coeff_zero_mul_X (φ : power_series α) :
coeff α 0 (φ * X) = 0 :=
begin
rw [coeff_mul _ φ, finset.sum_eq_zero],
rintro ⟨i,j⟩ hij,
obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { simpa using hij },
simp,
end
@[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff α).comp (C α) = ring_hom.id α := rfl
@[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl
@[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _
/-- If a formal power series is invertible, then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) :
is_unit (constant_coeff α φ) :=
mv_power_series.is_unit_constant_coeff φ h
section map
variables {β : Type*} {γ : Type*} [semiring β] [semiring γ]
variables (f : α →+* β) (g : β →+* γ)
/-- The map between formal power series induced by a map on the coefficients.-/
def map : power_series α →+* power_series β :=
mv_power_series.map _ f
@[simp] lemma map_id : (map (ring_hom.id α) :
power_series α → power_series α) = id := rfl
lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl
@[simp] lemma coeff_map (n : ℕ) (φ : power_series α) :
coeff β n (map f φ) = f (coeff α n φ) := rfl
end map
end semiring
section comm_semiring
variables [comm_semiring α]
lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} :
(X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 :=
begin
convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext,
classical, split; intros h m hm,
{ rw finsupp.unique_single m, convert h _ hm },
{ apply h, simpa only [finsupp.single_eq_same] using hm }
end
lemma X_dvd_iff {φ : power_series α} :
(X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 :=
begin
rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply],
split; intro h,
{ exact h 0 zero_lt_one },
{ intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) }
end
section trunc
/-- The `n`th truncation of a formal power series to a polynomial -/
def trunc (n : ℕ) (φ : power_series α) : polynomial α :=
{ support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0),
to_fun := λ m, if m ≤ n then coeff α m φ else 0,
mem_support_to_fun := λ m,
begin
suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n,
{ rw [finset.mem_filter, this], split,
{ intro h, rw [if_pos h.1], exact h.2 },
{ intro h, split_ifs at h with H H,
{ exact ⟨H, h⟩ },
{ exfalso, exact h rfl } } },
rw finset.mem_image, split,
{ rintros ⟨⟨i,j⟩, h, rfl⟩,
rw finset.nat.mem_antidiagonal at h,
rw ← h, exact nat.le_add_right _ _ },
{ intro h, refine ⟨(m, n-m), _, rfl⟩,
rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h }
end }
lemma coeff_trunc (m) (n) (φ : power_series α) :
polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl
@[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero],
split_ifs; refl
end
@[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H'; rw [polynomial.coeff_one],
{ subst m, rw [if_pos rfl] },
{ symmetry, exact if_neg (ne.elim (ne.symm H')) },
{ symmetry, refine if_neg _,
intro H', apply H, subst m, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_C, polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *}
end
@[simp] lemma trunc_add (n) (φ ψ : power_series α) :
trunc n (φ + ψ) = trunc n φ + trunc n ψ :=
polynomial.ext $ λ m,
begin
simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add],
split_ifs with H, {refl}, {rw [zero_add]}
end
end trunc
end comm_semiring
section ring
variables [ring α]
protected def inv.aux : α → power_series α → power_series α :=
mv_power_series.inv.aux
lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) :
coeff α n (inv.aux a φ) = if n = 0 then a else
- a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) :=
begin
rw [coeff, inv.aux, mv_power_series.coeff_inv_aux],
simp only [finsupp.single_eq_zero],
split_ifs, {refl},
congr' 1,
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij,
by_cases H : j < n,
{ rw [if_pos H, if_pos], {refl},
split,
{ rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H },
{ intro hh, rw lt_iff_not_ge at H, apply H,
simpa [finsupp.single_eq_same] using hh () } },
{ rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩,
simpa [finsupp.single_eq_same] using not_lt.1 H } },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal_support at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
/-- A formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : power_series α) (u : units α) : power_series α :=
mv_power_series.inv_of_unit φ u
lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) :
coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) :=
coeff_inv_aux n ↑u⁻¹ φ
@[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) :
constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) :
φ * inv_of_unit φ u = 1 :=
mv_power_series.mul_inv_of_unit φ u $ h
end ring
section integral_domain
variable [integral_domain α]
lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) :
φ = 0 ∨ ψ = 0 :=
begin
rw classical.or_iff_not_imp_left, intro H,
have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H },
let P : ℕ → Prop := λ k, coeff α k φ ≠ 0,
let m := nat.find ex,
have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex,
have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex,
ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n,
clear n, intros n ih,
replace h := congr_arg (coeff α (m + n)) h,
rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h,
{ replace h := eq_zero_or_eq_zero_of_mul_eq_zero h,
rw or_iff_not_imp_left at h, exact h hm₁ },
{ rintro ⟨i,j⟩ hij hne,
by_cases hj : j < n, { rw [ih j hj, mul_zero] },
by_cases hi : i < m,
{ specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] },
rw finset.nat.mem_antidiagonal at hij,
push_neg at hi hj,
suffices : m < i,
{ have : m + n < i + j := add_lt_add_of_lt_of_le this hj,
exfalso, exact ne_of_lt this hij.symm },
contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne,
simpa [ne.def, prod.mk.inj_iff] using (add_left_inj m).mp hij },
{ contrapose!, intro h, rw finset.nat.mem_antidiagonal }
end
instance : integral_domain (power_series α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero,
.. power_series.nonzero_comm_ring }
/-- The ideal spanned by the variable in the power series ring
over an integral domain is a prime ideal.-/
lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime :=
begin
suffices : ideal.span ({X} : set (power_series α)) = (constant_coeff α).ker,
{ rw this, exact ring_hom.ker_is_prime _ },
apply ideal.ext, intro φ,
rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff]
end
/-- The variable of the power series ring over an integral domain is prime.-/
lemma X_prime : prime (X : power_series α) :=
begin
rw ← ideal.span_singleton_prime,
{ exact span_X_is_prime },
{ intro h, simpa using congr_arg (coeff α 1) h }
end
end integral_domain
section local_ring
variables [comm_ring α]
lemma is_local_ring (h : is_local_ring α) :
is_local_ring (power_series α) :=
mv_power_series.is_local_ring h
end local_ring
section local_ring
variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f]
instance : local_ring (power_series α) :=
mv_power_series.local_ring
instance map.is_local_ring_hom :
is_local_ring_hom (map f) :=
mv_power_series.map.is_local_ring_hom f
end local_ring
section field
variables [field α]
protected def inv : power_series α → power_series α :=
mv_power_series.inv
instance : has_inv (power_series α) := ⟨power_series.inv⟩
lemma inv_eq_inv_aux (φ : power_series α) :
φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl
lemma coeff_inv (n) (φ : power_series α) :
coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else
- (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) :=
by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ]
@[simp] lemma constant_coeff_inv (φ : power_series α) :
constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ :=
mv_power_series.constant_coeff_inv φ
lemma inv_eq_zero {φ : power_series α} :
φ⁻¹ = 0 ↔ constant_coeff α φ = 0 :=
mv_power_series.inv_eq_zero
@[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ :=
mv_power_series.inv_of_unit_eq _ _
@[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) :
inv_of_unit φ u = φ⁻¹ :=
mv_power_series.inv_of_unit_eq' φ _ h
@[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) :
φ * φ⁻¹ = 1 :=
mv_power_series.mul_inv φ h
@[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) :
φ⁻¹ * φ = 1 :=
mv_power_series.inv_mul φ h
end field
end power_series
namespace power_series
variable {α : Type*}
local attribute [instance, priority 1] classical.prop_decidable
noncomputable theory
section order_basic
open multiplicity
variables [comm_semiring α]
/-- The order of a formal power series `φ` is the smallest `n : enat`
such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/
@[reducible] def order (φ : power_series α) : enat :=
multiplicity X φ
lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) :
(order φ).dom :=
begin
cases h with n h, refine ⟨n, _⟩,
rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩
end
/-- If the order of a formal power series is finite,
then the coefficient indexed by the order is nonzero.-/
lemma coeff_order (φ : power_series α) (h : (order φ).dom) :
coeff α (φ.order.get h) φ ≠ 0 :=
begin
have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff,
intros m hm, by_cases Hm : m < nat.find h,
{ have := nat.find_min h Hm, push_neg at this,
rw X_pow_dvd_iff at this, exact this m (lt_add_one m) },
have : m = nat.find h, {linarith}, {rwa this}
end
/-- If the `n`th coefficient of a formal power series is nonzero,
then the order of the power series is less than or equal to `n`.-/
lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) :
order φ ≤ n :=
begin
have h : ¬ X^(n+1) ∣ φ,
{ rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ },
have : (order φ).dom := ⟨n, h⟩,
rw [← enat.coe_get this, enat.coe_le_coe],
refine nat.find_min' this h
end
/-- The `n`th coefficient of a formal power series is `0` if `n` is strictly
smaller than the order of the power series.-/
lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) :
coeff α n φ = 0 :=
by { contrapose! h, exact order_le _ _ h }
/-- The `0` power series is the unique power series with infinite order.-/
lemma order_eq_top {φ : power_series α} :
φ.order = ⊤ ↔ φ = 0 :=
begin
rw multiplicity.eq_top_iff,
split,
{ intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) },
{ rintros rfl n, exact dvd_zero _ }
end
/-- The order of the `0` power series is infinite.-/
@[simp] lemma order_zero : order (0 : power_series α) = ⊤ :=
multiplicity.zero _
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma order_ge_nat (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) :
order φ ≥ n :=
begin
by_contra H, rw not_le at H,
have : (order φ).dom := enat.dom_of_le_some (le_of_lt H),
rw [← enat.coe_get this, enat.coe_lt_coe] at H,
exact coeff_order _ this (h _ H)
end
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma order_ge (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) :
order φ ≥ n :=
begin
induction n using enat.cases_on,
{ show _ ≤ _, rw [top_le_iff, order_eq_top],
ext i, exact h _ (enat.coe_lt_top i) },
{ apply order_ge_nat, simpa only [enat.coe_lt_coe] using h }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq_nat {φ : power_series α} {n : ℕ} :
order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) :=
begin
simp only [eq_some_iff, X_pow_dvd_iff], push_neg,
split,
{ rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩,
suffices : n = m, { rwa this },
suffices : m ≥ n, { linarith },
contrapose! hm₂, exact h₁ _ hm₂ },
{ rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq {φ : power_series α} {n : enat} :
order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) :=
begin
induction n using enat.cases_on,
{ rw order_eq_top, split,
{ rintro rfl, split; intros,
{ exfalso, exact enat.coe_ne_top ‹_› ‹_› },
{ exact (coeff _ _).map_zero } },
{ rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } },
{ simpa [enat.coe_inj] using order_eq_nat }
end
/-- The order of the sum of two formal power series
is at least the minimum of their orders.-/
lemma order_add_ge (φ ψ : power_series α) :
order (φ + ψ) ≥ min (order φ) (order ψ) :=
multiplicity.min_le_multiplicity_add
private lemma order_add_of_order_eq.aux (φ ψ : power_series α)
(h : order φ ≠ order ψ) (H : order φ < order ψ) :
order (φ + ψ) ≤ order φ ⊓ order ψ :=
begin
suffices : order (φ + ψ) = order φ,
{ rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ },
{ rw order_eq, split,
{ intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero],
exact (order_eq_nat.1 hi.symm).1 },
{ intros i hi,
rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi,
coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } }
end
/-- The order of the sum of two formal power series
is the minimum of their orders if their orders differ.-/
lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) :
order (φ + ψ) = order φ ⊓ order ψ :=
begin
refine le_antisymm _ (order_add_ge _ _),
by_cases H₁ : order φ < order ψ,
{ apply order_add_of_order_eq.aux _ _ h H₁ },
by_cases H₂ : order ψ < order φ,
{ simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ },
exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁))
end
/-- The order of the product of two formal power series
is at least the sum of their orders.-/
lemma order_mul_ge (φ ψ : power_series α) :
order (φ * ψ) ≥ order φ + order ψ :=
begin
apply order_ge,
intros n hn, rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij,
by_cases hi : ↑i < order φ,
{ rw [coeff_of_lt_order φ i hi, zero_mul] },
by_cases hj : ↑j < order ψ,
{ rw [coeff_of_lt_order ψ j hj, mul_zero] },
rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij,
exfalso,
apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj),
rw [← enat.coe_add, hij]
end
/-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/
lemma order_monomial (n : ℕ) (a : α) :
order (monomial α n a) = if a = 0 then ⊤ else n :=
begin
split_ifs with h,
{ rw [h, order_eq_top, add_monoid_hom.map_zero] },
{ rw [order_eq], split; intros i hi,
{ rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] },
{ rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } }
end
/-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/
lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) :
order (monomial α n a) = n :=
by rw [order_monomial, if_neg h]
end order_basic
section order_zero_ne_one
variables [nonzero_comm_ring α]
/-- The order of the formal power series `1` is `0`.-/
@[simp] lemma order_one : order (1 : power_series α) = 0 :=
by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero
/-- The order of the formal power series `X` is `1`.-/
@[simp] lemma order_X : order (X : power_series α) = 1 :=
order_monomial_of_ne_zero 1 (1:α) one_ne_zero
/-- The order of the formal power series `X^n` is `n`.-/
@[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n :=
by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero }
end order_zero_ne_one
section order_integral_domain
variables [integral_domain α]
/-- The order of the product of two formal power series over an integral domain
is the sum of their orders.-/
lemma order_mul (φ ψ : power_series α) :
order (φ * ψ) = order φ + order ψ :=
multiplicity.mul (X_prime)
end order_integral_domain
end power_series
namespace polynomial
open finsupp
variables {σ : Type*} {α : Type*} [comm_semiring α]
/-- The natural inclusion from polynomials into formal power series.-/
instance coe_to_power_series : has_coe (polynomial α) (power_series α) :=
⟨λ φ, power_series.mk $ λ n, coeff φ n⟩
@[simp, elim_cast] lemma coeff_coe (φ : polynomial α) (n) :
power_series.coeff α n φ = coeff φ n :=
congr_arg (coeff φ) (finsupp.single_eq_same)
@[simp, elim_cast] lemma coe_monomial (n : ℕ) (a : α) :
(monomial n a : power_series α) = power_series.monomial α n a :=
power_series.ext $ λ m,
begin
rw [coeff_coe, power_series.coeff_monomial],
simp only [@eq_comm _ m n],
convert finsupp.single_apply,
end
@[simp, elim_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl
@[simp, elim_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 :=
begin
have := coe_monomial 0 (1:α),
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, elim_cast] lemma coe_add (φ ψ : polynomial α) :
((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl
@[simp, elim_cast] lemma coe_mul (φ ψ : polynomial α) :
((φ * ψ : polynomial α) : power_series α) = φ * ψ :=
power_series.ext $ λ n,
by simp only [coeff_coe, power_series.coeff_mul, coeff_mul]
@[simp, elim_cast] lemma coe_C (a : α) :
((C a : polynomial α) : power_series α) = power_series.C α a :=
begin
have := coe_monomial 0 a,
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, elim_cast] lemma coe_X :
((X : polynomial α) : power_series α) = power_series.X :=
coe_monomial _ _
namespace coe_to_mv_power_series
instance : is_semiring_hom (coe : polynomial α → power_series α) :=
{ map_zero := coe_zero,
map_one := coe_one,
map_add := coe_add,
map_mul := coe_mul }
end coe_to_mv_power_series
end polynomial
|
1b6965873de9d69808a72eec58bed14c9f30e940 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/field_theory/splitting_field.lean | b50aad9a27cad38a401bc65d0bb8b59d3e88b893 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 37,533 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import ring_theory.adjoin_root
import ring_theory.algebra_tower
import ring_theory.algebraic
import ring_theory.polynomial
import field_theory.minpoly
import linear_algebra.finite_dimensional
import tactic.field_simp
import algebra.polynomial.big_operators
/-!
# Splitting fields
This file introduces the notion of a splitting field of a polynomial and provides an embedding from
a splitting field to any field that splits the polynomial. A polynomial `f : polynomial K` splits
over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have
degree `1`. A field extension of `K` of a polynomial `f : polynomial K` is called a splitting field
if it is the smallest field extension of `K` such that `f` splits.
## Main definitions
* `polynomial.splits i f`: A predicate on a field homomorphism `i : K → L` and a polynomial `f`
saying that `f` is zero or all of its irreducible factors over `L` have degree `1`.
* `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`.
* `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial
`f`.
## Main statements
* `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its
degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a`
ranges through its roots.
* `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset
`S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in
`L`, then `algebra.adjoin F S` embeds into `L`.
* `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into
another field such that `f` splits.
* `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorpic
to `splitting_field f` and thus, being a splitting field is unique up to isomorphism.
-/
noncomputable theory
open_locale classical big_operators
universes u v w
variables {F : Type u} {K : Type v} {L : Type w}
namespace polynomial
variables [field K] [field L] [field F]
open polynomial
section splits
variables (i : K →+* L)
/-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/
def splits (f : polynomial K) : Prop :=
f = 0 ∨ ∀ {g : polynomial L}, irreducible g → g ∣ f.map i → degree g = 1
@[simp] lemma splits_zero : splits i (0 : polynomial K) := or.inl rfl
@[simp] lemma splits_C (a : K) : splits i (C a) :=
if ha : a = 0 then ha.symm ▸ (@C_0 K _).symm ▸ splits_zero i
else
have hia : i a ≠ 0, from mt ((i.injective_iff).1
i.injective _) ha,
or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $
by have := congr_arg degree hp;
simp [degree_C hia, @eq_comm (with_bot ℕ) 0,
nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto))
lemma splits_of_degree_eq_one {f : polynomial K} (hf : degree f = 1) : splits i f :=
or.inr $ λ g hg ⟨p, hp⟩,
by have := congr_arg degree hp;
simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1,
mt is_unit_iff_degree_eq_zero.2 hg.1] at this;
clear _fun_match; tauto
lemma splits_of_degree_le_one {f : polynomial K} (hf : degree f ≤ 1) : splits i f :=
begin
cases h : degree f with n,
{ rw [degree_eq_bot.1 h]; exact splits_zero i },
{ cases n with n,
{ rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))];
exact splits_C _ _ },
{ have hn : n = 0,
{ rw h at hf,
cases n, { refl }, { exact absurd hf dec_trivial } },
exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } }
end
lemma splits_of_nat_degree_le_one {f : polynomial K} (hf : nat_degree f ≤ 1) : splits i f :=
splits_of_degree_le_one i (degree_le_of_nat_degree_le hf)
lemma splits_of_nat_degree_eq_one {f : polynomial K} (hf : nat_degree f = 1) : splits i f :=
splits_of_nat_degree_le_one i (le_of_eq hf)
lemma splits_mul {f g : polynomial K} (hf : splits i f) (hg : splits i g) : splits i (f * g) :=
if h : f * g = 0 then by simp [h]
else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _
(show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim
(hf.resolve_left (λ hf, by simpa [hf] using h) hp)
(hg.resolve_left (λ hg, by simpa [hg] using h) hp)
lemma splits_of_splits_mul {f g : polynomial K} (hfg : f * g ≠ 0) (h : splits i (f * g)) :
splits i f ∧ splits i g :=
⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi
(by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)),
or.inr $ λ g hgi hg, or.resolve_left h hfg hgi
(by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩
lemma splits_of_splits_of_dvd {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) :
splits i g :=
by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 }
lemma splits_of_splits_gcd_left {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) :
splits i (euclidean_domain.gcd f g) :=
polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g)
lemma splits_of_splits_gcd_right {f g : polynomial K} (hg0 : g ≠ 0) (hg : splits i g) :
splits i (euclidean_domain.gcd f g) :=
polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g)
lemma splits_map_iff (j : L →+* F) {f : polynomial K} :
splits j (f.map i) ↔ splits (j.comp i) f :=
by simp [splits, polynomial.map_map]
theorem splits_one : splits i 1 :=
splits_C i 1
theorem splits_of_is_unit {u : polynomial K} (hu : is_unit u) : u.splits i :=
splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu
theorem splits_X_sub_C {x : K} : (X - C x).splits i :=
splits_of_degree_eq_one _ $ degree_X_sub_C x
theorem splits_X : X.splits i :=
splits_of_degree_eq_one _ $ degree_X
theorem splits_id_iff_splits {f : polynomial K} :
(f.map i).splits (ring_hom.id L) ↔ f.splits i :=
by rw [splits_map_iff, ring_hom.id_comp]
theorem splits_mul_iff {f g : polynomial K} (hf : f ≠ 0) (hg : g ≠ 0) :
(f * g).splits i ↔ f.splits i ∧ g.splits i :=
⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩
theorem splits_prod {ι : Type u} {s : ι → polynomial K} {t : finset ι} :
(∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i :=
begin
refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _),
rw finset.forall_mem_insert at ht, rw finset.prod_insert hat,
exact splits_mul i ht.1 (ih ht.2)
end
lemma splits_pow {f : polynomial K} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i :=
begin
rw [←finset.card_range n, ←finset.prod_const],
exact splits_prod i (λ j hj, hf),
end
lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n
theorem splits_prod_iff {ι : Type u} {s : ι → polynomial K} {t : finset ι} :
(∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) :=
begin
refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _),
rw finset.forall_mem_insert at ht ⊢,
rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2]
end
lemma degree_eq_one_of_irreducible_of_splits {p : polynomial L}
(h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id L) p) :
p.degree = 1 :=
begin
rcases hp_splits,
{ contradiction },
{ apply hp_splits hp, simp }
end
lemma exists_root_of_splits {f : polynomial K} (hs : splits i f) (hf0 : degree f ≠ 0) :
∃ x, eval₂ i x f = 0 :=
if hf0 : f = 0 then ⟨37, by simp [hf0]⟩
else
let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor
(show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map))
(map_ne_zero hf0) in
let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in
let ⟨i, hi⟩ := hg.2 in
⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩
lemma exists_multiset_of_splits {f : polynomial K} : splits i f →
∃ (s : multiset L), f.map i = C (i f.leading_coeff) *
(s.map (λ a : L, (X : polynomial L) - C a)).prod :=
suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset L, f.map i =
(C (f.map i).leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod,
by rwa [splits_map_iff, leading_coeff_map i] at this,
wf_dvd_monoid.induction_on_irreducible (f.map i)
(λ _, ⟨{37}, by simp [i.map_zero]⟩)
(λ u hu _, ⟨0,
by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) };
simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩)
(λ f p hf0 hp ih hfs,
have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0,
let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in
⟨-(p * norm_unit p).coeff 0 ::ₘ s,
have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp),
begin
rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc,
mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0],
conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1},
simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg,
C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm,
mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1
hp.ne_zero), one_mul],
end⟩)
/-- Pick a root of a polynomial that splits. -/
def root_of_splits {f : polynomial K} (hf : f.splits i) (hfd : f.degree ≠ 0) : L :=
classical.some $ exists_root_of_splits i hf hfd
theorem map_root_of_splits {f : polynomial K} (hf : f.splits i) (hfd) :
f.eval₂ i (root_of_splits i hf hfd) = 0 :=
classical.some_spec $ exists_root_of_splits i hf hfd
theorem roots_map {f : polynomial K} (hf : f.splits $ ring_hom.id K) :
(f.map i).roots = (f.roots).map i :=
if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else
have hmf0 : f.map i ≠ 0 := map_ne_zero hf0,
let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in
have h1 : (0 : polynomial K) ∉ m.map (λ r, X - C r),
from zero_nmem_multiset_map_X_sub_C _ _,
have h2 : (0 : polynomial L) ∉ m.map (λ r, X - C (i r)),
from zero_nmem_multiset_map_X_sub_C _ _,
begin
rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢,
rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add,
map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C],
rw [roots_multiset_prod _ h2, multiset.bind_map,
roots_multiset_prod _ h1, multiset.bind_map],
simp_rw roots_X_sub_C,
rw [multiset.bind_cons, multiset.bind_zero, add_zero,
multiset.bind_cons, multiset.bind_zero, add_zero, multiset.map_id']
end
lemma eq_prod_roots_of_splits {p : polynomial K} {i : K →+* L}
(hsplit : splits i p) :
p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod :=
begin
by_cases p_eq_zero : p = 0,
{ rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] },
obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit,
have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero),
have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 :=
by rwa hs at map_ne_zero,
have zero_nmem : (0 : polynomial L) ∉ s.map (λ a, X - C a),
from zero_nmem_multiset_map_X_sub_C _ _,
have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s,
{ refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _,
intros a s ih,
rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C,
multiset.cons_add, zero_add] },
rw [hs, roots_mul prod_ne_zero, roots_C, zero_add,
roots_multiset_prod _ zero_nmem,
map_bind_roots_eq]
end
lemma eq_prod_roots_of_splits_id {p : polynomial K}
(hsplit : splits (ring_hom.id K) p) :
p = C (p.leading_coeff) * (p.roots.map (λ a, X - C a)).prod :=
by simpa using eq_prod_roots_of_splits hsplit
lemma eq_prod_roots_of_monic_of_splits_id {p : polynomial K}
(m : monic p) (hsplit : splits (ring_hom.id K) p) :
p = (p.roots.map (λ a, X - C a)).prod :=
begin
convert eq_prod_roots_of_splits_id hsplit,
simp [m],
end
lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : polynomial K} (h_splits : splits i h)
(h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) :=
begin
apply polynomial.map_injective _ i.injective,
rw [eq_prod_roots_of_splits h_splits, h_roots],
simp,
end
lemma nat_degree_eq_card_roots {p : polynomial K} {i : K →+* L}
(hsplit : splits i p) : p.nat_degree = (p.map i).roots.card :=
begin
by_cases p_eq_zero : p = 0,
{ rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] },
have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero),
rw eq_prod_roots_of_splits hsplit at map_ne_zero,
conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] },
have : (0 : polynomial L) ∉ (map i p).roots.map (λ a, X - C a),
from zero_nmem_multiset_map_X_sub_C _ _,
simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero),
nat_degree_multiset_prod _ this]
end
lemma degree_eq_card_roots {p : polynomial K} {i : K →+* L} (p_ne_zero : p ≠ 0)
(hsplit : splits i p) : p.degree = (p.map i).roots.card :=
by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit]
section UFD
local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid
local infix ` ~ᵤ ` : 50 := associated
open unique_factorization_monoid associates
lemma splits_of_exists_multiset {f : polynomial K} {s : multiset L}
(hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod) :
splits i f :=
if hf0 : f = 0 then or.inl hf0
else
or.inr $ λ p hp hdp,
have ht : multiset.rel associated
(factors (f.map i)) (s.map (λ a : L, (X : polynomial L) - C a)) :=
factors_unique
(λ p hp, irreducible_of_factor _ hp)
(λ p' m, begin
obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m,
exact irreducible_of_degree_eq_one (degree_X_sub_C _),
end)
(associated.symm $ calc _ ~ᵤ f.map i :
⟨(units.map C.to_monoid_hom : units L →* units (polynomial L))
(units.mk0 (f.map i).leading_coeff
(mt leading_coeff_eq_zero.1 (map_ne_zero hf0))),
by conv_rhs { rw [hs, ← leading_coeff_map i, mul_comm] }; refl⟩
... ~ᵤ _ : associated.symm (unique_factorization_monoid.factors_prod (by simpa using hf0))),
let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in
let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in
let ⟨a, ha⟩ := multiset.mem_map.1 hq' in
by rw [← degree_X_sub_C a, ha.2];
exact degree_eq_degree_of_associated (hpq.trans hqq')
lemma splits_of_splits_id {f : polynomial K} : splits (ring_hom.id _) f → splits i f :=
unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _)
(λ _ hu _, splits_of_degree_le_one _
((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial))
(λ a p ha0 hp ih hfi, splits_mul _
(splits_of_degree_eq_one _
((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left
hp.1 (irreducible_of_prime hp) (by rw map_id)))
(ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2))
end UFD
lemma splits_iff_exists_multiset {f : polynomial K} : splits i f ↔
∃ (s : multiset L), f.map i = C (i f.leading_coeff) *
(s.map (λ a : L, (X : polynomial L) - C a)).prod :=
⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩
lemma splits_comp_of_splits (j : L →+* F) {f : polynomial K}
(h : splits i f) : splits (j.comp i) f :=
begin
change i with ((ring_hom.id _).comp i) at h,
rw [← splits_map_iff],
rw [← splits_map_iff i] at h,
exact splits_of_splits_id _ h
end
/-- A monic polynomial `p` that has as many roots as its degree
can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/
lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial K}
(hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) :
(multiset.map (λ (a : K), X - C a) p.roots).prod = p :=
begin
have hprodmonic : (multiset.map (λ (a : K), X - C a) p.roots).prod.monic,
{ simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic),
monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] },
have hdegree : (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree = p.nat_degree,
{ rw [← hroots, nat_degree_multiset_prod _ (zero_nmem_multiset_map_X_sub_C _ (λ a : K, a))],
simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat,
multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map] },
obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p,
have qzero : q ≠ 0,
{ rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq },
have degp :
p.nat_degree = (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree + q.nat_degree,
{ nth_rewrite 0 [hq],
simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] },
have degq : q.nat_degree = 0,
{ rw hdegree at degp,
exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm },
obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq),
have hassoc : associated (multiset.map (λ (a : K), X - C a) p.roots).prod p,
{ rw associated, use u, rw [hu, ← hq] },
exact eq_of_monic_of_associated hprodmonic hmonic hassoc
end
/-- A polynomial `p` that has as many roots as its degree
can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/
lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial K}
(hroots : p.roots.card = p.nat_degree) :
(C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p :=
begin
by_cases hzero : p = 0,
{ rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], },
{ have hcoeff : p.leading_coeff ≠ 0,
{ intro h, exact hzero (leading_coeff_eq_zero.1 h) },
have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree,
{ rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots,
coe_norm_unit, nat_degree_C, add_zero], },
have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero)
hrootsnorm,
rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod,
calc (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod
= p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) :
by rw [hprod, mul_comm, mul_assoc, ← C_mul]
... = p * C 1 : by field_simp
... = p : by simp only [mul_one, ring_hom.map_one], },
end
/-- A polynomial splits if and only if it has as many roots as its degree. -/
lemma splits_iff_card_roots {p : polynomial K} :
splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree :=
begin
split,
{ intro H, rw [nat_degree_eq_card_roots H, map_id] },
{ intro hroots,
apply (splits_iff_exists_multiset (ring_hom.id K)).2,
use p.roots,
simp only [ring_hom.id_apply, map_id],
exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm },
end
end splits
end polynomial
section embeddings
variables (F) [field F]
/-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/
def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly
{R : Type*} [comm_ring R] [algebra F R] (x : R) :
algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) :=
alg_equiv.symm $ alg_equiv.of_bijective
(alg_hom.cod_restrict
(adjoin_root.lift_hom _ x $ minpoly.aeval F x) _
(λ p, adjoin_root.induction_on _ p $ λ p,
(algebra.adjoin_singleton_eq_range F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩))
⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p,
adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $
ideal.mem_span_singleton.2 $ minpoly.dvd F x hp,
λ y,
let ⟨p, hp⟩ := (set_like.ext_iff.1 (algebra.adjoin_singleton_eq_range F x) (y : R)).1 y.2 in
⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩
open finset
/-- If a `subalgebra` is finite_dimensional as a submodule then it is `finite_dimensional`. -/
lemma finite_dimensional.of_subalgebra_to_submodule
{K V : Type*} [field K] [ring V] [algebra K V] {s : subalgebra K V}
(h : finite_dimensional K s.to_submodule) : finite_dimensional K s := h
/-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that
the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/
theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L]
[algebra F K] [algebra F L] (s : finset K) :
(∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) →
nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) :=
begin
refine finset.induction_on s (λ H, _) (λ a s has ih H, _),
{ rw [coe_empty, algebra.adjoin_empty],
exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ },
rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f,
choose H3 H4 using H3,
rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union_eq_under],
letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra,
haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := (
(submodule.fg_iff_finite_dimensional _).1
(fg_adjoin_of_finite (set.finite_mem_finset s) H3)).of_subalgebra_to_submodule,
letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)),
have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1,
have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits
(algebra_map (algebra.adjoin F (↑s : set K)) L),
{ refine polynomial.splits_of_splits_of_dvd _
(polynomial.map_ne_zero $ minpoly.ne_zero H1 :
polynomial.map (algebra_map _ _) _ ≠ 0)
((polynomial.splits_map_iff _ _).2 _)
(minpoly.dvd _ _ _),
{ rw ← is_scalar_tower.algebra_map_eq, exact H2 },
{ rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } },
obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm,
refine ⟨subalgebra.of_under _ _ _⟩,
refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _,
exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a
end
end embeddings
namespace polynomial
variables [field K] [field L] [field F]
open polynomial
section splitting_field
/-- Non-computably choose an irreducible factor from a polynomial. -/
def factor (f : polynomial K) : polynomial K :=
if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X
instance irreducible_factor (f : polynomial K) : irreducible (factor f) :=
begin
rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X }
end
theorem factor_dvd_of_not_is_unit {f : polynomial K} (hf1 : ¬is_unit f) : factor f ∣ f :=
begin
by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ },
rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)],
exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2
end
theorem factor_dvd_of_degree_ne_zero {f : polynomial K} (hf : f.degree ≠ 0) : factor f ∣ f :=
factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf)
theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial K} (hf : f.nat_degree ≠ 0) :
factor f ∣ f :=
factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf)
/-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/
def remove_factor (f : polynomial K) : polynomial (adjoin_root $ factor f) :=
map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor))
theorem X_sub_C_mul_remove_factor (f : polynomial K) (hf : f.nat_degree ≠ 0) :
(X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f :=
let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in
mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg,
adjoin_root.eval₂_root, zero_mul]
theorem nat_degree_remove_factor (f : polynomial K) :
f.remove_factor.nat_degree = f.nat_degree - 1 :=
by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map,
nat_degree_X_sub_C]
theorem nat_degree_remove_factor' {f : polynomial K} {n : ℕ} (hfn : f.nat_degree = n+1) :
f.remove_factor.nat_degree = n :=
by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel]
/-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/
def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : polynomial K),
f.nat_degree = n → Type u :=
nat.rec_on n (λ K _ _ _, K) $ λ n ih K _ f hf, by exactI
ih f.remove_factor (nat_degree_remove_factor' hf)
namespace splitting_field_aux
theorem succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) :
splitting_field_aux (n+1) f hfn =
splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl
instance field (n : ℕ) : Π {K : Type u} [field K], by exactI
Π {f : polynomial K} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) :=
nat.rec_on n (λ K _ _ _, ‹field K›) $ λ n ih K _ f hf, ih _
instance inhabited {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n) :
inhabited (splitting_field_aux n f hfn) := ⟨37⟩
instance algebra (n : ℕ) : Π {K : Type u} [field K], by exactI
Π {f : polynomial K} (hfn : f.nat_degree = n), algebra K (splitting_field_aux n f hfn) :=
nat.rec_on n (λ K _ _ _, by exactI algebra.id K) $ λ n ih K _ f hfn,
by exactI @@restrict_scalars.algebra _ _ _ _ _ (ih _) _ _
instance algebra' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) :
algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) :=
splitting_field_aux.algebra n _
instance algebra'' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) :
algebra K (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
splitting_field_aux.algebra (n+1) hfn
instance algebra''' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) :
algebra (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
splitting_field_aux.algebra n _
instance scalar_tower {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) :
is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux _ _ hfn) :=
is_scalar_tower.of_algebra_map_eq $ λ x, rfl
instance scalar_tower' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) :
is_scalar_tower K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
is_scalar_tower.of_algebra_map_eq $ λ x, rfl
theorem algebra_map_succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) :
by exact algebra_map K (splitting_field_aux _ _ hfn) =
(algebra_map (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp
(adjoin_root.of f.factor) :=
rfl
protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI
∀ (f : polynomial K) (hfn : f.nat_degree = n),
splits (algebra_map K $ splitting_field_aux n f hfn) f :=
nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _
(le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf,
by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits,
← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })],
exact splits_mul _ (splits_X_sub_C _) (ih _ _) }
theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI
∀ (f : polynomial K) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI
∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* L,
k.comp (algebra_map _ _) = j :=
nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI
have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf },
have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl },
let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj
(factor_dvd_of_nat_degree_ne_zero hndf))
(mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in
have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0,
have hsf : splits (adjoin_root.lift j r hr) f.remove_factor,
by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2,
rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of,
splits_id_iff_splits] },
let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in
⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩
theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI
∀ (f : polynomial K) (hfn : f.nat_degree = n),
algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f hfn).roots.to_finset :
set (splitting_field_aux n f hfn)) = ⊤ :=
nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $
λ n ih K _ f hfn, by exactI
have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn },
have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl },
have hmf0 : map (algebra_map K (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0,
by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢,
rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union,
multiset.to_finset_cons, multiset.to_finset_zero, insert_emptyc_eq, finset.coe_singleton,
algebra.adjoin_union_eq_under, ← set.image_singleton,
algebra.adjoin_algebra_map K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)),
adjoin_root.adjoin_root_eq_top, algebra.map_top,
is_scalar_tower.range_under_adjoin K (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)),
ih, subalgebra.res_top] }
end splitting_field_aux
/-- A splitting field of a polynomial. -/
def splitting_field (f : polynomial K) :=
splitting_field_aux _ f rfl
namespace splitting_field
variables (f : polynomial K)
instance : field (splitting_field f) :=
splitting_field_aux.field _ _
instance inhabited : inhabited (splitting_field f) := ⟨37⟩
instance : algebra K (splitting_field f) :=
splitting_field_aux.algebra _ _
protected theorem splits : splits (algebra_map K (splitting_field f)) f :=
splitting_field_aux.splits _ _ _
variables [algebra K L] (hb : splits (algebra_map K L) f)
/-- Embeds the splitting field into any other field that splits the polynomial. -/
def lift : splitting_field f →ₐ[K] L :=
{ commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb),
exact ring_hom.ext_iff.1 this r },
.. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) }
theorem adjoin_roots : algebra.adjoin K
(↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ :=
splitting_field_aux.adjoin_roots _ _ _
theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ :=
adjoin_roots f
end splitting_field
variables (K L) [algebra K L]
/-- Typeclass characterising splitting fields. -/
class is_splitting_field (f : polynomial K) : Prop :=
(splits [] : splits (algebra_map K L) f)
(adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤)
namespace is_splitting_field
variables {K}
instance splitting_field (f : polynomial K) : is_splitting_field K (splitting_field f) f :=
⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩
section scalar_tower
variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L]
variables {K}
instance map (f : polynomial F) [is_splitting_field F L f] :
is_splitting_field K L (f.map $ algebra_map F K) :=
⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f },
subalgebra.res_inj F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.res_top,
eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff],
exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩
variables {K} (L)
theorem splits_iff (f : polynomial K) [is_splitting_field K L f] :
polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ :=
⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸
algebra.adjoin_le_iff.2 (λ y hy,
let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in
hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _),
λ h, @ring_equiv.to_ring_hom_refl K _ ▸
ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸
by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩
theorem mul (f g : polynomial F) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f]
[is_splitting_field K L (g.map $ algebra_map F K)] :
is_splitting_field F L (f * g) :=
⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _
(splits_comp_of_splits _ _ (splits K f))
((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)),
by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0)
(map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_under,
is_scalar_tower.algebra_map_eq F K L, ← map_map,
roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f),
multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots,
algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots,
subalgebra.res_top]⟩
end scalar_tower
/-- Splitting field of `f` embeds into any field that splits `f`. -/
def lift [algebra K F] (f : polynomial K) [is_splitting_field K L f]
(hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F :=
if hf0 : f = 0 then (algebra.of_id K F).comp $
(algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $
by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _),
exact algebra.to_top } else
alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy,
have aeval y f = 0, from (eval₂_eq_eval_map _).trans $
(mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy),
⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩,
splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) })
algebra.to_top
theorem finite_dimensional (f : polynomial K) [is_splitting_field K L f] : finite_dimensional K L :=
is_noetherian.iff_fg.2 ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸
fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy,
if hf : f = 0
then by { rw [hf, map_zero, roots_zero] at hy, cases hy }
else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $
(mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩
instance (f : polynomial K) : _root_.finite_dimensional K f.splitting_field :=
finite_dimensional f.splitting_field f
/-- Any splitting field is isomorphic to `splitting_field f`. -/
def alg_equiv (f : polynomial K) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f :=
begin
refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f)
⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩,
haveI := finite_dimensional (splitting_field f) f,
haveI := finite_dimensional L f,
have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) :=
le_antisymm
(linear_map.finrank_le_finrank_of_injective
(show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from
ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field)))
(linear_map.finrank_le_finrank_of_injective
(show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from
ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))),
change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map,
refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _,
exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field)
end
end is_splitting_field
end splitting_field
end polynomial
|
4378011234e2795be81d27cfaa9e17af1e4cf0e8 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/matrix/hadamard.lean | b9e476dc644949ba0106a01ef4a50c3a05821ab4 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,429 | lean | /-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import data.matrix.notation
import linear_algebra.matrix.trace
/-!
# Hadamard product of matrices
This file defines the Hadamard product `matrix.hadamard`
and contains basic properties about them.
## Main definition
- `matrix.hadamard`: defines the Hadamard product,
which is the pointwise product of two matrices of the same size.
## Notation
* `⊙`: the Hadamard product `matrix.hadamard`;
## References
* <https://en.wikipedia.org/wiki/hadamard_product_(matrices)>
## Tags
hadamard product, hadamard
-/
variables {α β γ m n : Type*}
variables {R : Type*}
namespace matrix
open_locale matrix big_operators
/-- `matrix.hadamard` defines the Hadamard product,
which is the pointwise product of two matrices of the same size.-/
@[simp]
def hadamard [has_mul α] (A : matrix m n α) (B : matrix m n α) : matrix m n α
| i j := A i j * B i j
localized "infix ` ⊙ `:100 := matrix.hadamard" in matrix
section basic_properties
variables (A : matrix m n α) (B : matrix m n α) (C : matrix m n α)
/- commutativity -/
lemma hadamard_comm [comm_semigroup α] : A ⊙ B = B ⊙ A :=
ext $ λ _ _, mul_comm _ _
/- associativity -/
lemma hadamard_assoc [semigroup α] : A ⊙ B ⊙ C = A ⊙ (B ⊙ C) :=
ext $ λ _ _, mul_assoc _ _ _
/- distributivity -/
lemma hadamard_add [distrib α] : A ⊙ (B + C) = A ⊙ B + A ⊙ C :=
ext $ λ _ _, left_distrib _ _ _
lemma add_hadamard [distrib α] : (B + C) ⊙ A = B ⊙ A + C ⊙ A :=
ext $ λ _ _, right_distrib _ _ _
/- scalar multiplication -/
section scalar
@[simp] lemma smul_hadamard [has_mul α] [has_scalar R α] [is_scalar_tower R α α] (k : R) :
(k • A) ⊙ B = k • A ⊙ B :=
ext $ λ _ _, smul_mul_assoc _ _ _
@[simp] lemma hadamard_smul [has_mul α] [has_scalar R α] [smul_comm_class R α α] (k : R):
A ⊙ (k • B) = k • A ⊙ B :=
ext $ λ _ _, mul_smul_comm _ _ _
end scalar
section zero
variables [mul_zero_class α]
@[simp] lemma hadamard_zero : A ⊙ (0 : matrix m n α) = 0 :=
ext $ λ _ _, mul_zero _
@[simp] lemma zero_hadamard : (0 : matrix m n α) ⊙ A = 0 :=
ext $ λ _ _, zero_mul _
end zero
section one
variables [decidable_eq n] [mul_zero_one_class α]
variables (M : matrix n n α)
lemma hadamard_one : M ⊙ (1 : matrix n n α) = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
lemma one_hadamard : (1 : matrix n n α) ⊙ M = diagonal (λ i, M i i) :=
by { ext, by_cases h : i = j; simp [h] }
end one
section diagonal
variables [decidable_eq n] [mul_zero_class α]
lemma diagonal_hadamard_diagonal (v : n → α) (w : n → α) :
diagonal v ⊙ diagonal w = diagonal (v * w) :=
ext $ λ _ _, (apply_ite2 _ _ _ _ _ _).trans (congr_arg _ $ zero_mul 0)
end diagonal
section trace
variables [fintype m] [fintype n]
variables (R) [semiring α] [semiring R] [module R α]
lemma sum_hadamard_eq : ∑ (i : m) (j : n), (A ⊙ B) i j = trace m R α (A ⬝ Bᵀ) :=
rfl
lemma dot_product_vec_mul_hadamard [decidable_eq m] [decidable_eq n] (v : m → α) (w : n → α) :
dot_product (vec_mul v (A ⊙ B)) w = trace m R α (diagonal v ⬝ A ⬝ (B ⬝ diagonal w)ᵀ) :=
begin
rw [←sum_hadamard_eq, finset.sum_comm],
simp [dot_product, vec_mul, finset.sum_mul, mul_assoc],
end
end trace
end basic_properties
end matrix
|
6e0cbf30ae724c36e8ea51c90b5059eb32e0cf59 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/equiv/ring.lean | 63f1a46e70dcdb886ea2e5a05661e6390d593111 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,960 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import data.equiv.mul_add
import algebra.field
import algebra.opposites
/-!
# (Semi)ring equivs
In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an
isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the
corresponding group of automorphisms `ring_aut`.
## Notations
* ``infix ` ≃+* `:25 := ring_equiv``
The extended equiv have coercions to functions, and the coercion is the canonical notation when
treating the isomorphism as maps.
## Implementation notes
The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are
deprecated.
Definition of multiplication in the groups of automorphisms agrees with function composition,
multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
variables {R : Type*} {S : Type*} {S' : Type*}
set_option old_structure_cmd true
/-- An equivalence between two (semi)rings that preserves the algebraic structure. -/
structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S]
extends R ≃ S, R ≃* S, R ≃+ S
infix ` ≃+* `:25 := ring_equiv
/-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_equiv
/-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_add_equiv
/-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_mul_equiv
namespace ring_equiv
section basic
variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S']
instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩
@[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl
/-- A ring isomorphism preserves multiplication. -/
@[simp] lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := e.map_mul' x y
/-- A ring isomorphism preserves addition. -/
@[simp] lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := e.map_add' x y
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
@[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) :
⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl
@[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) :
(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl
protected lemma congr_arg {f : R ≃+* S} : Π {x x' : R}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := h ▸ rfl
lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩
instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩
lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl
lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl
@[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl
@[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl
/-- The `ring_equiv` between two semirings with a unique element. -/
def ring_equiv_of_unique_of_unique {M N}
[unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N :=
{ ..add_equiv.add_equiv_of_unique_of_unique,
..mul_equiv.mul_equiv_of_unique_of_unique}
instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] :
unique (M ≃+* N) :=
{ default := ring_equiv_of_unique_of_unique,
uniq := λ _, ext $ λ x, subsingleton.elim _ _ }
variable (R)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R }
@[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl
@[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl
@[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl
instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩
variables {R}
/-- The inverse of a ring isomorphism is a ring isomorphism. -/
@[symm] protected def symm (e : R ≃+* S) : S ≃+* R :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : R ≃+* S) : S → R := e.symm
initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl
lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) :=
equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) :
(ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) :
(mk f g h₁ h₂ h₃ h₄).symm =
{ to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
@[simp] lemma trans_apply (e₁ : R ≃+* S) (e₂ : S ≃+* S') (a : R) :
e₁.trans e₂ a = e₂ (e₁ a) := rfl
protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective
protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective
protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective
@[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
end basic
section comm_semiring
open opposite
variables (R) [comm_semiring R]
/-- A commutative ring is isomorphic to its opposite. -/
def to_opposite : R ≃+* Rᵒᵖ :=
{ map_add' := λ x y, rfl,
map_mul' := λ x y, mul_comm (op y) (op x),
..equiv_to_opposite }
@[simp]
lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl
@[simp]
lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl
end comm_semiring
section semiring
variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R)
/-- A ring isomorphism sends one to one. -/
@[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one
/-- A ring isomorphism sends zero to zero. -/
@[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero
variable {x}
@[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff
@[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff
lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff
lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff
/-- Produce a ring isomorphism from a bijective ring homomorphism. -/
noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S :=
{ .. equiv.of_bijective f hf, .. f }
end semiring
section
variables [ring R] [ring S] (f : R ≃+* S) (x y : R)
@[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x
@[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end
section semiring_hom
variables [semiring R] [semiring S] [semiring S']
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : R ≃+* S) : R →+* S :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) :=
λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h)
instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩
lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl
lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) :
f = g ↔ (f : R →+* S) = g :=
⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom
/-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/
lemma to_add_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_add_monoid_hom = (f : R ≃+ S).to_add_monoid_hom :=
rfl
/-- The two paths coercion can take to an `monoid_hom` are equivalent -/
lemma to_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_monoid_hom = (f : R ≃* S).to_monoid_hom :=
rfl
/-- The two paths coercion can take to an `equiv` are equivalent -/
lemma to_equiv_commutes (f : R ≃+* S) :
(f : R ≃+ S).to_equiv = (f : R ≃* S).to_equiv :=
rfl
@[simp]
lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl
@[simp]
lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl
@[simp]
lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) :
∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) :
∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
@[simp]
lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl
@[simp]
lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) :
e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
@[simp]
lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) :
e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
/--
Construct an equivalence of rings from homomorphisms in both directions, which are inverses.
-/
def of_hom_inv (hom : R →+* S) (inv : S →+* R)
(hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) :
R ≃+* S :=
{ inv_fun := inv,
left_inv := λ x, ring_hom.congr_fun hom_inv_id x,
right_inv := λ x, ring_hom.congr_fun inv_hom_id x,
..hom }
@[simp]
lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) :
(of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl
@[simp]
lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) :
(of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl
end semiring_hom
end ring_equiv
namespace mul_equiv
/-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/
def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S :=
{..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H }
end mul_equiv
namespace ring_equiv
variables [has_add R] [has_add S] [has_mul R] [has_mul S]
@[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3
@[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B]
(hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A :=
{ mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa,
eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy,
have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero],
(hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx)
(λ hy, by simpa using congr_arg e.symm hy),
exists_pair_ne := ⟨e.symm 0, e.symm 1,
by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ }
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B]
(e : A ≃+* B) : integral_domain A :=
{ .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) }
end ring_equiv
namespace equiv
variables (K : Type*) [division_ring K]
/-- In a division ring `K`, the unit group `units K`
is equivalent to the subtype of nonzero elements. -/
-- TODO: this might already exist elsewhere for `group_with_zero`
-- deduplicate or generalize
def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} :=
⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩
variable {K}
@[simp]
lemma coe_units_equiv_ne_zero (a : units K) :
((units_equiv_ne_zero K a) : K) = a := rfl
end equiv
|
11d63537fbf9c1d4d7613191f04556d9bebfd151 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/PreDefinition/Structural/BRecOn.lean | 2fc755fd4f4276c7313050f5a2d59b3c9bd3e1b3 | [
"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 | 12,104 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.HasConstCache
import Lean.Meta.CasesOn
import Lean.Meta.Match.Match
import Lean.Elab.RecAppSyntax
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab.Structural
open Meta
private def throwToBelowFailed : MetaM α :=
throwError "toBelow failed"
/-- See `toBelow` -/
private partial def toBelowAux (C : Expr) (belowDict : Expr) (arg : Expr) (F : Expr) : MetaM Expr := do
let belowDict ← whnf belowDict
trace[Elab.definition.structural] "belowDict: {belowDict}, arg: {arg}"
match belowDict with
| .app (.app (.const `PProd _) d1) d2 =>
(do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F]))
<|>
(do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F]))
| .app (.app (.const `And _) d1) d2 =>
(do toBelowAux C d1 arg (← mkAppM `And.left #[F]))
<|>
(do toBelowAux C d2 arg (← mkAppM `And.right #[F]))
| _ => forallTelescopeReducing belowDict fun xs belowDict => do
let arg ← zetaReduce arg
let argArgs := arg.getAppArgs
unless argArgs.size >= xs.size do throwToBelowFailed
let n := argArgs.size
let argTailArgs := argArgs.extract (n - xs.size) n
let belowDict := belowDict.replaceFVars xs argTailArgs
match belowDict with
| .app belowDictFun belowDictArg =>
unless belowDictFun.getAppFn == C do throwToBelowFailed
unless ← isDefEq belowDictArg arg do throwToBelowFailed
pure (mkAppN F argTailArgs)
| _ => throwToBelowFailed
/-- See `toBelow` -/
private def withBelowDict (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do
let belowType ← inferType below
trace[Elab.definition.structural] "belowType: {belowType}"
belowType.withApp fun f args => do
let motivePos := numIndParams + 1
unless motivePos < args.size do throwError "unexpected 'below' type{indentExpr belowType}"
let pre := mkAppN f (args.extract 0 numIndParams)
let preType ← inferType pre
forallBoundedTelescope preType (some 1) fun x _ => do
let motiveType ← inferType x[0]!
withLocalDeclD (← mkFreshUserName `C) motiveType fun C =>
let belowDict := mkApp pre C
let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size)
k C belowDict
/--
`below` is a free variable with type of the form `I.below indParams motive indices major`,
where `I` is the name of an inductive datatype.
For example, when trying to show that the following function terminates using structural recursion
```lean
def addAdjacent : List Nat → List Nat
| [] => []
| [a] => [a]
| a::b::as => (a+b) :: addAdjacent as
```
when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type
`@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)`
The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute.
So, we first replace it with a fresh variable `C` at `withBelowDict`.
Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary
of the "previous values".
We search this dictionary using the auxiliary function `toBelowAux`.
The dictionary is built using the `PProd` (`And` for inductive predicates).
We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/
private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do
withBelowDict below numIndParams fun C belowDict =>
toBelowAux C belowDict recArg below
/--
This method is used after `matcherApp.addArg arg` to check whether the new type of `arg` has been "refined/modified"
in at least one alternative.
-/
def refinedArgType (matcherApp : MatcherApp) (arg : Expr) : MetaM Bool := do
let argType ← inferType arg
(Array.zip matcherApp.alts matcherApp.altNumParams).anyM fun (alt, numParams) =>
lambdaTelescope alt fun xs _ => do
if xs.size >= numParams then
let refinedArg := xs[numParams - 1]!
return !(← isDefEq (← inferType refinedArg) argType)
else
return false
private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr :=
let containsRecFn (e : Expr) : StateRefT (HasConstCache recFnName) M Bool :=
modifyGet (·.contains e)
let rec loop (below : Expr) (e : Expr) : StateRefT (HasConstCache recFnName) M Expr := do
if !(← containsRecFn e) then
return e
match e with
| Expr.lam n d b c =>
withLocalDecl n c (← loop below d) fun x => do
mkLambdaFVars #[x] (← loop below (b.instantiate1 x))
| Expr.forallE n d b c =>
withLocalDecl n c (← loop below d) fun x => do
mkForallFVars #[x] (← loop below (b.instantiate1 x))
| Expr.letE n type val body _ =>
withLetDecl n (← loop below type) (← loop below val) fun x => do
mkLetFVars #[x] (← loop below (body.instantiate1 x)) (usedLetOnly := false)
| Expr.mdata d b =>
if let some _ := getRecAppSyntax? e then
loop below b
else
return mkMData d (← loop below b)
| Expr.proj n i e => return mkProj n i (← loop below e)
| Expr.app _ _ =>
let processApp (e : Expr) : StateRefT (HasConstCache recFnName) M Expr :=
e.withApp fun f args => do
if f.isConstOf recFnName then
let numFixed := recArgInfo.fixedParams.size
let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos
if recArgPos >= args.size then
throwError "insufficient number of parameters at recursive application {indentExpr e}"
let recArg := args[recArgPos]!
-- For reflexive type, we may have nested recursive applications in recArg
let recArg ← loop below recArg
let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError "failed to eliminate recursive application{indentExpr e}"
-- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them.
let argsNonFixed := args.extract numFixed args.size
-- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too.
let mut fArgs := #[]
for i in [:argsNonFixed.size] do
if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then
let arg := argsNonFixed[i]!
let arg ← replaceRecApps recFnName recArgInfo below arg
fArgs := fArgs.push arg
return mkAppN f fArgs
else
return mkAppN (← loop below f) (← args.mapM (loop below))
match (← matchMatcherApp? e) with
| some matcherApp =>
if !recArgHasLooseBVarsAt recFnName recArgInfo.recArgPos e then
processApp e
else
/- Here is an example we currently do not handle
```
def g (xs : List Nat) : Nat :=
match xs with
| [] => 0
| y::ys =>
match ys with
| [] => 1
| _::_::zs => g zs + 1
| zs => g ys + 2
```
We are matching on `ys`, but still using `ys` in the third alternative.
If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`.
To make it work, users have to write the third alternative as `| zs => g zs + 2`
If this is too annoying in practice, we may replace `ys` with the matching term, but
this may generate weird error messages, when it doesn't work. -/
trace[Elab.definition.structural] "below before matcherApp.addArg: {below} : {← inferType below}"
let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg)
if !(← refinedArgType matcherApp below) then
processApp e
else
let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) =>
lambdaTelescope alt fun xs altBody => do
trace[Elab.definition.structural] "altNumParams: {numParams}, xs: {xs}"
unless xs.size >= numParams do
throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}"
let belowForAlt := xs[numParams - 1]!
mkLambdaFVars xs (← loop belowForAlt altBody)
pure { matcherApp with alts := altsNew }.toExpr
| none =>
match (← toCasesOnApp? e) with
| some casesOnApp =>
if !recArgHasLooseBVarsAt recFnName recArgInfo.recArgPos e then
processApp e
else if let some casesOnApp ← casesOnApp.addArg? below (checkIfRefined := true) then
let altsNew ← (Array.zip casesOnApp.alts casesOnApp.altNumParams).mapM fun (alt, numParams) =>
lambdaTelescope alt fun xs altBody => do
unless xs.size >= numParams do
throwError "unexpected `casesOn` application alternative{indentExpr alt}\nat application{indentExpr e}"
let belowForAlt := xs[numParams]!
mkLambdaFVars xs (← loop belowForAlt altBody)
return { casesOnApp with alts := altsNew }.toExpr
else
processApp e
| none => processApp e
| e => ensureNoRecFn recFnName e
loop below e |>.run' {}
def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do
trace[Elab.definition.structural] "mkBRecOn: {value}"
let type := (← inferType value).headBeta
let major := recArgInfo.ys[recArgInfo.pos]!
let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y
trace[Elab.definition.structural] "fixedParams: {recArgInfo.fixedParams}, otherArgs: {otherArgs}"
let motive ← mkForallFVars otherArgs type
let mut brecOnUniv ← getLevel motive
trace[Elab.definition.structural] "brecOn univ: {brecOnUniv}"
let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero
if recArgInfo.reflexive && brecOnUniv != levelZero then
brecOnUniv ← decLevel brecOnUniv
let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive
trace[Elab.definition.structural] "brecOn motive: {motive}"
let brecOn :=
if useBInductionOn then
Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels
else
Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels)
let brecOn := mkAppN brecOn recArgInfo.indParams
let brecOn := mkApp brecOn motive
let brecOn := mkAppN brecOn recArgInfo.indIndices
let brecOn := mkApp brecOn major
check brecOn
let brecOnType ← inferType brecOn
trace[Elab.definition.structural] "brecOn {brecOn}"
trace[Elab.definition.structural] "brecOnType {brecOnType}"
forallBoundedTelescope brecOnType (some 1) fun F _ => do
let F := F[0]!
let FType ← inferType F
trace[Elab.definition.structural] "FType: {FType}"
let FType ← instantiateForall FType recArgInfo.indIndices
let FType ← instantiateForall FType #[major]
forallBoundedTelescope FType (some 1) fun below _ => do
-- TODO: `below` user name is `f`, and it will make a global `f` to be pretty printed as `_root_.f` in error messages.
-- We should add an option to `forallBoundedTelescope` to ensure fresh names are used.
let below := below[0]!
let valueNew ← replaceRecApps recFnName recArgInfo below value
let Farg ← mkLambdaFVars (recArgInfo.indIndices ++ #[major, below] ++ otherArgs) valueNew
let brecOn := mkApp brecOn Farg
return mkAppN brecOn otherArgs
end Lean.Elab.Structural
|
0a7ad35b60f941386184f6237d2e3c720f981f04 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/init/hit.hlean | 4a6197c03af3b27d81457b1dd5d1e846bdc5fd65 | [
"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 | 3,288 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the primitive hits in Lean
-/
prelude
import .trunc .pathover
open is_trunc eq
/-
We take two higher inductive types (hits) as primitive notions in Lean. We define all other hits
in terms of these two hits. The hits which are primitive are
- n-truncation
- quotients (not truncated)
For each of the hits we add the following constants:
- the type formation
- the term and path constructors
- the dependent recursor
We add the computation rule for point constructors judgmentally to the kernel of Lean.
The computation rules for the path constructors are added (propositionally) as axioms
In this file we only define the dependent recursor. For the nondependent recursor and all other
uses of these hits, see the folder ../hit/
-/
constant trunc.{u} (n : ℕ₋₂) (A : Type.{u}) : Type.{u}
namespace trunc
constant tr {n : ℕ₋₂} {A : Type} (a : A) : trunc n A
constant is_trunc_trunc (n : ℕ₋₂) (A : Type) : is_trunc n (trunc n A)
attribute is_trunc_trunc [instance]
protected constant rec {n : ℕ₋₂} {A : Type} {P : trunc n A → Type}
[Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a)) : Πaa, P aa
protected definition rec_on [reducible] {n : ℕ₋₂} {A : Type}
{P : trunc n A → Type} (aa : trunc n A) [Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a))
: P aa :=
trunc.rec H aa
end trunc
constant quotient.{u v} {A : Type.{u}} (R : A → A → Type.{v}) : Type.{max u v}
namespace quotient
constant class_of {A : Type} (R : A → A → Type) (a : A) : quotient R
constant eq_of_rel {A : Type} (R : A → A → Type) ⦃a a' : A⦄ (H : R a a')
: class_of R a = class_of R a'
protected constant rec {A : Type} {R : A → A → Type} {P : quotient R → Type}
(Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel R H] Pc a')
(x : quotient R) : P x
protected definition rec_on [reducible] {A : Type} {R : A → A → Type} {P : quotient R → Type}
(x : quotient R) (Pc : Π(a : A), P (class_of R a))
(Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel R H] Pc a') : P x :=
quotient.rec Pc Pp x
end quotient
init_hits -- Initialize builtin computational rules for trunc and quotient
namespace trunc
definition rec_tr [reducible] {n : ℕ₋₂} {A : Type} {P : trunc n A → Type}
[Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a)) (a : A) : trunc.rec H (tr a) = H a :=
idp
end trunc
namespace quotient
definition rec_class_of {A : Type} {R : A → A → Type} {P : quotient R → Type}
(Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel R H] Pc a')
(a : A) : quotient.rec Pc Pp (class_of R a) = Pc a :=
idp
constant rec_eq_of_rel {A : Type} {R : A → A → Type} {P : quotient R → Type}
(Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel R H] Pc a')
{a a' : A} (H : R a a') : apd (quotient.rec Pc Pp) (eq_of_rel R H) = Pp H
end quotient
attribute quotient.class_of trunc.tr [constructor]
attribute quotient.rec_on trunc.rec_on [unfold 4]
|
879f275aa864c7c615ae2b5d9c9c5685b2df01ed | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Meta/WHNF.lean | faadca91fea32d7713da6a721c382132b22bb5da | [
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 36,868 | 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.Structure
import Lean.Util.Recognizers
import Lean.Meta.GetConst
import Lean.Meta.FunInfo
import Lean.Meta.Match.MatcherInfo
import Lean.Meta.Match.MatchPatternAttr
namespace Lean.Meta
-- ===========================
/-! # Smart unfolding support -/
-- ===========================
/--
Forward declaration. It is defined in the module `src/Lean/Elab/PreDefinition/Structural/Eqns.lean`.
It is possible to avoid this hack if we move `Structural.EqnInfo` and `Structural.eqnInfoExt`
to this module.
-/
@[extern "lean_get_structural_rec_arg_pos"]
opaque getStructuralRecArgPos? (declName : Name) : CoreM (Option Nat)
def smartUnfoldingSuffix := "_sunfold"
@[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name :=
Name.mkStr declName smartUnfoldingSuffix
def hasSmartUnfoldingDecl (env : Environment) (declName : Name) : Bool :=
env.contains (mkSmartUnfoldingNameFor declName)
register_builtin_option smartUnfolding : Bool := {
defValue := true
descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion"
}
/-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/
def markSmartUnfoldingMatch (e : Expr) : Expr :=
mkAnnotation `sunfoldMatch e
def smartUnfoldingMatch? (e : Expr) : Option Expr :=
annotation? `sunfoldMatch e
/-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/
def markSmartUnfoldingMatchAlt (e : Expr) : Expr :=
mkAnnotation `sunfoldMatchAlt e
def smartUnfoldingMatchAlt? (e : Expr) : Option Expr :=
annotation? `sunfoldMatchAlt e
-- ===========================
/-! # Helper methods -/
-- ===========================
def isAuxDef (constName : Name) : MetaM Bool := do
let env ← getEnv
return isAuxRecursor env constName || isNoConfusion env constName
@[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α :=
match e with
| Expr.const name lvls => do
let (some cinfo) ← getConst? name | failK ()
k cinfo lvls
| _ => failK ()
-- ===========================
/-! # Helper functions for reducing recursors -/
-- ===========================
private def getFirstCtor (d : Name) : MetaM (Option Name) := do
let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none
return some ctor
private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do
match type.getAppFn with
| Expr.const d lvls =>
let (some ctor) ← getFirstCtor d | pure none
return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams)
| _ =>
return none
private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule :=
match major.getAppFn with
| Expr.const fn _ => recVal.rules.find? fun r => r.ctor == fn
| _ => none
private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM Expr := do
let majorType ← inferType major
let majorType ← instantiateMVars (← whnf majorType)
let majorTypeI := majorType.getAppFn
if !majorTypeI.isConstOf recVal.getInduct then
return major
else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then
return major
else do
let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure major
let newType ← inferType newCtorApp
/- TODO: check whether changing reducibility to default hurts performance here.
We do that to make sure auxiliary `Eq.rec` introduced by the `match`-compiler
are reduced even when `TransparencyMode.reducible` (like in `simp`).
We use `withNewMCtxDepth` to make sure metavariables at `majorType` are not assigned.
For example, given `major : Eq ?x y`, we don't want to apply K by assigning `?x := y`.
-/
if (← withAtLeastTransparency TransparencyMode.default <| withNewMCtxDepth <| isDefEq majorType newType) then
return newCtorApp
else
return major
/--
Create the `i`th projection `major`. It tries to use the auto-generated projection functions if available. Otherwise falls back
to `Expr.proj`.
-/
def mkProjFn (ctorVal : ConstructorVal) (us : List Level) (params : Array Expr) (i : Nat) (major : Expr) : CoreM Expr := do
match getStructureInfo? (← getEnv) ctorVal.induct with
| none => return mkProj ctorVal.induct i major
| some info => match info.getProjFn? i with
| none => return mkProj ctorVal.induct i major
| some projFn => return mkApp (mkAppN (mkConst projFn us) params) major
/--
If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n`
\pre `inductName` is `C`.
If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/
private def toCtorWhenStructure (inductName : Name) (major : Expr) : MetaM Expr := do
unless (← useEtaStruct inductName) do
return major
let env ← getEnv
if !isStructureLike env inductName then
return major
else if let some _ := major.isConstructorApp? env then
return major
else
let majorType ← inferType major
let majorType ← instantiateMVars (← whnf majorType)
let majorTypeI := majorType.getAppFn
if !majorTypeI.isConstOf inductName then
return major
match majorType.getAppFn with
| Expr.const d us =>
if (← whnfD (← inferType majorType)) == mkSort levelZero then
return major -- We do not perform eta for propositions, see implementation in the kernel
else
let some ctorName ← getFirstCtor d | pure major
let ctorInfo ← getConstInfoCtor ctorName
let params := majorType.getAppArgs.shrink ctorInfo.numParams
let mut result := mkAppN (mkConst ctorName us) params
for i in [:ctorInfo.numFields] do
result := mkApp result (← mkProjFn ctorInfo us params i major)
return result
| _ => return major
/-- Auxiliary function for reducing recursor applications. -/
private def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let majorIdx := recVal.getMajorIdx
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩
let mut major ← whnf major
if recVal.k then
major ← toCtorWhenK recVal major
major := major.toCtorIfLit
major ← toCtorWhenStructure recVal.getInduct major
match getRecRuleFor recVal major with
| some rule =>
let majorArgs := major.getAppArgs
if recLvls.length != recVal.levelParams.length then
failK ()
else
let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls
-- Apply parameters, motives and minor premises from recursor application.
let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs
/- The number of parameters in the constructor is not necessarily
equal to the number of parameters in the recursor when we have
nested inductive types. -/
let nparams := majorArgs.size - rule.nfields
let rhs := mkAppRange rhs nparams majorArgs.size majorArgs
let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs
successK rhs
| none => failK ()
else
failK ()
-- ===========================
/-! # Helper functions for reducing Quot.lift and Quot.ind -/
-- ===========================
/-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/
private def reduceQuotRec (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α :=
let process (majorPos argPos : Nat) : MetaM α :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩
let major ← whnf major
match major with
| Expr.app (Expr.app (Expr.app (Expr.const majorFn _) _) _) majorArg => do
let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK ()
let f := recArgs[argPos]!
let r := mkApp f majorArg
let recArity := majorPos + 1
successK <| mkAppRange r recArity recArgs.size recArgs
| _ => failK ()
else
failK ()
match recVal.kind with
| QuotKind.lift => process 5 3
| QuotKind.ind => process 4 3
| _ => failK ()
-- ===========================
/-! # Helper function for extracting "stuck term" -/
-- ===========================
mutual
private partial def isRecStuck? (recVal : RecursorVal) (recArgs : Array Expr) : MetaM (Option MVarId) :=
if recVal.k then
-- TODO: improve this case
return none
else do
let majorIdx := recVal.getMajorIdx
if h : majorIdx < recArgs.size then do
let major := recArgs.get ⟨majorIdx, h⟩
let major ← whnf major
getStuckMVar? major
else
return none
private partial def isQuotRecStuck? (recVal : QuotVal) (recArgs : Array Expr) : MetaM (Option MVarId) :=
let process? (majorPos : Nat) : MetaM (Option MVarId) :=
if h : majorPos < recArgs.size then do
let major := recArgs.get ⟨majorPos, h⟩
let major ← whnf major
getStuckMVar? major
else
return none
match recVal.kind with
| QuotKind.lift => process? 5
| QuotKind.ind => process? 4
| _ => return none
/-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/
partial def getStuckMVar? (e : Expr) : MetaM (Option MVarId) := do
match e with
| .mdata _ e => getStuckMVar? e
| .proj _ _ e => getStuckMVar? (← whnf e)
| .mvar .. =>
let e ← instantiateMVars e
match e with
| .mvar mvarId => return some mvarId
| _ => getStuckMVar? e
| .app f .. =>
let f := f.getAppFn
match f with
| .mvar .. =>
let e ← instantiateMVars e
match e.getAppFn with
| .mvar mvarId => return some mvarId
| _ => getStuckMVar? e
| .const fName _ =>
match (← getConstNoEx? fName) with
| some <| .recInfo recVal => isRecStuck? recVal e.getAppArgs
| some <| .quotInfo recVal => isQuotRecStuck? recVal e.getAppArgs
| _ =>
unless e.hasExprMVar do return none
-- Projection function support
let some projInfo ← getProjectionFnInfo? fName | return none
-- This branch is relevant if `e` is a type class projection that is stuck because the instance has not been synthesized yet.
unless projInfo.fromClass do return none
let args := e.getAppArgs
-- First check whether `e`s instance is stuck.
if let some major := args.get? projInfo.numParams then
if let some mvarId ← getStuckMVar? major then
return mvarId
/-
Then, recurse on the explicit arguments
We want to detect the stuck instance in terms such as
`HAdd.hAdd Nat Nat Nat (instHAdd Nat instAddNat) n (OfNat.ofNat Nat 2 ?m)`
See issue https://github.com/leanprover/lean4/issues/1408 for an example where this is needed.
-/
let info ← getFunInfo f
for pinfo in info.paramInfo, arg in args do
if pinfo.isExplicit then
if let some mvarId ← getStuckMVar? arg then
return some mvarId
return none
| .proj _ _ e => getStuckMVar? (← whnf e)
| _ => return none
| _ => return none
end
-- ===========================
/-! # Weak Head Normal Form auxiliary combinators -/
-- ===========================
/-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/
@[specialize] partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do
match e with
| .forallE .. => return e
| .lam .. => return e
| .sort .. => return e
| .lit .. => return e
| .bvar .. => unreachable!
| .letE .. => k e
| .const .. => k e
| .app .. => k e
| .proj .. => k e
| .mdata _ e => whnfEasyCases e k
| .fvar fvarId =>
let decl ← fvarId.getDecl
match decl with
| .cdecl .. => return e
| .ldecl (value := v) (nonDep := nonDep) .. =>
let cfg ← getConfig
if nonDep && !cfg.zetaNonDep then
return e
else
if cfg.trackZeta then
modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId }
whnfEasyCases v k
| .mvar mvarId =>
match (← getExprMVarAssignment? mvarId) with
| some v => whnfEasyCases v k
| none => return e
@[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level)
(failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := do
if c.levelParams.length != lvls.length then
failK ()
else
successK (← instantiateValueLevelParams c lvls)
@[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr)
(failK : Unit → MetaM α) (successK : Expr → MetaM α) (preserveMData := false) : MetaM α := do
if c.levelParams.length != lvls.length then
failK ()
else
let val ← instantiateValueLevelParams c lvls
let val := val.betaRev revArgs (preserveMData := preserveMData)
successK val
inductive ReduceMatcherResult where
| reduced (val : Expr)
| stuck (val : Expr)
| notMatcher
| partialApp
/--
The "match" compiler uses `if-then-else` expressions and other auxiliary declarations to compile match-expressions such as
```
match v with
| 'a' => 1
| 'b' => 2
| _ => 3
```
because it is more efficient than using `casesOn` recursors.
The method `reduceMatcher?` fails if these auxiliary definitions (e.g., `ite`) cannot be unfolded in the current
transparency setting. This is problematic because tactics such as `simp` use `TransparencyMode.reducible`, and
most users assume that expressions such as
```
match 0 with
| 0 => 1
| 100 => 2
| _ => 3
```
should reduce in any transparency mode.
Thus, we define a custom `canUnfoldAtMatcher` predicate for `whnfMatcher`.
This solution is not very modular because modications at the `match` compiler require changes here.
We claim this is defensible because it is reducing the auxiliary declaration defined by the `match` compiler.
Alternative solution: tactics that use `TransparencyMode.reducible` should rely on the equations we generated for match-expressions.
This solution is also not perfect because the match-expression above will not reduce during type checking when we are not using
`TransparencyMode.default` or `TransparencyMode.all`.
-/
def canUnfoldAtMatcher (cfg : Config) (info : ConstantInfo) : CoreM Bool := do
match cfg.transparency with
| TransparencyMode.all => return true
| TransparencyMode.default => return true
| _ =>
if (← isReducible info.name) || isGlobalInstance (← getEnv) info.name then
return true
else if hasMatchPatternAttribute (← getEnv) info.name then
return true
else
return info.name == ``ite
|| info.name == ``dite
|| info.name == ``decEq
|| info.name == ``Nat.decEq
|| info.name == ``Char.ofNat || info.name == ``Char.ofNatAux
|| info.name == ``String.decEq || info.name == ``List.hasDecEq
|| info.name == ``Fin.ofNat
|| info.name == ``UInt8.ofNat || info.name == ``UInt8.decEq
|| info.name == ``UInt16.ofNat || info.name == ``UInt16.decEq
|| info.name == ``UInt32.ofNat || info.name == ``UInt32.decEq
|| info.name == ``UInt64.ofNat || info.name == ``UInt64.decEq
/- Remark: we need to unfold the following two definitions because they are used for `Fin`, and
lazy unfolding at `isDefEq` does not unfold projections. -/
|| info.name == ``HMod.hMod || info.name == ``Mod.mod
private def whnfMatcher (e : Expr) : MetaM Expr := do
/- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`,
we increase it to `TransparencyMode.instance`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`),
and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat α n inst`.
For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target.
TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior. -/
let mut transparency ← getTransparency
if transparency == TransparencyMode.reducible then
transparency := TransparencyMode.instances
withTransparency transparency <| withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do
whnf e
def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do
match e.getAppFn with
| Expr.const declName declLevels =>
let some info ← getMatcherInfo? declName
| return ReduceMatcherResult.notMatcher
let args := e.getAppArgs
let prefixSz := info.numParams + 1 + info.numDiscrs
if args.size < prefixSz + info.numAlts then
return ReduceMatcherResult.partialApp
else
let constInfo ← getConstInfo declName
let f ← instantiateValueLevelParams constInfo declLevels
let auxApp := mkAppN f args[0:prefixSz]
let auxAppType ← inferType auxApp
forallBoundedTelescope auxAppType info.numAlts fun hs _ => do
let auxApp ← whnfMatcher (mkAppN auxApp hs)
let auxAppFn := auxApp.getAppFn
let mut i := prefixSz
for h in hs do
if auxAppFn == h then
let result := mkAppN args[i]! auxApp.getAppArgs
let result := mkAppN result args[prefixSz + info.numAlts:args.size]
return ReduceMatcherResult.reduced result.headBeta
i := i + 1
return ReduceMatcherResult.stuck auxApp
| _ => pure ReduceMatcherResult.notMatcher
private def projectCore? (e : Expr) (i : Nat) : MetaM (Option Expr) := do
let e := e.toCtorIfLit
matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ =>
let numArgs := e.getAppNumArgs
let idx := ctorVal.numParams + i
if idx < numArgs then
return some (e.getArg! idx)
else
return none
def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do
projectCore? (← whnf e) i
/-- Reduce kernel projection `Expr.proj ..` expression. -/
def reduceProj? (e : Expr) : MetaM (Option Expr) := do
match e with
| Expr.proj _ i c => project? c i
| _ => return none
/--
Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned.
Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled".
-/
private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do
if f'.isMVar then
match (← getDelayedMVarAssignment? f'.mvarId!) with
| none => return none
| some { fvars, mvarIdPending } =>
let args := e.getAppArgs
if fvars.size > args.size then
-- Insufficient number of argument to expand delayed assignment
return none
else
let newVal ← instantiateMVars (mkMVar mvarIdPending)
if newVal.hasExprMVar then
-- Delayed assignment still contains metavariables
return none
else
let newVal := newVal.abstract fvars
let result := newVal.instantiateRevRange 0 fvars.size args
return mkAppRange result fvars.size args.size args
else
return none
/--
Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction,
expand let-expressions, expand assigned meta-variables.
The parameter `deltaAtProj` controls how to reduce projections `s.i`. If `deltaAtProj == true`,
then delta reduction is used to reduce `s` (i.e., `whnf` is used), otherwise `whnfCore`.
We only set this flag to `false` when implementing `isDefEq`.
If `simpleReduceOnly`, then `iota` and projection reduction are not performed.
Note that the value of `deltaAtProj` is irrelevant if `simpleReduceOnly = true`.
-/
partial def whnfCore (e : Expr) (deltaAtProj : Bool := true) (simpleReduceOnly := false) : MetaM Expr :=
go e
where
go (e : Expr) : MetaM Expr :=
whnfEasyCases e fun e => do
trace[Meta.whnf] e
match e with
| Expr.const .. => pure e
| Expr.letE _ _ v b _ => go <| b.instantiate1 v
| Expr.app f .. =>
let f := f.getAppFn
let f' ← go f
if f'.isLambda then
let revArgs := e.getAppRevArgs
go <| f'.betaRev revArgs
else if let some eNew ← whnfDelayedAssigned? f' e then
go eNew
else
let e := if f == f' then e else e.updateFn f'
if simpleReduceOnly then
return e
else
match (← reduceMatcher? e) with
| ReduceMatcherResult.reduced eNew => go eNew
| ReduceMatcherResult.partialApp => pure e
| ReduceMatcherResult.stuck _ => pure e
| ReduceMatcherResult.notMatcher =>
matchConstAux f' (fun _ => return e) fun cinfo lvls =>
match cinfo with
| ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) go
| ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) go
| c@(ConstantInfo.defnInfo _) => do
if (← isAuxDef c.name) then
deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) go
else
return e
| _ => return e
| Expr.proj _ i c =>
if simpleReduceOnly then
return e
else
let c ← if deltaAtProj then whnf c else whnfCore c
match (← projectCore? c i) with
| some e => go e
| none => return e
| _ => unreachable!
/--
Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldingMatch` (*) and `markSmartUnfoldingMatchAlt` (**).
For example, consider the following definition
```
def r (i j : Nat) : Nat :=
i +
match j with
| Nat.zero => 1
| Nat.succ j =>
i + match j with
| Nat.zero => 2
| Nat.succ j => r i j
```
produces the following `_sunfold` auxiliary definition with the markers
```
def r._sunfold (i j : Nat) : Nat :=
i +
(*) match j with
| Nat.zero => (**) 1
| Nat.succ j =>
i + (*) match j with
| Nat.zero => (**) 2
| Nat.succ j => (**) r i j
```
`match` expressions marked with `markSmartUnfoldingMatch` (*) must be reduced, otherwise the resulting term is not definitionally
equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached.
For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j`
-/
partial def smartUnfoldingReduce? (e : Expr) : MetaM (Option Expr) :=
go e |>.run
where
go (e : Expr) : OptionT MetaM Expr := do
match e with
| Expr.letE n t v b _ => withLetDecl n t (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x))
| Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← go b)
| Expr.app f a .. => return mkApp (← go f) (← go a)
| Expr.proj _ _ s => return e.updateProj! (← go s)
| Expr.mdata _ b =>
if let some m := smartUnfoldingMatch? e then
goMatch m
else
return e.updateMData! (← go b)
| _ => return e
goMatch (e : Expr) : OptionT MetaM Expr := do
match (← reduceMatcher? e) with
| ReduceMatcherResult.reduced e =>
if let some alt := smartUnfoldingMatchAlt? e then
return alt
else
go e
| ReduceMatcherResult.stuck e' =>
let mvarId ← getStuckMVar? e'
/- Try to "unstuck" by resolving pending TC problems -/
if (← Meta.synthPending mvarId) then
goMatch e
else
failure
| _ => failure
mutual
/--
Auxiliary method for unfolding a class projection.
-/
partial def unfoldProjInst? (e : Expr) : MetaM (Option Expr) := do
match e.getAppFn with
| Expr.const declName .. =>
match (← getProjectionFnInfo? declName) with
| some { fromClass := true, .. } =>
match (← withDefault <| unfoldDefinition? e) with
| none => return none
| some e =>
match (← withReducibleAndInstances <| reduceProj? e.getAppFn) with
| none => return none
| some r => return mkAppN r e.getAppArgs |>.headBeta
| _ => return none
| _ => return none
/--
Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`.
Recall that class instance projections are not marked with `[reducible]` because we want them to be
in "reducible canonical form".
-/
partial def unfoldProjInstWhenIntances? (e : Expr) : MetaM (Option Expr) := do
if (← getTransparency) != TransparencyMode.instances then
return none
else
unfoldProjInst? e
/-- Unfold definition using "smart unfolding" if possible. -/
partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app f _ =>
matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do
if fInfo.levelParams.length != fLvls.length then
return none
else
let unfoldDefault (_ : Unit) : MetaM (Option Expr) :=
if fInfo.hasValue then
deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))
else
return none
if smartUnfolding.get (← getOptions) then
match ((← getEnv).find? (mkSmartUnfoldingNameFor fInfo.name)) with
| some fAuxInfo@(ConstantInfo.defnInfo _) =>
-- We use `preserveMData := true` to make sure the smart unfolding annotation are not erased in an over-application.
deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (preserveMData := true) (fun _ => pure none) fun e₁ => do
let some r ← smartUnfoldingReduce? e₁ | return none
/-
If `smartUnfoldingReduce?` succeeds, we should still check whether the argument the
structural recursion is recursing on reduces to a constructor.
This extra check is necessary in definitions (see issue #1081) such as
```
inductive Vector (α : Type u) : Nat → Type u where
| nil : Vector α 0
| cons : α → Vector α n → Vector α (n+1)
def Vector.insert (a: α) (i : Fin (n+1)) (xs : Vector α n) : Vector α (n+1) :=
match i, xs with
| ⟨0, _⟩, xs => cons a xs
| ⟨i+1, h⟩, cons x xs => cons x (xs.insert a ⟨i, Nat.lt_of_succ_lt_succ h⟩)
```
The structural recursion is being performed using the vector `xs`. That is, we used `Vector.brecOn` to define
`Vector.insert`. Thus, an application `xs.insert a ⟨0, h⟩` is **not** definitionally equal to
`Vector.cons a xs` because `xs` is not a constructor application (the `Vector.brecOn` application is blocked).
Remark 1: performing structural recursion on `Fin (n+1)` is not an option here because it is a `Subtype` and
and the repacking in recursive applications confuses the structural recursion module.
Remark 2: the match expression reduces reduces to `cons a xs` when the discriminants are `⟨0, h⟩` and `xs`.
Remark 3: this check is unnecessary in most cases, but we don't need dependent elimination to trigger the issue fixed by this extra check. Here is another example that triggers the issue fixed by this check.
```
def f : Nat → Nat → Nat
| 0, y => y
| x+1, y+1 => f (x-2) y
| x+1, 0 => 0
theorem ex : f 0 y = y := rfl
```
Remark 4: the `return some r` in the following `let` is not a typo. Binport generated .olean files do not
store the position of recursive arguments for definitions using structural recursion.
Thus, we should keep `return some r` until Mathlib has been ported to Lean 3.
Note that the `Vector` example above does not even work in Lean 3.
-/
let some recArgPos ← getStructuralRecArgPos? fInfo.name | return some r
let numArgs := e.getAppNumArgs
if recArgPos >= numArgs then return none
let recArg := e.getArg! recArgPos numArgs
if !(← whnfMatcher recArg).isConstructorApp (← getEnv) then return none
return some r
| _ =>
if (← getMatcherInfo? fInfo.name).isSome then
-- Recall that `whnfCore` tries to reduce "matcher" applications.
return none
else
unfoldDefault ()
else
unfoldDefault ()
| Expr.const declName lvls => do
if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then
return none
else
let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? declName | pure none
deltaDefinition cinfo lvls
(fun _ => pure none)
(fun e => pure (some e))
| _ => return none
end
def unfoldDefinition (e : Expr) : MetaM Expr := do
let some e ← unfoldDefinition? e | throwError "failed to unfold definition{indentExpr e}"
return e
@[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr :=
whnfEasyCases e fun e => do
let e ← whnfCore e
if (← pred e) then
match (← unfoldDefinition? e) with
| some e => whnfHeadPred e pred
| none => return e
else
return e
def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do
let e ← whnfHeadPred e (fun e => return !e.isAppOf declName)
if e.isAppOf declName then
return e
else
return none
/-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/
def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do
if !e.isApp then
return none
else match (← reduceMatcher? e) with
| ReduceMatcherResult.reduced e => return e
| _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do
match cinfo with
| ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))
| ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))
| c@(ConstantInfo.defnInfo _) =>
if (← isAuxDef c.name) then
deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))
else
return none
| _ => return none
unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName
unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName
@[implemented_by reduceBoolNativeUnsafe] opaque reduceBoolNative (constName : Name) : MetaM Bool
@[implemented_by reduceNatNativeUnsafe] opaque reduceNatNative (constName : Name) : MetaM Nat
def reduceNative? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app (Expr.const fName _) (Expr.const argName _) =>
if fName == ``Lean.reduceBool then do
return toExpr (← reduceBoolNative argName)
else if fName == ``Lean.reduceNat then do
return toExpr (← reduceNatNative argName)
else
return none
| _ =>
return none
@[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do
let a ← whnf a
match a with
| Expr.const `Nat.zero _ => k 0
| Expr.lit (Literal.natVal v) => k v
| _ => return none
def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) :=
withNatValue a fun a =>
return mkRawNatLit <| f a
def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) :=
withNatValue a fun a =>
withNatValue b fun b => do
trace[Meta.isDefEq.whnf.reduceBinOp] "{a} op {b}"
return mkRawNatLit <| f a b
def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do
withNatValue a fun a =>
withNatValue b fun b =>
return toExpr <| f a b
def reduceNat? (e : Expr) : MetaM (Option Expr) :=
if e.hasFVar || e.hasMVar then
return none
else match e with
| Expr.app (Expr.const fn _) a =>
if fn == ``Nat.succ then
reduceUnaryNatOp Nat.succ a
else
return none
| Expr.app (Expr.app (Expr.const fn _) a1) a2 =>
if fn == ``Nat.add then reduceBinNatOp Nat.add a1 a2
else if fn == ``Nat.sub then reduceBinNatOp Nat.sub a1 a2
else if fn == ``Nat.mul then reduceBinNatOp Nat.mul a1 a2
else if fn == ``Nat.div then reduceBinNatOp Nat.div a1 a2
else if fn == ``Nat.mod then reduceBinNatOp Nat.mod a1 a2
else if fn == ``Nat.beq then reduceBinNatPred Nat.beq a1 a2
else if fn == ``Nat.ble then reduceBinNatPred Nat.ble a1 a2
else return none
| _ =>
return none
@[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do
-- We cache only closed terms without expr metavars.
-- Potential refinement: cache if `e` is not stuck at a metavariable
if e.hasFVar || e.hasExprMVar || (← read).canUnfold?.isSome then
return false
else
match (← getConfig).transparency with
| TransparencyMode.default => return true
| TransparencyMode.all => return true
| _ => return false
@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do
if useCache then
match (← getConfig).transparency with
| TransparencyMode.default => return (← get).cache.whnfDefault.find? e
| TransparencyMode.all => return (← get).cache.whnfAll.find? e
| _ => unreachable!
else
return none
private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do
if useCache then
match (← getConfig).transparency with
| TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r }
| TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r }
| _ => unreachable!
return r
@[export lean_whnf]
partial def whnfImp (e : Expr) : MetaM Expr :=
withIncRecDepth <| whnfEasyCases e fun e => do
checkMaxHeartbeats "whnf"
let useCache ← useWHNFCache e
match (← cached? useCache e) with
| some e' => pure e'
| none =>
let e' ← whnfCore e
match (← reduceNat? e') with
| some v => cache useCache e v
| none =>
match (← reduceNative? e') with
| some v => cache useCache e v
| none =>
match (← unfoldDefinition? e') with
| some e => whnfImp e
| none => cache useCache e e'
/-- If `e` is a projection function that satisfies `p`, then reduce it -/
def reduceProjOf? (e : Expr) (p : Name → Bool) : MetaM (Option Expr) := do
if !e.isApp then
pure none
else match e.getAppFn with
| Expr.const name .. => do
let env ← getEnv
match env.getProjectionStructureName? name with
| some structName =>
if p structName then
Meta.unfoldDefinition? e
else
pure none
| none => pure none
| _ => pure none
builtin_initialize
registerTraceClass `Meta.whnf
registerTraceClass `Meta.isDefEq.whnf.reduceBinOp
end Lean.Meta
|
f3c552c136a447ec68b54b932c4b321628a9e40c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/nat/periodic.lean | a5a14e738006c9cfc93a9f22d904c0498c1ecf1e | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 2,169 | lean | /-
Copyright (c) 2021 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey
-/
import algebra.periodic
import data.nat.count
import data.nat.interval
/-!
# Periodic Functions on ℕ
This file identifies a few functions on `ℕ` which are periodic, and also proves a lemma about
periodic predicates which helps determine their cardinality when filtering intervals over them.
-/
namespace nat
open nat function
lemma periodic_gcd (a : ℕ) : periodic (gcd a) a :=
by simp only [forall_const, gcd_add_self_right, eq_self_iff_true, periodic]
lemma periodic_coprime (a : ℕ) : periodic (coprime a) a :=
by simp only [coprime_add_self_right, forall_const, iff_self, eq_iff_iff, periodic]
lemma periodic_mod (a : ℕ) : periodic (λ n, n % a) a :=
by simp only [forall_const, eq_self_iff_true, add_mod_right, periodic]
lemma _root_.function.periodic.map_mod_nat {α : Type*} {f : ℕ → α} {a : ℕ} (hf : periodic f a) :
∀ n, f (n % a) = f n :=
λ n, by conv_rhs { rw [← nat.mod_add_div n a, mul_comm, ← nat.nsmul_eq_mul, hf.nsmul] }
section multiset
open multiset
/-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality
equal to the number naturals below `a` for which `p a` is true. -/
lemma filter_multiset_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p]
(pp : periodic p a) :
(filter p (Ico n (n+a))).card = a.count p :=
begin
rw [count_eq_card_filter_range, finset.card, finset.filter_val, finset.range_coe,
←multiset_Ico_map_mod n, ←map_count_true_eq_filter_card, ←map_count_true_eq_filter_card,
map_map, function.comp],
simp only [pp.map_mod_nat],
end
end multiset
section finset
open finset
/-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality
equal to the number naturals below `a` for which `p a` is true. -/
lemma filter_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p]
(pp : periodic p a) :
((Ico n (n + a)).filter p).card = a.count p :=
filter_multiset_Ico_card_eq_of_periodic n a p pp
end finset
end nat
|
926a35961459412449d42705cef7391a64ca6bf9 | 74d9d5f45c6ce5c4f2faf215c04a68eab55fe525 | /src/topological_manifold.lean | de2ded0dd72cd2f3944bb1f8417c44b2b95c1c6e | [] | no_license | joshpoll/differential_geometry | 290bb8a934ca3b3b6b707d810e6d4b941710b710 | 57e00a7e37b7c4c73c847429171ff63d3a48def5 | refs/heads/master | 1,584,551,626,391 | 1,527,747,643,000 | 1,527,747,643,000 | 135,014,993 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,618 | lean | -- An n-dimensional topological manifold is a second countable Hausdorff space that is locally Euclidean of dimension n.
import analysis.real
import analysis.topology.topological_space
import data.vector
import .homeos
open topological_space
universes u
-- ℝ^n
def euclidean_space (n : ℕ) := vector ℝ n
local notation `ℝ^`n := euclidean_space n
instance euclidean_topology (n : ℕ) : topological_space ℝ^n := sorry
-- Lean doesn't recognize this for some reason
-- instance nbhds_topology {α : Type u} [topological_space α] {a : α} (s ∈ (nhds a).sets) : topological_space s := sorry
-- set_option trace.class_instances true
-- TODO: need to show R^n has a topology
-- TODO: would like to write ∃ s ∈ (nhds a).sets, but then lean doesn't know that s has a topology
-- todo: manifold with boundary
-- a chart is a homeomorphism from an open set on a manifold to an open set in ℝ^n (along with the other terms needed for that to make sense)
-- TODO: prove a chart can be found at every point in a manifold
-- TODO: prove open subset of a manifold is also a manifold -/
-- def open_set (α : Type u) [topological_space α] := { s : set α // is_open s }
-- -- TODO: coerce to set
-- A chart is a pair of a coordinate neighborhood in α and a homeomorphism from that nbhd to ℝ^n. There are several other equivalent formulations.
-- TODO: not sure which codomain to choose. picking simpler definition for now, because no messy open set arguments (not yet at least). revisit
structure chart (α : Type u) (n : ℕ) [topological_space α] : Type u :=
(coord_domain : set α)
(coord_map : homeo coord_domain ℝ^n)
-- hack to get around Lean not realizing s has a topology if just use the predicate
def neighborhood {α : Type u} [topological_space α] (a : α) := { s : set α // s ∈ (nhds a).sets }
-- chart at a with dimension n
structure nbhd_chart {α : Type u} (a : α) (n : ℕ) [topological_space α] : Type u :=
(coord_nbhd : neighborhood a)
(coord_map : homeo coord_nbhd.1 ℝ^n)
-- TODO: coerce to chart?
class topological_manifold (α : Type u) (n : ℕ) extends
topological_space α,
second_countable_topology α,
t2_space α : Type u :=
(locally_euclidean_of_dim_n (a : α) : nbhd_chart a n)
-- could write: forall a, exists f : (nbhd a).sets -> R^n, is_homeo f
-- this seems not as good b/c we frequently use the charts and the functions so want to return those!!!
-- this is not the case for things like linear_map, continuous_linear_map, where all additional data are propositions. what about the derivative? seems like propositional data, but is it all that?
|
b133d28df9620081f5cb0565e147b190f34cdfd1 | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world3/level2.lean | af6cd4a331db46aaa2b86e2f1bf900fecc1bf9f3 | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 723 | lean | import game.world3.level1 -- hide
import mynat.mul -- hide
namespace mynat -- hide
/-
# Multiplication World
## Level 2: `mul_one`
Remember that you can see everything you have proved so far about multiplication in
the drop-down box on the left (and that this list will grow as we proceed).
In this level we'll need to use
* `one_eq_succ_zero : 1 = succ(0)`
which was mentioned back in Addition World and
which will be a useful thing to rewrite right now, as we
begin to prove a couple of lemmas about how `1` behaves
with respect to multiplication.
-/
/- Lemma
For any natural number $m$, we have
$$ m \times 1 = m. $$
-/
lemma mul_one (m : mynat) : m * 1 = m :=
begin [nat_num_game]
end
end mynat -- hide
|
6ba89b3d058ab964a41da0927236fedc27be5a83 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/496.lean | a4455b4898131bab08dd336f2d4b8f0ed4c69697 | [
"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 | 127 | lean | axiom F : Type
axiom foo : F
def foo' : F := foo
axiom bla : Nat
noncomputable def bla1 : Nat := id bla
def bla2 := id bla1
|
64f54d63fc34537e046113112481ea1d11696891 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/struct1.lean | fca26b6b346fa10df25eb2452e1f671f7254bdf4 | [
"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 | 1,004 | lean | new_frontend
structure A (α : Type) :=
(x : α)
structure B (α : Type) :=
(x : α)
structure S : Nat := -- error expected Type
(x : Nat)
structure S extends Nat → Nat := -- error expected structure
(x : Nat)
structure S extends A Nat, A Bool := -- error field toA already declared
(x : Nat)
structure S extends A Nat, B Bool := -- error field `x` from `B` has already been declared
(x : Nat)
structure S := -- error '_' is not allowed
(_x : Nat)
structure S := -- error '_' is not allowed
(x _y : Nat)
structure S :=
(x : Nat)
(x : Nat) -- error
structure S extends A Nat :=
(x : Nat) -- error
structure S extends A Nat :=
(x := true) -- error type mismatch
structure S extends A Nat :=
(x : Bool := true) -- error omit type
structure S :=
(x : Nat := true) -- error type mismatch
private structure S :=
private mk :: (x : Nat)
private structure S :=
protected mk :: (x : Nat)
private structure S :=
protected (x : Nat)
private structure S :=
mk2 :: (x : Nat)
#check S
#check S.mk2
|
8abc4a792156b6fcedcabaf0005045a3e65b78f2 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/set_like.lean | a09a0c0b04a6769109de23df4cac514f9ee246e1 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,827 | 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.basic
/-!
# Typeclass for a type `A` with an injective map to `set B`
This typecalss is primary for use by subobjects like `submonoid` and `submodule`.
A typical subobject should be declared as:
```
structure my_subobject (X : Type*) :=
(carrier : set X)
(op_mem : ∀ {x : X}, x ∈ carrier → sorry ∈ carrier)
namespace my_subobject
instance : set_like (my_subobject R) M :=
⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp] lemma mem_carrier {p : my_subobject R} : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl
@[ext] theorem ext {p q : my_subobject R} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h
end my_subobject
```
This file will then provide a `coe_sort`, a `coe` to set, a `partial_order`, and various
extensionality and simp lemmas.
-/
set_option old_structure_cmd true
/-- A class to indicate that there is a canonical injection between `A` and `set B`. -/
@[protect_proj]
class set_like (A : Type*) (B : out_param $ Type*) :=
(coe : A → set B)
(coe_injective' : function.injective coe)
namespace set_like
variables {A : Type*} {B : Type*} [i : set_like A B]
include i
instance : has_coe_t A (set B) := ⟨set_like.coe⟩
@[priority 100]
instance : has_mem B A := ⟨λ x p, x ∈ (p : set B)⟩
-- `dangerous_instance` does not know that `B` is used only as an `out_param`
@[nolint dangerous_instance, priority 100]
instance : has_coe_to_sort A := ⟨_, λ p, {x : B // x ∈ p}⟩
variables (p q : A)
@[simp, norm_cast] theorem coe_sort_coe : ↥(p : set B) = p := rfl
variables {p q}
protected theorem «exists» {q : p → Prop} :
(∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists
protected theorem «forall» {q : p → Prop} :
(∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall
theorem coe_injective : function.injective (coe : A → set B) :=
λ x y h, set_like.coe_injective' h
@[simp, norm_cast] theorem coe_set_eq : (p : set B) = q ↔ p = q := coe_injective.eq_iff
theorem ext' (h : (p : set B) = q) : p = q := coe_injective h
theorem ext'_iff : p = q ↔ (p : set B) = q := coe_set_eq.symm
/-- Note: implementers of `set_like` must copy this lemma in order to tag it with `@[ext]`. -/
theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h
theorem ext_iff : p = q ↔ (∀ x, x ∈ p ↔ x ∈ q) := coe_injective.eq_iff.symm.trans set.ext_iff
@[simp] theorem mem_coe {x : B} : x ∈ (p : set B) ↔ x ∈ p := iff.rfl
@[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : B) = y ↔ x = y := subtype.ext_iff_val.symm
@[simp, norm_cast] lemma coe_mk (x : B) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : B) = x := rfl
@[simp] lemma coe_mem (x : p) : (x : B) ∈ p := x.2
@[simp] protected lemma eta (x : p) (hx : (x : B) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx
-- `dangerous_instance` does not know that `B` is used only as an `out_param`
@[nolint dangerous_instance, priority 100]
instance : partial_order A :=
{ le := λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K,
.. partial_order.lift (coe : A → set B) coe_injective }
lemma le_def {S T : A} : S ≤ T ↔ ∀ ⦃x : B⦄, x ∈ S → x ∈ T := iff.rfl
@[simp, norm_cast]
lemma coe_subset_coe {S T : A} : (S : set B) ⊆ T ↔ S ≤ T := iff.rfl
@[simp, norm_cast]
lemma coe_ssubset_coe {S T : A} : (S : set B) ⊂ T ↔ S < T := iff.rfl
lemma not_le_iff_exists : ¬(p ≤ q) ↔ ∃ x ∈ p, x ∉ q := set.not_subset
lemma exists_of_lt : p < q → ∃ x ∈ q, x ∉ p := set.exists_of_ssubset
lemma lt_iff_le_and_exists : p < q ↔ p ≤ q ∧ ∃ x ∈ q, x ∉ p :=
by rw [lt_iff_le_not_le, not_le_iff_exists]
end set_like
|
27c6d367643bf62069099de0e2f1d52ecd96d361 | a51edd9a1700339fa6dc7dc428eb5dfa3994b8bc | /src/examples.lean | 132236cd78e6a228653f03eb9fc06317ec18942c | [] | no_license | avigad/formal_logic | 83f5c0534b3e9e7da53eff01bb82289daad65555 | 59d7fe7cb7a7927fb72d89d4fd40965bcd769349 | refs/heads/master | 1,585,302,642,116 | 1,541,000,469,000 | 1,541,000,469,000 | 146,376,915 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 536 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import .subst
section examples
open hol
open hol.term
private def foo : term :=
let ty := mk_nat ⇒ mk_nat ⇒ mk_nat,
f := Const (const.user 0 ty []),
x := Var 0,
y := Var 1,
t := abstract 1 "y" mk_nat (App (App f x) y),
c := Const (const.user 1 mk_nat []),
s := subst c 0 t in
s
#eval foo.repr
#eval repr (foo.typeof [])
end examples
|
dd081d5fbf6c5f728733c75286a7d9fd8a97ef8a | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Parser/Extension.lean | 02e40fe612272bb1a3615008c077635adede4267 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,483 | 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.ResolveName
import Lean.ScopedEnvExtension
import Lean.Parser.Basic
import Lean.Parser.StrInterpolation
import Lean.KeyedDeclsAttribute
/-! 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 : Name) (behavior : LeadingIdentBehavior) : IO Unit := do
let categories ← builtinParserCategoriesRef.get
let categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, behavior := behavior}
builtinParserCategoriesRef.set categories
namespace ParserExtension
inductive OLeanEntry where
| token (val : Token) : OLeanEntry
| kind (val : SyntaxNodeKind) : OLeanEntry
| category (catName : 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) (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 b => OLeanEntry.category c 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 : Name) (parserName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none =>
throwUnknownParserCategory catName
| some cat =>
let addTokens (tks : List Token) : Except String ParserCategories :=
let tks := tks.map $ fun tk => Name.mkSimple tk
let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with leadingTable := tables.leadingTable.insert tk (p, prio) }) cat.tables
pure $ categories.insert catName { cat with tables := 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 tables := 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 (fun (tables : PrattParsingTables) tk => { tables with trailingTable := tables.trailingTable.insert tk (p, prio) }) tables
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 : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none => throwUnknownParserCategory catName
| some cat => pure $ categories.insert catName { cat with tables := addTrailingParserAux cat.tables p prio }
def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories :=
match leading, p with
| true, p => addLeadingParser categories catName declName p prio
| false, p => addTrailingParser categories catName 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 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 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 := tokens }
| _ => unreachable!
| Entry.kind k =>
{ s with kinds := s.kinds.insert k }
| Entry.category catName behavior =>
if s.categories.contains catName then s
else { s with
categories := s.categories.insert catName { tables := {}, behavior := behavior } }
| Entry.parser catName declName leading parser prio =>
match addParser s.categories catName declName leading parser prio with
| Except.ok categories => { s with categories := categories }
| _ => unreachable!
unsafe def mkParserOfConstantUnsafe
(categories : ParserCategories) (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!"unknow 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"
@[implementedBy mkParserOfConstantUnsafe]
constant mkParserOfConstantAux
(categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser)
/- 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 (← IO.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
builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {}
-- Later, we define macro registerParserAlias! which registers a parser, formatter and parenthesizer
def registerAlias (aliasName : Name) (p : ParserAliasValue) : IO Unit := do
registerAliasCore parserAliasesRef aliasName p
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 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
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 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 categories 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 categories 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 := `runBuiltinParserAttributeHooks,
descr := "explicitly run hooks normally activated by builtin parser attributes",
add := fun decl stx persistent => do
Attribute.Builtin.ensureNoArgs stx
runParserAttributeHooks Name.anonymous decl (builtin := true)
}
builtin_initialize
registerBuiltinAttribute {
name := `runParserAttributeHooks,
descr := "explicitly run hooks normally activated by parser attributes",
add := fun decl stx persistent => 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 l => return Entry.category c l
| parser catName declName prio => do
let (leading, p) ← mkParserOfConstant s.categories declName
Entry.parser catName declName leading p prio
builtin_initialize parserExtension : ParserExtension ←
registerScopedEnvExtension {
name := `parserExt
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 : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do
if isParserCategory env catName then
throwParserCategoryAlreadyDefined catName
else
return parserExtension.addEntry env <| ParserExtension.Entry.category catName behavior
def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior :=
match getCategory (parserExtension.getState env).categories catName with
| none => LeadingIdentBehavior.default
| some cat => cat.behavior
def mkCategoryAntiquotParser (kind : Name) : Parser :=
mkAntiquot kind.toString none
-- 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
kinds.contains k
def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do
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 mkParserContext (ictx : InputContext) (pmctx : ParserModuleContext) : ParserContext := {
prec := 0,
toInputContext := ictx,
toParserModuleContext := pmctx,
tokens := getTokenTable pmctx.env
}
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 c := mkParserContext (mkInputContext input fileName) { env := env, options := {} }
let s := mkParserState input
let s := whitespace c s
let s := categoryParserFnImpl catName c s
if s.hasError then
Except.error (s.toErrorMsg c)
else if input.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error ((s.mkError "end of input").toErrorMsg c)
def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : IO Environment :=
let name := `_regBuiltinParser ++ declName
let type := mkApp (mkConst `IO) (mkConst `Unit)
let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkRawNatLit prio]
let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.safe }
match env.addAndCompile {} decl with
-- TODO: pretty print error
| Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'"))
| Except.ok env => IO.ofExcept (setBuiltinInitAttr env name)
def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM?
declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName prio
def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM?
declareBuiltinParser env `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
let env ← getEnv
match decl.type with
| Expr.const `Lean.Parser.TrailingParser _ _ => do
let env ← declareTrailingBuiltinParser env catName declName prio
setEnv env
| Expr.const `Lean.Parser.Parser _ _ => do
let env ← declareLeadingBuiltinParser env catName declName prio
setEnv env
| _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)"
runParserAttributeHooks catName declName (builtin := true)
/-
The parsing tables for builtin parsers are "stored" in the extracted source code.
-/
def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Unit := do
addBuiltinParserCategory catName behavior
registerBuiltinAttribute {
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 opts ← getOptions
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 ref 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 : Name) (catName : Name) : AttributeImpl where
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 : Name) (catName : Name) : IO Unit := do
registerBuiltinAttribute (mkParserAttributeImpl attrName catName)
builtin_initialize
registerAttributeImplBuilder `parserAttr fun args =>
match args with
| [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName
| _ => throw "invalid parser attribute implementation builder arguments"
def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Environment := do
let env ← IO.ofExcept $ addParserCategory env catName behavior
registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName]
-- declare `termParser` here since it is used everywhere via antiquotations
builtin_initialize registerBuiltinParserAttribute `builtinTermParser `term
builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term
-- declare `commandParser` to break cyclic dependency
builtin_initialize registerBuiltinParserAttribute `builtinCommandParser `command
builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command
@[inline] def commandParser (rbp : Nat := 0) : Parser :=
categoryParser `command rbp
def notFollowedByCategoryTokenFn (catName : Name) : ParserFn := fun ctx s =>
let categories := (parserExtension.getState ctx.env).categories
match getCategory categories catName with
| none => s.mkUnexpectedError s!"unknown parser category '{catName}'"
| some cat =>
let (s, stx) := peekToken ctx s
match stx with
| Except.ok (Syntax.atom _ sym) =>
if ctx.quotDepth > 0 && sym == "$" then s
else match cat.tables.leadingTable.find? (Name.mkSimple sym) with
| some _ => s.mkUnexpectedError (toString catName)
| _ => s
| Except.ok _ => s
| Except.error _ => s
@[inline] def notFollowedByCategoryToken (catName : Name) : Parser := {
fn := notFollowedByCategoryTokenFn catName
}
abbrev notFollowedByCommandToken : Parser :=
notFollowedByCategoryToken `command
abbrev notFollowedByTermToken : Parser :=
notFollowedByCategoryToken `term
private def withNamespaces (ids : Array Name) (p : ParserFn) (addOpenSimple : Bool) : ParserFn := fun c s =>
let c := ids.foldl (init := c) fun c id =>
match ResolveName.resolveNamespace? c.env c.currNamespace c.openDecls id with
| none => c -- Ignore namespace resolution errors, the elaborator will report them.
| some ns =>
let openDecls := if addOpenSimple then OpenDecl.simple ns [] :: c.openDecls else c.openDecls
let env := parserExtension.activateScoped c.env ns
{ c with env, openDecls }
let tokens := parserExtension.getState c.env |>.tokens
p { c with tokens } s
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 (p : Parser) : Parser := {
info := p.info
fn := withOpenFn p.fn
}
/-- 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 (p : Parser) : Parser := {
info := p.info
fn := withOpenDeclFn p.fn
}
end Parser
end Lean
|
415a7d111d9bca79efc8c8f2a7e32c901eff6e3a | f618aea02cb4104ad34ecf3b9713065cc0d06103 | /src/ring_theory/algebra.lean | 549f45f75ad9b0b09b4835a28df6b1d21c6284f9 | [
"Apache-2.0"
] | permissive | joehendrix/mathlib | 84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5 | c15eab34ad754f9ecd738525cb8b5a870e834ddc | refs/heads/master | 1,589,606,591,630 | 1,555,946,393,000 | 1,555,946,393,000 | 182,813,854 | 0 | 0 | null | 1,555,946,309,000 | 1,555,946,308,000 | null | UTF-8 | Lean | false | false | 18,869 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Algebra over Commutative Ring (under category)
-/
import data.polynomial data.mv_polynomial
import data.complex.basic
import linear_algebra.tensor_product
import ring_theory.subring
local attribute [instance, priority 0] int.cast_coe
universes u v w u₁ v₁
open lattice
local infix ` ⊗ `:100 := tensor_product
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends module R A :=
(to_fun : R → A) [hom : is_ring_hom to_fun]
(commutes' : ∀ r x, x * to_fun r = to_fun r * x)
(smul_def' : ∀ r x, r • x = to_fun r * x)
attribute [instance] algebra.hom
def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A :=
algebra.to_fun A x
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
variables [comm_ring R] [comm_ring S] [ring A] [algebra R A]
/-- The codomain of an algebra. -/
instance : module R A := infer_instance
instance : has_scalar R A := infer_instance
instance {F : Type u} {K : Type v} [discrete_field F] [ring K] [algebra F K] :
vector_space F K :=
@vector_space.mk F _ _ _ algebra.module
include R
instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A
variables (A)
@[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s :=
is_ring_hom.map_add _
@[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s :=
is_ring_hom.map_mul _
variables (R)
@[simp] lemma map_zero : algebra_map A (0 : R) = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_one : algebra_map A (1 : R) = 1 :=
is_ring_hom.map_one _
variables {R A}
/-- Creating an algebra from a morphism in CRing. -/
def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S :=
{ smul := λ c x, i c * x,
smul_zero := λ x, mul_zero (i x),
smul_add := λ r x y, mul_add (i r) x y,
add_smul := λ r s x, show i (r + s) * x = _, by rw [hom.3, add_mul],
mul_smul := λ r s x, show i (r * s) * x = _, by rw [hom.2, mul_assoc],
one_smul := λ x, show i 1 * x = _, by rw [hom.1, one_mul],
zero_smul := λ x, show i 0 * x = _, by rw [@@is_ring_hom.map_zero _ _ i hom, zero_mul],
to_fun := i,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c x, rfl }
theorem smul_def (r : R) (x : A) : r • x = algebra_map A r * x :=
algebra.smul_def' r x
theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) :=
by rw [← mul_assoc, commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
/-- R[X] is the generator of the category R-Alg. -/
instance polynomial (R : Type u) [comm_ring R] [decidable_eq R] : algebra R (polynomial R) :=
{ to_fun := polynomial.C,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, (polynomial.C_mul' c p).symm,
.. polynomial.module }
/-- The algebra of multivariate polynomials. -/
instance mv_polynomial (R : Type u) [comm_ring R] [decidable_eq R]
(ι : Type v) [decidable_eq ι] : algebra R (mv_polynomial ι R) :=
{ to_fun := mv_polynomial.C,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, (mv_polynomial.C_mul' c p).symm,
.. mv_polynomial.module }
/-- Creating an algebra from a subring. This is the dual of ring extension. -/
instance of_subring (S : set R) [is_subring S] : algebra S R :=
of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
set_option class.instance_max_depth 39
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
end algebra
/-- Defining the homomorphism in the category R-Alg. -/
structure alg_hom {R : Type u} (A : Type v) (B : Type w)
[comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] :=
(to_fun : A → B) [hom : is_ring_hom to_fun]
(commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r)
infixr ` →ₐ `:25 := alg_hom
notation A ` →ₐ[`:25 R `] ` B := @alg_hom R A B _ _ _ _ _
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
variables [comm_ring R] [ring A] [ring B] [ring C] [ring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
include R
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨λ _, A → B, to_fun⟩
variables (φ : A →ₐ[R] B)
instance : is_ring_hom ⇑φ := hom φ
@[extensionality]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
by cases φ₁; cases φ₂; congr' 1; ext; apply H
theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
is_ring_hom.map_add _
@[simp] lemma map_zero : φ 0 = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
is_ring_hom.map_mul _
@[simp] lemma map_one : φ 1 = 1 :=
is_ring_hom.map_one _
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
add := φ.map_add,
smul := λ c x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
variables (R A)
protected def id : A →ₐ[R] A :=
{ to_fun := id, commutes' := λ _, rfl }
variables {R A}
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ C :=
{ to_fun := φ₁ ∘ φ₂,
commutes' := λ r, by rw [function.comp_apply, φ₂.commutes, φ₁.commutes] }
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
end alg_hom
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
include R S A
def comap : Type w := A
def comap.to_comap : A → comap R S A := id
def comap.of_comap : comap R S A → A := id
omit R S A
instance comap.ring : ring (comap R S A) := _inst_3
instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] :
comm_ring (comap R S A) := _inst_8
instance comap.module : module S (comap R S A) := _inst_5.to_module
instance comap.has_scalar : has_scalar S (comap R S A) := _inst_5.to_module.to_has_scalar
set_option class.instance_max_depth 40
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map S r • x : A),
smul_add := λ _ _ _, smul_add _ _ _,
add_smul := λ _ _ _, by simp only [algebra.map_add]; from add_smul _ _ _,
mul_smul := λ _ _ _, by simp only [algebra.map_mul]; from mul_smul _ _ _,
one_smul := λ _, by simp only [algebra.map_one]; from one_smul _ _,
zero_smul := λ _, by simp only [algebra.map_zero]; from zero_smul _ _,
smul_zero := λ _, smul_zero _,
to_fun := (algebra_map A : S → A) ∘ algebra_map S,
hom := by letI : is_ring_hom (algebra_map A) := _inst_5.hom; apply_instance,
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _ }
def to_comap : S →ₐ[R] comap R S A :=
{ to_fun := (algebra_map A : S → A),
hom := _inst_5.hom,
commutes' := λ r, rfl }
theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_ring R] [comm_ring S] [ring A] [ring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ to_fun := φ,
hom := alg_hom.is_ring_hom _,
commutes' := λ r, φ.commutes (algebra_map S r) }
end alg_hom
namespace polynomial
variables (R : Type u) (A : Type v)
variables [comm_ring R] [comm_ring A] [algebra R A]
variables [decidable_eq R] (x : A)
/-- A → Hom[R-Alg](R[X],A) -/
def aeval : polynomial R →ₐ[R] A :=
{ to_fun := eval₂ (algebra_map A) x,
hom := ⟨eval₂_one _ x, λ _ _, eval₂_mul _ x, λ _ _, eval₂_add _ x⟩,
commutes' := λ r, eval₂_C _ _ }
theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map A) x p := rfl
instance aeval.is_ring_hom : is_ring_hom (aeval R A x) :=
alg_hom.hom _
theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) :
φ p = eval₂ (algebra_map A) (φ X) p :=
begin
apply polynomial.induction_on p,
{ intro r, rw eval₂_C, exact φ.commutes r },
{ intros f g ih1 ih2,
rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] },
{ intros n r ih,
rw [pow_succ', ← mul_assoc, is_ring_hom.map_mul φ, eval₂_mul (algebra_map A : R → A), eval₂_X, ih] }
end
end polynomial
namespace mv_polynomial
variables (R : Type u) (A : Type v)
variables [comm_ring R] [comm_ring A] [algebra R A]
variables [decidable_eq R] [decidable_eq A] (σ : set A)
/-- (ι → A) → Hom[R-Alg](R[ι],A) -/
def aeval : mv_polynomial σ R →ₐ[R] A :=
{ to_fun := eval₂ (algebra_map A) subtype.val,
hom := ⟨eval₂_one _ _, λ _ _, eval₂_mul _ _, λ _ _, eval₂_add _ _⟩,
commutes' := λ r, eval₂_C _ _ _ }
theorem aeval_def (p : mv_polynomial σ R) : aeval R A σ p = eval₂ (algebra_map A) subtype.val p := rfl
instance aeval.is_ring_hom : is_ring_hom (aeval R A σ) :=
alg_hom.hom _
variables (ι : Type w) [decidable_eq ι]
theorem eval_unique (φ : mv_polynomial ι R →ₐ[R] A) (p) :
φ p = eval₂ (algebra_map A) (φ ∘ X) p :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw eval₂_C, exact φ.commutes r },
{ intros f g ih1 ih2,
rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] },
{ intros p j ih,
rw [is_ring_hom.map_mul φ, eval₂_mul, eval₂_X, ih] }
end
end mv_polynomial
namespace complex
instance algebra_over_reals : algebra ℝ ℂ :=
algebra.of_ring_hom coe $ by constructor; intros; simp [one_re]
instance : has_scalar ℝ ℂ := { smul := λ r c, ↑r * c}
end complex
structure subalgebra (R : Type u) (A : Type v)
[comm_ring R] [ring A] [algebra R A] : Type v :=
(carrier : set A) [subring : is_subring carrier]
(range_le : set.range (algebra_map A : R → A) ≤ carrier)
attribute [instance] subalgebra.subring
namespace subalgebra
variables {R : Type u} {A : Type v}
variables [comm_ring R] [ring A] [algebra R A]
include R
instance : has_coe (subalgebra R A) (set A) :=
⟨λ S, S.carrier⟩
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ S.carrier⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[extensionality] theorem ext {S T : subalgebra R A}
(h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T :=
by cases S; cases T; congr; ext x; exact h x
variables (S : subalgebra R A)
instance : is_subring (S : set A) := S.subring
instance : ring S := @@subtype.ring _ S.is_subring
instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1,
by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩,
smul_add := λ c x y, subtype.eq $ smul_add _ _ _,
add_smul := λ c x y, subtype.eq $ add_smul _ _ _,
mul_smul := λ c x y, subtype.eq $ mul_smul _ _ _,
one_smul := λ x, subtype.eq $ one_smul _ _,
zero_smul := λ x, subtype.eq $ zero_smul _ _,
smul_zero := λ x, subtype.eq $ smul_zero _,
to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩,
hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y,
λ x y, subtype.eq $ algebra.map_add A x y⟩,
commutes' := λ c x, subtype.eq $ by apply _inst_3.4,
smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 }
instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : algebra S A :=
algebra.of_subring _
def val : S →ₐ[R] A :=
{ to_fun := subtype.val,
hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩,
commutes' := λ r, rfl }
def to_submodule : submodule R A :=
{ carrier := S.carrier,
zero := (0:S).2,
add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance to_submodule.is_subring : is_subring (S.to_submodule : set A) := S.2
instance : partial_order (subalgebra R A) :=
{ le := λ S T, S.carrier ≤ T.carrier,
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ carrier := (iSB : set A),
subring := iSB.is_subring,
range_le := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ }
def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ carrier := T,
range_le := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) }
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
protected def range : subalgebra R B :=
{ carrier := set.range φ,
subring :=
{ one_mem := ⟨1, φ.map_one⟩,
mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ },
range_le := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ }
end alg_hom
namespace algebra
variables {R : Type u} (A : Type v)
variables [comm_ring R] [ring A] [algebra R A]
include R
variables (R)
instance id : algebra R R :=
algebra.of_ring_hom id $ by apply_instance
def of_id : R →ₐ A :=
{ to_fun := algebra_map A, commutes' := λ _, rfl }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl
variables (R) {A}
def adjoin (s : set A) : subalgebra R A :=
{ carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s),
range_le := le_trans (set.subset_union_left _ _) ring.subset_closure }
variables {R}
protected def gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H,
λ H, ring.closure_subset $ set.union_subset S.range_le H⟩
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) :=
suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl,
le_antisymm bot_le $ subalgebra.range_le _
theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
ring.mem_closure $ or.inr trivial
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
{ to_fun := λ x, ⟨x, mem_top⟩,
hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩,
commutes' := λ _, rfl }
end algebra
section int
variables (R : Type*) [comm_ring R]
/-- CRing ⥤ ℤ-Alg -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S :=
{ to_fun := f, hom := by apply_instance,
commutes' := λ i, int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f])
(λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih])
(λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]) }
/-- CRing ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
algebra.of_ring_hom coe $ by constructor; intros; simp
variables {R}
/-- CRing ⥤ ℤ-Alg -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier := S, range_le := λ x ⟨i, h⟩, h ▸ int.induction_on i
(by rw algebra.map_zero; exact is_add_submonoid.zero_mem _)
(λ i hi, by rw [algebra.map_add, algebra.map_one]; exact is_add_submonoid.add_mem hi (is_submonoid.one_mem _))
(λ i hi, by rw [algebra.map_sub, algebra.map_one]; exact is_add_subgroup.sub_mem _ _ _ hi (is_submonoid.one_mem _)) }
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
end int
|
fc296675303c080af4b39cd539799d42037f42fa | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /10_Structures_and_Records.org.13.lean | 98f2bb86840dd710e5256602946568e63f5a7798 | [] | 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 | 178 | lean | import standard
structure point (A : Type) :=
mk :: (x : A) (y : A)
inductive color :=
red | green | blue
structure color_point (A : Type) extends point A :=
mk :: (c : color)
|
d35a01d79ea0276511b7472daac0bddc721c0a80 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/proposition/2.lean | 878a43da1eedbb2de92e022f2caa23090403e556 | [
"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 | 71 | lean | lemma imp_self (P : Prop) : P → P :=
begin
intro p,
exact p,
end
|
9b67d5691227b6cbdcca7b4611005261f26204cc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/logic/nonempty.lean | bf8eb3ed20519b4232722404617f3f91a9c4d1c6 | [
"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 | 5,820 | 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 logic.basic
/-!
# Nonempty types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves a few extra facts about `nonempty`, which is defined in core Lean.
## Main declarations
* `nonempty.some`: Extracts a witness of nonemptiness using choice. Takes `nonempty α` explicitly.
* `classical.arbitrary`: Extracts a witness of nonemptiness using choice. Takes `nonempty α` as an
instance.
-/
variables {α β : Type*} {γ : α → Type*}
attribute [simp] nonempty_of_inhabited
@[priority 20]
instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩
@[priority 20]
instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩
lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α :=
iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩)
@[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p :=
iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩)
lemma not_nonempty_iff_imp_false {α : Sort*} : ¬ nonempty α ↔ α → false :=
⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩
@[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_psigma {α} {β : α → Sort*} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_subtype {α} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) :=
iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩)
@[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_pprod {α β} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end)
@[simp] lemma nonempty_psum {α β} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end)
@[simp] lemma nonempty_empty : ¬ nonempty empty :=
assume ⟨h⟩, h.elim
@[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty_plift {α} : nonempty (plift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty.forall {α} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) :=
iff.intro (assume h a, h _) (assume h ⟨a⟩, h _)
@[simp] lemma nonempty.exists {α} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) :=
iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩)
/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)
`inhabited` instance. `classical.inhabited_of_nonempty` already exists, in
`core/init/classical.lean`, but the assumption is not a type class argument,
which makes it unsuitable for some applications. -/
noncomputable def classical.inhabited_of_nonempty' {α} [h : nonempty α] : inhabited α :=
⟨classical.choice h⟩
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
@[reducible] protected noncomputable def nonempty.some {α} (h : nonempty α) : α :=
classical.choice h
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
@[reducible] protected noncomputable def classical.arbitrary (α) [h : nonempty α] : α :=
classical.choice h
/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.
`nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/
lemma nonempty.map {α β} (f : α → β) : nonempty α → nonempty β
| ⟨h⟩ := ⟨f h⟩
protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ
| ⟨x⟩ ⟨y⟩ := ⟨f x y⟩
protected lemma nonempty.congr {α β} (f : α → β) (g : β → α) :
nonempty α ↔ nonempty β :=
⟨nonempty.map f, nonempty.map g⟩
lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop}
(f : inhabited α → p) : p :=
h.elim $ f ∘ inhabited.mk
instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) :=
h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩
instance {ι : Sort*} {α : ι → Sort*} [Π i, nonempty (α i)] : nonempty (Π i, α i) :=
⟨λ _, classical.arbitrary _⟩
lemma classical.nonempty_pi {ι} {α : ι → Sort*} : nonempty (Π i, α i) ↔ ∀ i, nonempty (α i) :=
⟨λ ⟨f⟩ a, ⟨f a⟩, @pi.nonempty _ _⟩
lemma subsingleton_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : subsingleton α :=
⟨λ x, false.elim $ not_nonempty_iff_imp_false.mp h x⟩
lemma function.surjective.nonempty {α β : Sort*} [h : nonempty β] {f : α → β}
(hf : function.surjective f) :
nonempty α :=
let ⟨y⟩ := h, ⟨x, hx⟩ := hf y in ⟨x⟩
|
01e0e6e4af1d837ac79529030bb588884b688e7c | b24beef0a8b1a8e92be756a25aa78e24908b2b14 | /src/hints/thursday/afternoon/category_theory/exercise1/hint1.lean | 640a45feba2aca61ecc2058affadf91a3e58ed57 | [] | permissive | ChristopheMargerin/lftcm2020 | 14967e74cbe92a7b61d32d8130f32cfa09b5172b | 589180047fa4fdfb3179636db58b0b0320549871 | refs/heads/master | 1,668,536,269,632 | 1,594,891,664,000 | 1,594,891,664,000 | 280,112,730 | 0 | 0 | MIT | 1,594,891,963,000 | 1,594,891,962,000 | null | UTF-8 | Lean | false | false | 1,528 | lean | import category_theory.isomorphism
import category_theory.yoneda
open category_theory
open opposite
variables {C : Type*} [category C]
def iso_of_hom_iso_attempt_1 (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y :=
-- We're trying to construct an isomorphism, so our first task is to write a stub for the structure:
{ }
/-
This says:
```
invalid structure value { ... }, field 'hom' was not provided
invalid structure value { ... }, field 'inv' was not provided
```
so let's try again:
-/
def iso_of_hom_iso_attempt_2 (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y :=
{ hom := sorry,
inv := sorry, }
/-
This says:
```
`chain` tactic made no progress
state:
C : Type u_1,
_inst_1 : category C,
X Y : C,
h : yoneda.obj X ≅ yoneda.obj Y
⊢ sorry ≫ sorry = 𝟙 X
`chain` tactic made no progress
state:
C : Type u_1,
_inst_1 : category C,
X Y : C,
h : yoneda.obj X ≅ yoneda.obj Y
⊢ sorry ≫ sorry = 𝟙 Y
```
What's going on? An isomorphism in fact has two more fields, called `hom_inv_id'` and `inv_hom_id'`.
These are both marked using an `auto_param`, and so a tactic called `obviously` is trying to solve
them for us, but can't because they don't yet make sense.
Let's add in those fields:
-/
def iso_of_hom_iso_attempt_3 (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y :=
{ hom := sorry,
inv := sorry,
hom_inv_id' := sorry,
inv_hom_id' := sorry, }
/-
Finally it's time to think about the maths, but lets do that in the next hint file.
-/
|
bc28cbc59591b7b75f8fc7ac8c30aa0b123ce9bf | 1fbca480c1574e809ae95a3eda58188ff42a5e41 | /src/util/meta/tactic/basic.lean | 4ba6c890eaa8947e996d2789bbd13254a7d5d824 | [] | no_license | unitb/lean-lib | 560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e | 439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9 | refs/heads/master | 1,610,706,025,400 | 1,570,144,245,000 | 1,570,144,245,000 | 99,579,229 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,742 | lean |
import data.stream
import util.control.applicative
import util.logic
import tactic.nursery
namespace tactic
open tactic
open lean.parser
open interactive
open interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def get_local_value (e : expr) : tactic (option expr) :=
try_core $ local_def_value e
meta def print (e : parse texpr) : tactic unit :=
do e ← to_expr e,
let e' := e.get_app_fn,
if e'.is_local_constant
then do p ← local_def_value e' >>= pp,
trace format!"{e'.local_pp_name} := {p}"
else if e'.is_constant
then do e ← get_env, d ← e.get e'.const_name,
p ← pp d.value,
trace format!"{e'.const_name} := {p}"
else do p ← pp e',
trace format!"{p} := {e'.to_raw_fmt}"
meta def unfold_local (n : parse ident) : tactic unit := do
e ← resolve_name n >>= to_expr,
g ← target,
t ← infer_type e,
v ← mk_meta_var t,
h ← to_expr ``(%%e = (%%v : %%t)) >>= assert `h,
solve1 (do
tactic.revert e,
g ← target,
match g with
| (expr.elet n _ e b) := tactic.change (expr.instantiate_local n e b)
| _ := fail $ to_string n ++ " is not a local definition"
end,
tactic.intros, reflexivity ),
rewrite_target h,
tactic.clear h
meta def unfold_locals : parse ident * → tactic unit
| [] := return ()
| (n::ns) := unfold_local n >> unfold_locals ns
open list
open tactic.interactive
open applicative (lift₂)
meta def rw_aux (p : pos) (r : pexpr) (loc : loc) : tactic unit :=
do interactive.rw ⟨[rw_rule.mk p ff r ],none⟩ loc
meta def simp_coes
(eta : parse (tk "!")?) (only_kw : parse only_flag)
(rs : parse simp_arg_list) (atts : parse with_ident_list)
(l : parse location)
(cfg : simp_config_ext := {})
: tactic unit := do
coes ← [``coe,``lift_t,``has_lift_t.lift,``coe_t,``has_coe_t.coe,``coe_b,``has_coe.coe,
``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe].mmap
(λ n, simp_arg_type.expr <$> resolve_name n),
tactic.interactive.simp eta only_kw (rs ++ coes) atts l cfg
meta def distrib1
(arg : rw_rule)
(loc : loc) : tactic unit :=
do let op := arg.rule,
let p := arg.1,
if arg.symm then
( rw_aux p ``(is_left_distrib.left_distrib _ %%op) loc <|>
rw_aux p ``(is_right_distrib.right_distrib _ %%op) loc)
else
( rw_aux p ``(is_left_distrib.left_distrib %%op) loc <|>
rw_aux p ``(is_right_distrib.right_distrib %%op) loc),
return ()
meta def distributivity
(args : parse $ rw_rules)
(l : parse location) : tactic unit :=
mmap' (λ e, distrib1 e l) args.rules
meta def split_or (xs : list expr) : smt_tactic (list expr) :=
do cs ← local_context,
h ← mmap (λ h, try_core $ do
t ← infer_type h,
h <$ (match_or t <|> match_and t))
$ cs.diff xs,
let h' := h.filter_map id,
h' <$ mmap' smt_tactic.destruct h'
meta def split_all_or' : list expr → smt_tactic unit
| xs := do ys ← split_or xs, (guard (¬ ys.empty) >> smt_tactic.all_goals (split_all_or' (ys ++ xs))) <|> return ()
meta def split_all_or : smt_tactic unit :=
split_all_or' []
/-- (w,p) ← find_eq e returns a witness for bound variable #0 and a proof that
- the witness is valid
-/
meta def find_eq (v : expr) : expr → tactic (expr × expr)
| `(%%p ∧ %%q) :=
(do (w,pr) ← whnf p >>= find_eq,
pr' ← to_expr ``(λ p : %%p ∧ %%q, %%pr ∘ and.elim_left $ p),
return (w,pr')) <|>
(do (w,pr) ← whnf q >>= find_eq,
pr' ← to_expr ``(λ p : %%p ∧ %%q, %%pr ∘ and.elim_right $ p),
return (w,pr'))
| e@`(@Exists %%t %%p') :=
do (expr.lam n bi _ p) ← pure p',
v ← mk_local' n bi t,
let p'' := p.instantiate_var v,
(w,pr) ← whnf p'' >>= find_eq,
pr' ← to_expr ``( (exists_imp_iff_forall_imp _ _).mpr %%(pr.lambdas [v])),
return (w,pr')
| `(%%e₀ = %%e₁) := do
if e₀ = v then do
guard (¬ e₁.occurs v),
p ← to_expr ``(@id (%%e₀ = %%e₁)), return (e₁,p)
else if e₁ = v then do
guard (¬ e₀.occurs v),
p ← to_expr ``(@eq.symm _ %%e₀ %%e₁), return (e₀,p)
else failed
| _ := failed
meta def one_point_aux : expr → tactic (expr × expr)
| e@`(@Exists %%t %%p') :=
(do (expr.lam n bi _ p) ← pure p',
v ← mk_local' n bi t,
let p'' := p.instantiate_var v,
(w,pr) ← whnf p'' >>= find_eq v,
let pr' := pr.lambdas [v],
pr'' ← to_expr ``(iff.to_eq (exists_one_point %%w %%pr')),
let p' := p.instantiate_var w,
return (p',pr'')) <|>
(do (expr.lam n bi _ p) ← pure p',
v ← mk_local' n bi t,
let p'' := p.instantiate_var v,
(e',pr) ← one_point_aux p'',
e'' ← to_expr ``(Exists %%(e'.lambdas[v])),
pr' ← to_expr ``(eq.to_iff %%pr),
pr'' ← to_expr ``(iff.to_eq (exists_congr %%(pr'.lambdas [v]))),
return (e'',pr''))
| e₀@(expr.lam n bi t e₁) :=
do v ← mk_local' n bi t,
(e',pr) ← one_point_aux (e₁.instantiate_var v),
let pr' := pr.lambdas [v],
pr'' ← to_expr ``(@_root_.funext %%t _ %%e₀ %%(e'.lambdas [v]) %%pr'),
return (e'.lambdas [v],pr'')
| (expr.app e₀ e₁) :=
(do (e',pr) ← one_point_aux e₀,
pr' ← to_expr ``(congr_fun %%pr %%e₁),
return (expr.app e' e₁,pr')) <|>
(do (e',pr) ← one_point_aux e₁,
pr' ← to_expr ``(congr_arg %%e₀ %%pr),
return (expr.app e₀ e',pr'))
-- | `(%%e₀ → %%e₁) :=
-- do guard (e₁.has_var_idx 0),
-- (do (e',pr) ← one_point_aux e₀, _) <|>
-- (do (e',pr) ← one_point_aux e₁, _)
| _ := failed
meta def soft_apply : loc → (expr → tactic unit) → tactic unit → tactic unit
| l@loc.wildcard asm tgt := l.try_apply asm tgt
| l asm tgt := l.apply asm tgt
meta def one_point_at : option name → tactic unit
| (some h) :=
do h ← get_local h,
t ← infer_type h,
(t',pr) ← one_point_aux t,
() <$ replace_hyp h t' pr
| none :=
do t ← target,
(t',pr) ← one_point_aux t,
replace_target t' pr
meta def one_point (l : parse location) : tactic unit :=
soft_apply l
(λ h, one_point_at h.local_pp_name)
(one_point_at none)
/-- simplify `∃ x, ... x = y ...` and delete `x` -/
meta def simp_one_point
(only_kw : parse only_flag)
(rs : parse simp_arg_list)
(atts : parse with_ident_list)
(l : parse location) : tactic unit :=
soft_apply l
(λ h, repeat1 $ one_point_at h.local_pp_name <|> simp none only_kw rs atts (loc.ns [h.local_pp_name]))
(repeat1 $ one_point_at none <|> simp none only_kw rs atts (loc.ns [none]))
meta def set_binder' : expr → binder_info → expr
| (expr.pi v _ d b) bi := expr.pi v bi d (set_binder' b bi)
| e _ := e
open expr
meta def pis' : list expr → expr → tactic expr
| (e@(local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis' es f,
pure $ pi pp info t (abstract_local f' uniq)
| _ f := pure f
meta def update_name (f : string → string) : name → name
| (name.mk_string s p) := name.mk_string (f s) p
| x := x <.> f ""
protected meta def mk_unique_name' (n : name) : ℕ → tactic name | i :=
do let n' := update_name (λ x, x ++ "_" ++ to_string i) n,
(resolve_name n' >> mk_unique_name' (i+1)) <|> pure n'
meta def mk_unique_name (n : name) : tactic name :=
(resolve_name n >> tactic.mk_unique_name' n 1) <|> pure n
meta def my_generalize
(n : parse $ ident <* tk ":")
(p : parse texpr)
(h : parse (tk "with" *> ident)?): tactic unit :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
tgt ← target,
v ← mk_meta_var t,
-- (fail "thus far" : tactic unit),
t ← to_expr ``(%%t → %%tgt),
(p,_) ← solve_aux t (do
n ← intro n,
p ← to_expr p,
return $ expr.instantiate_var (expr.abstract p n) v),
unify p tgt,
interactive.generalize h () (to_pexpr v,n),
instantiate_mvars v >>= trace
meta def explicit_binders : tactic unit :=
do t ← target,
h ← assert `h $ set_binder' t binder_info.default,
tactic.swap,
exact h
meta def revert' (ids : parse ident*) : tactic unit :=
propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, explicit_binders, skip)
end tactic
open tactic
run_cmd add_interactive [`unfold_local,`unfold_locals
,`simp_coes,`explicit_binders
,`distributivity,`print,`one_point,`simp_one_point,`revert'
,`my_generalize]
meta def smt_tactic.interactive.break_asms : smt_tactic unit :=
tactic.split_all_or
meta def smt_tactic.interactive.auto : opt_param ℕ 3 → tactic unit
| 0 := done
| (nat.succ n) :=
do ls ← (local_context),
ls.any_of (λ h, () <$ apply h ; smt_tactic.interactive.auto n)
<|> exfalso ; smt_tactic.interactive.auto n
|
f7176b5ab3d76dd461a15f8ec0f0c1561254747c | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/algebra/char_zero.lean | 681e5e1a91d57a18eb2dbde003a8733706bf20f8 | [
"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,196 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Natural homomorphism from the natural numbers into a monoid with one.
-/
import data.nat.cast algebra.field tactic.wlog
/-- Typeclass for monoids with characteristic zero.
(This is usually stated on fields but it makes sense for any additive monoid with 1.) -/
class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop :=
(cast_injective : function.injective (coe : ℕ → α))
theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α]
(add_left_cancel : ∀ a b c : α, a + b = a + c → b = c)
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
⟨λ m n, begin
assume h,
wlog hle : m ≤ n,
cases nat.le.dest hle with k e,
suffices : k = 0, by rw [← e, this, add_zero],
apply H, apply add_left_cancel n,
rw [← h, ← nat.cast_add, e, add_zero, h]
end⟩
-- We have no `left_cancel_add_monoid`, so we restate it for `add_group`
-- and `ordered_cancel_comm_monoid`.
theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α]
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
char_zero_of_inj_zero (@add_left_cancel _ _) H
theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*}
[ordered_cancel_add_comm_monoid α] [has_one α]
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
char_zero_of_inj_zero (@add_left_cancel _ _) H
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_semiring.to_char_zero {α : Type*}
[linear_ordered_semiring α] : char_zero α :=
ordered_cancel_comm_monoid.char_zero_of_inj_zero $
λ n h, nat.eq_zero_of_le_zero $
(@nat.cast_le α _ _ _).1 (le_of_eq h)
namespace nat
variables {α : Type*} [add_monoid α] [has_one α] [char_zero α]
theorem cast_injective : function.injective (coe : ℕ → α) :=
char_zero.cast_injective
@[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n :=
cast_injective.eq_iff
@[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
end nat
@[field_simps] lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 :=
have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial,
by rwa [nat.cast_succ, nat.cast_one] at this
section
variables {α : Type*} [domain α] [char_zero α]
lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 :=
by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or]
lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero
end
section
variables {α : Type*} [division_ring α] [char_zero α]
@[simp] lemma half_add_self (a : α) : (a + a) / 2 = a :=
by rw [← mul_two, mul_div_cancel a two_ne_zero']
@[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a :=
by rw [← add_div, half_add_self]
lemma sub_half (a : α) : a - a / 2 = a / 2 :=
by rw [sub_eq_iff_eq_add, add_halves']
lemma half_sub (a : α) : a / 2 - a = - (a / 2) :=
by rw [← neg_sub, sub_half]
end
|
22c10d8d8f7cfc620e569cc8e2d789970018e7b7 | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/data/fintype.lean | 80d41f9e980e8ef49d65510f3410834623b1190e | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 29,929 | 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 data.finset algebra.big_operators data.array.lemmas data.vector2 data.equiv.encodable
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext]
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] :
decidable_eq (Πa, β a) :=
assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩
instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α)
(H : ∀ x : α, x ∈ s) : fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α)
(H : ∀ x : α, x ∈ l) : fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ← e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- 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 (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩)
mem_univ_val univ.2
theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) :=
by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩
protected def subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] :
card {x // p x} = s.card :=
by rw ← subtype_card s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin
change multiset.card s = multiset.card s' at e',
revert nd nd' h h' e',
refine quotient.induction_on₂ s s' (λ l₁ l₂
(nd₁ : l₁.nodup) (nd₂ : l₂.nodup)
(h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂)
(e' : l₁.length = l₂.length), _),
haveI := classical.dec_eq α,
refine ⟨equiv.of_bijective ⟨_, _⟩⟩,
{ refine λ a, l₂.nth_le (l₁.index_of a) _,
rw ← e', exact list.index_of_lt_length.2 (h₁ a) },
{ intros a b h, simpa [h₁] using congr_arg l₁.nth
(list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) },
{ have := classical.dec_eq β,
refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩,
{ rw e', exact list.index_of_lt_length.2 (h₂ b) },
{ simp [nd₁] } }
end end, λ ⟨f⟩, card_congr f⟩
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = finset.singleton a := rfl
@[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
end fintype
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
instance (n : ℕ) : fintype (fin n) :=
⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1),
list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩,
λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
by rw [fin.fintype]; simp [fintype.card, card, univ]
instance : fintype empty := ⟨∅, empty.rec _⟩
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
instance : fintype pempty := ⟨∅, pempty.rec _⟩
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
@[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl
@[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
def finset.insert_none (s : finset α) : finset (option α) :=
⟨none :: s.1.map some, multiset.nodup_cons.2
⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩
@[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α},
o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s
| none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h)
| (some a) := multiset.mem_cons.trans $ by simp; refl
theorem finset.some_mem_insert_none {s : finset α} {a : α} :
some a ∈ s.insert_none ↔ a ∈ s := by simp
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(multiset.card_cons _ _).trans (by rw multiset.card_map; refl)
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) :=
card_sigma _ _
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
@[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
by rw [sum.fintype, fintype.of_equiv_card]; simp
lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β)
(hf : function.injective f) : fintype.card α ≤ fintype.card β :=
by haveI := classical.prop_decidable; exact
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [← fintype.card_unit, fintype.card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) :=
⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim,
λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩,
by simp [fintype.card_congr e]⟩
lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α :=
⟨λ h, classical.by_contradiction (λ h₁,
have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩),
lt_irrefl 0 $ by rwa this at h),
λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩
lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := fintype.card α in
have hn : n = fintype.card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) :
∃ b : α, b ≠ a :=
let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in
let ⟨c, hc⟩ := classical.not_forall.1 hb in
by haveI := classical.dec_eq α; exact
if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩
lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, injective_of_has_left_inverse
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)),
λ hsurj, by simpa [function.comp] using
injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card (↑s : set α) = s.card := card_attach
instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true::false::0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s :=
fintype.subtype (univ.filter (∈ s)) (by simp)
instance pi.fintype {α : Type*} {β : α → Type*}
[fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) :=
@fintype.of_equiv _ _
⟨univ.pi $ λa:α, @univ (β a) _,
λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩
⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩
@[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) :=
by letI f' : fintype (Πa∈univ, β a) :=
⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩;
exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr
⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩
... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _
@[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
@[simp] lemma card_vector [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
by rw fintype.of_equiv_card; simp
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} :=
set_fintype _
instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) :=
pi.fintype
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i::l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i::l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
@[simp, to_additive finset.sum_attach_univ]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) :=
prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩)
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact
| [] := rfl
| (a :: l) := by rw [length_cons, nat.fact_succ];
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul]
lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l
| [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at *
| (a::l) f h :=
if hfa : f a = a
then
mem_append_left _ $ mem_perms_of_list_of_mem
(λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx))
else
have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa,
have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx,
have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa,
list.mem_of_ne_of_mem hxa
(h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)),
suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f,
by simpa [perms_of_list],
(@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2
(λ hfl, ⟨f a,
if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa))
else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc,
⟨swap a (f a) * f, mem_perms_of_list_of_mem this,
by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩)
lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a::l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a::l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext.2 $
by simp [mem_perms_of_list_iff,mem_of_perm hab]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card.fact :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α).fact :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
end equiv
namespace fintype
section choose
open fintype
open equiv
variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p]
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
end choose
section bijection_inverse
open function
variables [fintype α] [decidable_eq α]
variables [fintype β] [decidable_eq β]
variables {f : α → β}
/-- `
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨injective_of_left_inverse (right_inverse_bij_inv _),
surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩
end bijection_inverse
end fintype
|
a7ed03c5f9b04dcfd60ec049deb7905d401dc286 | 26b8b0964ca8e1c2e203585ba5940f83fe05e48a | /src/tidy/recover.lean | 299d82ca2b48f9c1071a4366c1bfdac11b27e836 | [] | no_license | jcommelin/lean-tidy | ef3cd32a3804221d93f0dff9e180bb2c52f4b143 | 9cecf497e90db64b5ea140ad6ae1603976dcd402 | refs/heads/master | 1,585,129,919,276 | 1,533,512,680,000 | 1,533,512,680,000 | 143,677,361 | 0 | 0 | null | 1,616,803,481,000 | 1,533,530,576,000 | Lean | UTF-8 | Lean | false | false | 1,747 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Mario Carneiro, Scott Morrison
open tactic
-- This has been PR'd to mathlib; remove when it's merged.
-- https://github.com/leanprover/mathlib/pull/125
meta def expr.metavariables (r : expr) : list expr :=
r.fold [] $ λ e _ l,
match e with
| expr.mvar _ _ _ := insert e l
| _ := l
end
meta def metavariables : tactic (list expr) :=
do r ← result,
pure r.metavariables
meta def propositional_goal : tactic unit :=
do goals ← get_goals,
let current_goal := goals.head,
current_goal_type ← infer_type current_goal,
p ← is_prop current_goal_type,
guard p
meta def subsingleton_goal : tactic unit :=
do goals ← get_goals,
let current_goal := goals.head,
current_goal_type ← infer_type current_goal >>= instantiate_mvars,
to_expr ``(subsingleton %%current_goal_type) >>= mk_instance >> skip
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do goals ← get_goals,
let current_goal := goals.head,
other_goals ← metavariables,
let other_goals := other_goals.erase current_goal,
other_goals.mmap' $ λ g, (do t ← infer_type g, t ← instantiate_mvars t, d ← kdepends_on t current_goal,
monad.whenb d $ pp t >>= λ s, fail ("This is not a terminal goal: " ++ s.to_string ++ " depends on it."))
meta def done_no_metavariables : tactic unit :=
do done,
mvars ← metavariables,
guard mvars.empty
meta def recover : tactic unit :=
do mvars ← metavariables,
done,
guard ¬ mvars.empty,
trace "recovering meta-variables in result!"
set_goals mvars
|
8f7fe0c2a086b3d5da3f57988d165931f0ada653 | d534932ed7c1eba03b537c377a4f8961acd41e99 | /examples/http-client/lakefile.lean | 9f0662092ba28f1425fdb633721d7ba587971756 | [
"Apache-2.0"
] | permissive | Adminixtrator/lean4-socket | d7e321d547df6545d0c085d310be8f2c41c44ddb | b313041f2e75f4ad8320ab66d7e2afafd2202318 | refs/heads/main | 1,692,582,696,753 | 1,633,439,398,000 | 1,633,439,523,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 135 | lean | import Lake
open Lake DSL
package http_client where
dependencies := #[{
name := `socket
src := Source.path "../../lake"
}] |
091feb2b09ead104133419a67f710988f60df109 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/autoparam.lean | 294708797e07d97d5f0fa38ebf4dc037d441b3d0 | [
"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 | 111 | lean |
def f (x y : Nat) (h : x = y := by assumption) : Nat :=
x + x
def g (x y z : Nat) (h : x = y) : Nat :=
f x y
|
fe433f2f4e9309459c7549b8435e62fe74d46edd | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/parlang/lemmas_memory.lean | abaaa4cd03e7cb71839399ccc24e86cc10cca5b9 | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 651 | lean | import parlang.defs
namespace parlang
namespace memory
variables {ι : Type} {τ : ι → Type} [decidable_eq ι] {m : memory τ} {i i' : ι} {val val' : τ i}
lemma get_update_success : get (update m i val) i = val := begin
unfold update get function.update,
simp,
end
lemma get_update_skip (h : i' ≠ i) : get (update m i val) i' = get m i' := begin
unfold update get function.update,
simp [h],
end
lemma update_update_eq : update (update m i val) i val' = update m i val' := begin
funext i',
by_cases h : i' = i,
simp [update, function.update, h],
simp [update, function.update, h],
end
end memory
end parlang |
eb2ea8d03853fed8fef76b5fa9b930c1758be6a4 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/mk_dec_eq_instance.lean | d578968fa4f3e6d4017d6a9c8c1cf0b68cd0a960 | [
"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 | 5,622 | 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
Helper tactic for showing that a type has decidable equality.
-/
prelude
import init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics
import init.meta.rec_util init.meta.interactive
namespace tactic
open expr environment list
/- Retrieve the name of the type we are building a decidable equality proof for. -/
private meta def get_dec_eq_type_name : tactic name :=
do {
(pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf,
(const n ls) ← return (get_app_fn b),
when (n ≠ `decidable) failed,
(const I ls) ← return (get_app_fn d1),
return I }
<|>
fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)"
/- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/
private meta def get_lhs_rhs : tactic (expr × expr) :=
do
(app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case",
match_eq lhs_eq_rhs
private meta def find_next_target : list expr → list expr → tactic (expr × expr)
| (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r)
| l1 l2 := failed
/- Create an inhabitant of (decidable (lhs = rhs)) -/
private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr :=
do lhs_type ← infer_type lhs,
dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf,
do {
inst ← mk_instance dec_type,
return $ inst lhs rhs }
<|>
do {
f ← pp dec_type,
fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) }
private meta def apply_eq_of_heq (h : expr) : tactic unit :=
do pr ← mk_app `eq_of_heq [h],
ty ← infer_type pr,
assertv `h' ty pr >> skip
/- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/
private meta def dec_eq_same_constructor : name → name → nat → tactic unit
| I_name F_name num_rec :=
do
(lhs, rhs) ← get_lhs_rhs,
-- Try easy case first, where the proof is just reflexivity
(unify lhs rhs >> right >> reflexivity)
<|>
do {
let lhs_list := get_app_args lhs,
let rhs_list := get_app_args rhs,
when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"),
(lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list,
rec ← is_type_app_of lhs_arg I_name,
inst ← if rec then do {
inst_fn ← mk_brec_on_rec_value F_name num_rec,
return $ app inst_fn rhs_arg }
else do {
mk_dec_eq_for lhs_arg rhs_arg
},
`[eapply @decidable.by_cases _ _ %%inst],
-- discharge first (positive) case by recursion
intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec),
-- discharge second (negative) case by contradiction
intro1, left, -- decidable.is_false
intro1 >>= injection,
intros,
contradiction <|> do {
lc ← local_context,
lc.mmap' (λ h, try (apply_eq_of_heq h) <|> skip),
contradiction },
return () }
/- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/
private meta def dec_eq_diff_constructor : tactic unit :=
left >> intron 1 >> contradiction
/- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number
of constructors. -/
private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit :=
do
(lhs, rhs) ← get_lhs_rhs,
let lhs_fn := get_app_fn lhs,
let rhs_fn := get_app_fn rhs,
if lhs_fn = rhs_fn
then dec_eq_same_constructor I_name F_name 0
else dec_eq_diff_constructor
private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit :=
intro `w >>= cases >> all_goals' (dec_eq_case_2 I_name F_name)
meta def mk_dec_eq_instance_core : tactic unit :=
do I_name ← get_dec_eq_type_name,
env ← get_env,
let v_name := `_v,
let F_name := `_F,
let num_indices := inductive_num_indices env I_name,
let idx_names := list.map (λ (p : name × nat), mk_num_name p.fst p.snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)),
-- Use brec_on if type is recursive.
-- We store the functional in the variable F.
if is_recursive env I_name
then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ())
else intro v_name >> return (),
-- Apply cases to first element of type (I ...)
get_local v_name >>= cases,
all_goals' (dec_eq_case_1 I_name F_name)
meta def mk_dec_eq_instance : tactic unit :=
do env ← get_env,
(pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf,
(const I_name ls) ← return (get_app_fn d1),
when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $
do { d1' ← whnf d1,
(app I_basic_const I_idx) ← return d1',
I_idx_type ← infer_type I_idx,
new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)),
assert `_basic_dec_eq new_goal,
swap,
`[exact _basic_dec_eq %%I_idx],
intro1,
return () },
mk_dec_eq_instance_core
meta instance binder_info.has_decidable_eq : decidable_eq binder_info :=
by mk_dec_eq_instance
@[derive_handler] meta def decidable_eq_derive_handler :=
instance_derive_handler ``decidable_eq tactic.mk_dec_eq_instance
end tactic
|
e2d07e426460b0473dfd0bbc9db221e4d8f6f5ce | 5756a081670ba9c1d1d3fca7bd47cb4e31beae66 | /Mathport/Syntax/Translate/Tactic/Mathlib/Misc1.lean | 601398241ab79ef71f5d4de87167a1d3baee8051 | [
"Apache-2.0"
] | permissive | leanprover-community/mathport | 2c9bdc8292168febf59799efdc5451dbf0450d4a | 13051f68064f7638970d39a8fecaede68ffbf9e1 | refs/heads/master | 1,693,841,364,079 | 1,693,813,111,000 | 1,693,813,111,000 | 379,357,010 | 27 | 10 | Apache-2.0 | 1,691,309,132,000 | 1,624,384,521,000 | Lean | UTF-8 | Lean | false | false | 14,390 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathport.Syntax.Translate.Tactic.Basic
import Mathport.Syntax.Translate.Tactic.Lean3
import Mathport.Syntax.Translate.Tactic.Mathlib.Cache
import Mathport.Syntax.Translate.Command
import Mathlib.Tactic.Explode
-- Misc. general-purpose tactics
open Lean
open Lean.Elab.Tactic (Location)
namespace Mathport.Translate.Tactic
open AST3 Mathport.Translate.Parser
-- # tactic.by_contra
@[tr_tactic by_contra'] def trByContra' : TacM Syntax.Tactic := do
`(tactic| by_contra' $[$((← parse (ident)?).map mkIdent):ident]?
$[: $(← liftM $ (← parse (tk ":" *> pExpr)?).mapM trExpr)]?)
-- # tactic.dec_trivial
@[tr_tactic dec_trivial] def trDecTrivial : TacM Syntax.Tactic := do
match ← parse (tk "!")? with
| none => `(tactic| decide)
| some _ => `(tactic| decide!)
-- # tactic.delta_instance
@[tr_tactic delta_instance] def trDeltaInstance : TacM Syntax.Tactic := do
`(tactic| delta_instance $[$((← parse ident*).map mkIdent)]*)
-- # tactic.elide
@[tr_tactic elide] def trElide : TacM Syntax.Tactic := do
`(tactic| elide $(Quote.quote (← parse smallNat)) $(← trLoc (← parse location))?)
@[tr_tactic unelide] def trUnelide : TacM Syntax.Tactic := do
`(tactic| unelide $(← trLoc (← parse location))?)
-- # tactic.explode
@[tr_user_cmd «#explode»] def trExplode : Parse1 Syntax.Command :=
parse1 ident fun n => do `(command| #explode $(← mkIdentI n))
-- # tactic.find
@[tr_user_cmd «#find»] def trFindCmd : Parse1 Syntax.Command :=
parse1 pExpr fun e => do `(command| #find $(← trExpr e))
-- # tactic.find_unused
@[tr_user_attr main_declaration] def trMainDeclaration := tagAttr `main_declaration
@[tr_user_cmd «#list_unused_decls»] def trListUnusedDecls : Parse1 Syntax.Command :=
parse0 `(command| #list_unused_decls)
-- # tactic.generalizes
@[tr_tactic generalizes] def trGeneralizes : TacM Syntax.Tactic := do
let args ← (← parse (listOf generalizesArg)).mapM fun (h, t, x) => do
`(Parser.Tactic.generalizeArg| $[$(h.map mkIdent) :]? $(← trExpr t) = $(mkIdent x))
`(tactic| generalize $args,*)
-- # tactic.generalize_proofs
@[tr_tactic generalize_proofs] def trGeneralizeProofs : TacM Syntax.Tactic := do
`(tactic| generalize_proofs
$[$((← parse (ident_)*).map trBinderIdent)]*
$[$(← trLoc (← parse location))]?)
-- # tactic.induction
@[tr_user_cmd cases'] def trCases' : Parse1 Syntax.Command := parse0 do
warn! "unsupported: cases'" -- unattested
@[tr_user_cmd induction'] def trInduction' : Parse1 Syntax.Command := parse0 do
warn! "unsupported: induction'" -- unattested
-- # tactic.itauto
@[tr_tactic itauto] def trITauto : TacM Syntax.Tactic := do
match ← parse (tk "!")?, ← parse ((return some (← pExprList)) <|> (tk "*" *> pure none))? with
| none, none => `(tactic| itauto)
| some _, none => `(tactic| itauto!)
| none, some none => `(tactic| itauto *)
| some _, some none => `(tactic| itauto! *)
| none, some (some ls) => `(tactic| itauto [$(← ls.mapM trExpr),*])
| some _, some (some ls) => `(tactic| itauto! [$(← ls.mapM trExpr),*])
-- # tactic.lift
@[tr_tactic lift] def trLift : TacM Syntax.Tactic := do
let what ← trExpr (← parse pExpr)
let to_ ← trExpr (← parse (tk "to" *> pExpr))
let using_ ← liftM $ (← parse (tk "using" *> pExpr)?).mapM trExpr
let with_ ← (← parse withIdentList).toList.mapM fun
| .ident n => pure <| mkIdent n
| _ => warn! "unsupported: lift with _" | pure <| mkIdent `_
match with_ with
| [] => `(tactic| lift $what to $to_ $[using $using_]?)
| [w1] => `(tactic| lift $what to $to_ $[using $using_]? with $w1)
| [w1, w2] => `(tactic| lift $what to $to_ $[using $using_]? with $w1 $w2)
| w1::w2::w3::_ => `(tactic| lift $what to $to_ $[using $using_]? with $w1 $w2 $w3)
-- # tactic.lift
-- # tactic.localized
@[tr_user_cmd «open_locale»] def trOpenLocale : Parse1 Unit :=
parse1 (ident* <* skipAll) fun ids => do
unless ids.isEmpty do
pushM `(command| open scoped $(← liftM $ ids.mapM mkIdentN)*)
@[tr_user_cmd «localized»] def trLocalized : Parse1 Unit :=
parse1 (return (← pExpr *> emittedCodeHere, ← tk "in" *> ident)) fun (cmd, loc) => do
let loc ← renameNamespace loc
match cmd with
| #[Command.attribute true mods attrs ns] =>
unless mods.isEmpty do warn! "unsupported: localized modifiers"
if loc == (← getCurrNamespace) then
trAttributeCmd .scoped attrs ns id
else
let loc ← mkIdentR loc
trAttributeCmd .global attrs ns fun stx => Id.run `(scoped[$loc] $stx)
| #[Command.notation (true, res) attrs n] =>
if loc == (← getCurrNamespace) then
trNotationCmd .scoped res attrs n
else
trNotationCmd .global res attrs n (some loc)
| #[_] => warn! "unsupported: unusual localized"
| _ => warn! "unsupported: multiple localized"
-- # tactic.mk_iff_of_inductive_prop
@[tr_user_cmd «mk_iff_of_inductive_prop»] def trMkIffOfInductiveProp : Parse1 Syntax.Command :=
parse1 (return (← ident, ← ident)) fun (i, r) => do
`(command| mk_iff_of_inductive_prop $(← mkIdentI i) $(← mkIdentI r))
@[tr_user_attr mk_iff] def trMkIffAttr : Parse1 Syntax.Attr :=
parse1 (ident)? fun n => do `(attr| mk_iff $(← liftM $ n.mapM mkIdentI)?)
-- # tactic.replacer
@[tr_user_cmd «def_replacer»] def trDefReplacer : Parse1 Syntax.Command :=
parse1 (return (← ident, ← (tk ":" *> pExpr)?)) fun (n, ty) => do
`(command| def_replacer $(← mkIdentI n) $[$(← trOptType ty):typeSpec]?)
@[tr_user_attr replaceable] def trReplaceableAttr := tagAttr `replaceable
-- # tactic.obviously
@[tr_user_attr obviously] def trObviouslyAttr := tagAttr `obviously
@[tr_ni_tactic obviously] def trObviously (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| obviously)
-- # tactic.pretty_cases
@[tr_tactic pretty_cases] def trPrettyCases : TacM Syntax.Tactic := do
`(tactic| pretty_cases)
-- # tactic.protected
@[tr_user_attr «protected»] def trProtectedAttr := tagAttr `protected
@[tr_user_attr protect_proj] def trProtectProjAttr : Parse1 Syntax.Attr :=
parse1 withoutIdentList fun ids => do
let ids ← match ids with
| #[] => pure none
| ids => some <$> liftM (ids.mapM mkIdentF)
`(attr| protect_proj $[without $[$ids]*]?)
-- # tactic.push_neg
@[tr_tactic push_neg] def trPushNeg : TacM Syntax.Tactic := do
`(tactic| push_neg $(← trLoc (← parse location))?)
@[tr_user_cmd «#push_neg»] def trPushNegCmd : Parse1 Syntax.Command :=
parse1 pExpr fun e => do `(command| #push_neg $(← trExpr e))
@[tr_tactic contrapose] def trContrapose : TacM Syntax.Tactic := do
let (tac, s) := match ← parse (tk "!")? with
| none => (``Mathlib.Tactic.Contrapose.contrapose, "contrapose")
| some _ => (``Mathlib.Tactic.Contrapose.contrapose!, "contrapose!")
let n ← parse (return (← ident, ← (tk "with" *> ident)?))?
pure ⟨mkNode tac #[mkAtom s, mkOptionalNode' n fun (a, b) =>
#[mkIdent a, mkOptionalNode' b fun b => #[mkAtom "with", mkIdent b]]]⟩
-- # tactic.rename_var
@[tr_tactic rename_var] def trRenameVar : TacM Syntax.Tactic := do
`(tactic| rename_bvar $(mkIdent (← parse ident)) → $(mkIdent (← parse ident))
$(← trLoc (← parse location))?)
-- # tactic.restate_axiom
@[tr_user_cmd «restate_axiom»] def trRestateAxiom : Parse1 Syntax.Command :=
parse1 (return (← ident, ← (ident)?)) fun (a, b) => do
`(command| restate_axiom $(← mkIdentI a) $(← liftM $ b.mapM mkIdentI)?)
-- # tactic.rewrite
@[tr_tactic assoc_rewrite assoc_rw] def trAssocRw : TacM Syntax.Tactic := do
`(tactic| assoc_rw
[$(← liftM $ (← parse rwRules).mapM trRwRule),*]
$(← trLoc (← parse location))?)
-- # tactic.show_term
@[tr_tactic «show_term»] def trShowTerm : TacM Syntax.Tactic := do
`(tactic| show_term $(← trBlock (← itactic)):tacticSeq)
-- # tactic.simp_rw
@[tr_tactic simp_rw] def trSimpRw : TacM Syntax.Tactic := do
`(tactic| simp_rw
[$(← liftM $ (← parse rwRules).mapM trRwRule),*]
$(← trLoc (← parse location))?)
-- # tactic.simp_command
@[tr_user_cmd «#simp»] def trSimpCmd : Parse1 Syntax.Command :=
parse1 (return (← onlyFlag, ← simpArgList,
(← (tk "with" *> ident*)?).getD #[], ← (tk ":")? *> pExpr))
fun (o, args, attrs, e) => do
let o := optTk o
let hs ← trSimpArgs args
let hs := (hs ++ attrs.map trSimpExt).asNonempty
`(command| #simp $[only%$o]? $[[$hs,*]]? $(← trExpr e))
-- # tactic.simp_result
@[tr_tactic dsimp_result] def trDSimpResult : TacM Syntax.Tactic := do
let o := optTk (← parse onlyFlag)
let hs ← trSimpArgs (← parse simpArgList)
let (hs, _all) := filterSimpStar hs -- dsimp [*] is always pointless
let attrs := (← parse (tk "with" *> ident*)?).getD #[]
let hs := (hs ++ attrs.map trSimpExt).asNonempty
`(tactic| dsimp_result $[only%$o]? $[[$hs,*]]? => $(← trBlock (← itactic)))
@[tr_tactic simp_result] def trSimpResult : TacM Syntax.Tactic := do
let o := optTk (← parse onlyFlag)
let hs ← trSimpArgs (← parse simpArgList)
let attrs := (← parse (tk "with" *> ident*)?).getD #[]
let hs := (hs ++ attrs.map trSimpExt).asNonempty
`(tactic| simp_result $[only%$o]? $[[$hs,*]]? => $(← trBlock (← itactic)))
-- # tactic.split_ifs
@[tr_tactic split_ifs] def trSplitIfs : TacM Syntax.Tactic := do
`(tactic| split_ifs $(← trLoc (← parse location))?
$[with $(((← parse withIdentList).map trBinderIdent).asNonempty)*]?)
-- # tactic.swap_var
@[tr_tactic swap_var] def trSwapVar : TacM Syntax.Tactic := do
let args ← parse $ maybeListOf $ return (← ident, ← (tk "↔" <|> tk "<->")? *> ident)
if args.isEmpty then `(tactic| skip) else
let args ← args.mapM fun (x, y) =>
`(Mathlib.Tactic.swapRule| $(mkIdent x):ident ↔ $(mkIdent y):ident)
`(tactic| swap_var $args,*)
-- # tactic.tauto
@[tr_tactic tauto tautology] def trTauto : TacM Syntax.Tactic := do
let _ ← parse (tk "!")?
-- Ignore the !. The new tauto is equivalent to the old tauto!, and the old
-- tauto is just a half baked weak version of the same thing.
let cfg ← liftM $ (← expr?).mapM trExpr
`(tactic| tauto $[(config := $cfg)]?)
-- # tactic.unify_equations
@[tr_tactic unify_equations] def trUnifyEquations : TacM Syntax.Tactic := do
warn! "unsupported tactic unify_equations" -- unattested
-- # tactic.where
@[tr_user_cmd «#where»] def trWhereCmd : Parse1 Syntax.Command :=
parse1 skipAll fun _ => `(command| #where)
-- # tactic.tfae
open TSyntax.Compat in
@[tr_tactic tfae_have] def trTfaeHave : TacM Syntax.Tactic := do
let h := (← parse ((ident)? <* tk ":")).map mkIdent
let n1 := Quote.quote (← parse smallNat)
let tk ← parse <| (tk "->" *> pure "→") <|> (tk "↔" *> pure "↔") <|> (tk "<-" *> pure "←")
let n2 := Quote.quote (← parse smallNat)
match tk with
| "→" => `(tactic| tfae_have $[$h :]? $n1 → $n2)
| "↔" => `(tactic| tfae_have $[$h :]? $n1 ↔ $n2)
| "←" => `(tactic| tfae_have $[$h :]? $n1 ← $n2)
| _ => unreachable!
@[tr_tactic tfae_finish] def trTfaeFinish : TacM Syntax.Tactic := `(tactic| tfae_finish)
-- # tactic.apply_fun
@[tr_tactic apply_fun] def trApplyFun : TacM Syntax.Tactic := do
`(tactic| apply_fun
$(← trExpr (← parse pExpr))
$[$(← trLoc (← parse location))]?
$[using $(← liftM $ (← parse (tk "using" *> pExpr)?).mapM trExpr)]?)
-- # tactic.reassoc_axiom
@[tr_user_attr reassoc] def trReassocAttr : Parse1 Syntax.Attr :=
parse1 (ident)? fun n => do
let ns ← liftM $ n.mapM mkIdentI
if let some ns := ns then warn! "unsupported lemma name {ns} in reassoc attr"
`(attr| reassoc)
@[tr_user_cmd «reassoc_axiom»] def trReassocAxiom : Parse1 Syntax.Command :=
parse1 ident fun n => do `(command| reassoc_axiom $(← mkIdentI n))
@[tr_tactic reassoc] def trReassoc : TacM Syntax.Tactic := do
match ← parse (tk "!")?, (← parse ident*).map mkIdent with
| none, ns => `(tactic| reassoc $[$ns]*)
| some _, ns => `(tactic| reassoc! $[$ns]*)
@[tr_ni_tactic tactic.derive_reassoc_proof] def trDeriveReassocProof
(_ : AST3.Expr) : M Syntax.Tactic := `(tactic| derive_reassoc_proof)
-- # tactic.slice
@[tr_conv slice] def trSliceConv : TacM Syntax.Conv := do
let ⟨_, AST3.Expr.nat a⟩ ← expr! | warn! "slice: weird nat"
let ⟨_, AST3.Expr.nat b⟩ ← expr! | warn! "slice: weird nat"
`(conv| slice $(Quote.quote a) $(Quote.quote b))
@[tr_tactic slice_lhs] def trSliceLHS : TacM Syntax.Tactic := do
`(tactic| slice_lhs $(Quote.quote (← parse smallNat)) $(Quote.quote (← parse smallNat))
=> $(← trConvBlock (← itactic)):convSeq)
@[tr_tactic slice_rhs] def trSliceRHS : TacM Syntax.Tactic := do
`(tactic| slice_rhs $(Quote.quote (← parse smallNat)) $(Quote.quote (← parse smallNat))
=> $(← trConvBlock (← itactic)):convSeq)
-- # tactic.rewrite_search
@[tr_user_attr rewrite] def trRewriteAttr := tagAttr `rewrite
@[tr_tactic rewrite_search] def trRewriteSearch : TacM Syntax.Tactic := do
let explain ← parse (tk "?")?
let rw ← liftM $ (← parse rwRules).mapM trRwRule
let cfg ← liftM $ (← expr?).mapM trExpr
match explain with
| none => `(tactic| rw_search $[(config := $cfg)]? [$rw,*])
| some _ => `(tactic| rw_search? $[(config := $cfg)]? [$rw,*])
-- # tactic.tidy
@[tr_user_attr tidy] def trTidyAttr := tagAttr `tidy
@[tr_tactic tidy] def trTidy : TacM Syntax.Tactic := do
let explain ← parse (tk "?")?
let cfg ← liftM $ (← expr?).mapM trExpr
match explain with
| none => `(tactic| tidy $[(config := $cfg)]?)
| some _ => `(tactic| tidy? $[(config := $cfg)]?)
-- # tactic.wlog
@[tr_tactic wlog] def trWlog : TacM Syntax.Tactic := do
let h ← parse (mkIdent <$> ident)
let pat ← trExpr (← parse (tk ":" *> pExpr))
let revert ← parse <| tk "generalizing" *>
((tk "*" *> pure none) <|> (some <$> (mkIdent <$> ident)*)) <|> pure none
let H ← parse (tk "with" *> mkIdent <$> ident)?
`(tactic| wlog $h:ident : $pat:term $[generalizing $[$revert]*]? $[with $H:ident]?)
-- # tactic.algebra
@[tr_user_attr ancestor] def trAncestorAttr : Parse1 Syntax.Attr :=
parse1 ident* fun _ => pure ⟨.missing⟩ -- ancestor attribute no longer needed
|
cae5a37be7752e701b3f92c6aa6c1918e11925aa | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/group_theory/presented_group.lean | 135a8b1ebcc16236e332ad305eb016cf524a9ba9 | [
"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 | 2,449 | lean | /-
Copyright (c) 2019 Michael Howes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Howes
Defining a group given by generators and relations
-/
import group_theory.free_group
import group_theory.quotient_group
variables {α : Type}
/-- Given a set of relations, rels, over a type α, presented_group constructs the group with
generators α and relations rels as a quotient of free_group α.-/
def presented_group (rels : set (free_group α)) : Type :=
quotient_group.quotient $ subgroup.normal_closure rels
namespace presented_group
instance (rels : set (free_group α)) : group (presented_group (rels)) :=
quotient_group.quotient.group _
/-- `of x` is the canonical map from α to a presented group with generators α. The term x is
mapped to the equivalence class of the image of x in free_group α. -/
def of {rels : set (free_group α)} (x : α) : presented_group rels :=
quotient_group.mk (free_group.of x)
section to_group
/-
Presented groups satisfy a universal property. If β is a group and f : α → β is a map such that the
images of f satisfy all the given relations, then f extends uniquely to a group homomorphism from
presented_group rels to β
-/
variables {β : Type} [group β] {f : α → β} {rels : set (free_group α)}
local notation `F` := free_group.to_group f
variable (h : ∀ r ∈ rels, F r = 1)
lemma closure_rels_subset_ker : subgroup.normal_closure rels ≤ monoid_hom.ker F :=
subgroup.normal_closure_le_normal (λ x w, (monoid_hom.mem_ker _).2 (h x w))
lemma to_group_eq_one_of_mem_closure : ∀ x ∈ subgroup.normal_closure rels, F x = 1 :=
λ x w, (monoid_hom.mem_ker _).1 $ closure_rels_subset_ker h w
/-- The extension of a map f : α → β that satisfies the given relations to a group homomorphism
from presented_group rels → β. -/
def to_group : presented_group rels →* β :=
quotient_group.lift (subgroup.normal_closure rels) (monoid_hom.of F) (to_group_eq_one_of_mem_closure h)
@[simp] lemma to_group.of {x : α} : to_group h (of x) = f x := free_group.to_group.of
theorem to_group.unique (g : presented_group rels →* β)
(hg : ∀ x : α, g (of x) = f x) : ∀ {x}, g x = to_group h x :=
λ x, quotient_group.induction_on x
(λ _, free_group.to_group.unique (g.comp (quotient_group.mk' _)) hg)
end to_group
instance (rels : set (free_group α)) : inhabited (presented_group rels) := ⟨1⟩
end presented_group
|
5d90ea8518a0eda4e8cec86c1fe6ad24b37910e2 | df561f413cfe0a88b1056655515399c546ff32a5 | /8-inequality-world/l1.lean | 727e516a6ad00a1c7fc5ddccaaac29eb04017000 | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 109 | lean | lemma one_add_le_self (x : mynat) : x ≤ 1 + x :=
begin
rw le_iff_exists_add,
use 1,
exact add_comm 1 x,
end |
b0be9502248c41a501ef5397221160efc33b826b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/dsimp_proj.lean | 8c98c5b1f1b73cbca05474224554132be328becf | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 325 | lean | example (a b : nat) : a + b = b + a :=
begin
dsimp [has_add.add],
guard_target nat.add a b = nat.add b a,
apply nat.add_comm
end
example (f g : nat → nat) : (f ∘ g) = (λ x, f (g x)) :=
begin
fail_if_success {dsimp},
dsimp {unfold_reducible := tt},
guard_target (λ x, f (g x)) = (λ x, f (g x)),
refl
end
|
e928c79c4b7d764bef60b4061a125f1ed3f820a2 | 3b15c7b0b62d8ada1399c112ad88a529e6bfa115 | /src/Lean/Elab/Tactic/Conv/Pattern.lean | c643285c68ab7c303ad22f0bddb5cad2a7d7827d | [
"Apache-2.0"
] | permissive | stephenbrady/lean4 | 74bf5cae8a433e9c815708ce96c9e54a5caf2115 | b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9 | refs/heads/master | 1,692,621,473,161 | 1,634,308,743,000 | 1,634,310,749,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,818 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Tactic.Simp
import Lean.Elab.Tactic.Conv.Basic
namespace Lean.Elab.Tactic.Conv
open Meta
private def getContext : MetaM Simp.Context := do
return {
simpLemmas := {}
congrLemmas := (← getCongrLemmas)
config.zeta := false
config.beta := false
config.eta := false
config.iota := false
config.proj := false
config.decide := false
}
partial def matchPattern? (pattern : AbstractMVarsResult) (e : Expr) : MetaM (Option (Expr × Array Expr)) :=
withNewMCtxDepth do
/- TODO: check whether the following is a performance bottleneck. If it is, recall that we used `AbstractMVarsResult` to make
sure we can match the pattern inside of binders. So, it is not needed in most cases. -/
let (_, _, pattern) ← openAbstractMVarsResult pattern
let rec go? (e : Expr) : MetaM (Option (Expr × Array Expr)) := do
if (← isDefEqGuarded pattern e) then
return some (e, #[])
else if e.isApp then
(← go? e.appFn!).map fun (f, extra) => (f, extra.push e.appArg!)
else
return none
withReducible <| go? e
private def pre (pattern : AbstractMVarsResult) (found? : IO.Ref (Option Expr)) (e : Expr) : SimpM Simp.Step := do
if (← found?.get).isSome then
return Simp.Step.visit { expr := e }
else if let some (e, extraArgs) ← matchPattern? pattern e then
let (rhs, newGoal) ← mkConvGoalFor e
found?.set newGoal
let mut proof := newGoal
for extraArg in extraArgs do
proof ← mkCongrFun proof extraArg
return Simp.Step.done { expr := mkAppN rhs extraArgs, proof? := proof }
else
return Simp.Step.visit { expr := e }
private def findPattern? (pattern : AbstractMVarsResult) (e : Expr) : MetaM (Option (MVarId × Simp.Result)) := do
let found? ← IO.mkRef none
let result ← Simp.main e (← getContext) (methods := { pre := pre pattern found? })
if let some newGoal ← found?.get then
return some (newGoal.mvarId!, result)
else
return none
@[builtinTactic Lean.Parser.Tactic.Conv.pattern] def evalPattern : Tactic := fun stx => withMainContext do
match stx with
| `(conv| pattern $p) =>
let pattern ← Term.withoutPending <| Term.elabTerm p none
let patternA ← abstractMVars pattern
let lhs ← getLhs
match (← findPattern? patternA lhs) with
| none => throwError "'pattern' conv tactic failed, pattern was not found{indentExpr pattern}"
| some (mvarId', result) =>
updateLhs result.expr (← result.getProof)
applyRefl (← getMainGoal)
replaceMainGoal [mvarId']
| _ => throwUnsupportedSyntax
end Lean.Elab.Tactic.Conv
|
e313d8e91c995b5bdb56f83baeb4f324fa2ffed5 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/instances/nnreal.lean | 32dab35f60751685bf5c9eb30cfdaea7df338c7d | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,802 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import topology.algebra.infinite_sum
import topology.algebra.group_with_zero
/-!
# Topology on `ℝ≥0`
The natural topology on `ℝ≥0` (the one induced from `ℝ`), and a basic API.
## Main definitions
Instances for the following typeclasses are defined:
* `topological_space ℝ≥0`
* `topological_ring ℝ≥0`
* `second_countable_topology ℝ≥0`
* `order_topology ℝ≥0`
* `has_continuous_sub ℝ≥0`
* `has_continuous_inv' ℝ≥0` (continuity of `x⁻¹` away from `0`)
* `has_continuous_smul ℝ≥0 ℝ`
Everything is inherited from the corresponding structures on the reals.
## Main statements
Various mathematically trivial lemmas are proved about the compatibility
of limits and sums in `ℝ≥0` and `ℝ`. For example
* `tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} :
tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x)`
says that the limit of a filter along a map to `ℝ≥0` is the same in `ℝ` and `ℝ≥0`, and
* `coe_tsum {f : α → ℝ≥0} : ((∑'a, f a) : ℝ) = (∑'a, (f a : ℝ))`
says that says that a sum of elements in `ℝ≥0` is the same in `ℝ` and `ℝ≥0`.
Similarly, some mathematically trivial lemmas about infinite sums are proved,
a few of which rely on the fact that subtraction is continuous.
-/
noncomputable theory
open set topological_space metric filter
open_locale topological_space
namespace nnreal
open_locale nnreal big_operators filter
instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference
instance : topological_ring ℝ≥0 :=
{ continuous_mul := continuous_subtype_mk _ $
(continuous_subtype_val.comp continuous_fst).mul (continuous_subtype_val.comp continuous_snd),
continuous_add := continuous_subtype_mk _ $
(continuous_subtype_val.comp continuous_fst).add (continuous_subtype_val.comp continuous_snd) }
instance : second_countable_topology ℝ≥0 :=
topological_space.subtype.second_countable_topology _ _
instance : order_topology ℝ≥0 := @order_topology_of_ord_connected _ _ _ _ (Ici 0) _
section coe
variable {α : Type*}
open filter finset
lemma continuous_of_real : continuous real.to_nnreal :=
continuous_subtype_mk _ $ continuous_id.max continuous_const
lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ) :=
continuous_subtype_val
@[simp, norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} :
tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) :=
tendsto_subtype_rng.symm
lemma tendsto_coe' {f : filter α} [ne_bot f] {m : α → ℝ≥0} {x : ℝ} :
tendsto (λ a, m a : α → ℝ) f (𝓝 x) ↔ ∃ hx : 0 ≤ x, tendsto m f (𝓝 ⟨x, hx⟩) :=
⟨λ h, ⟨ge_of_tendsto' h (λ c, (m c).2), tendsto_coe.1 h⟩, λ ⟨hx, hm⟩, tendsto_coe.2 hm⟩
@[simp] lemma map_coe_at_top : map (coe : ℝ≥0 → ℝ) at_top = at_top :=
map_coe_Ici_at_top 0
lemma comap_coe_at_top : comap (coe : ℝ≥0 → ℝ) at_top = at_top :=
(at_top_Ici_eq 0).symm
@[simp, norm_cast] lemma tendsto_coe_at_top {f : filter α} {m : α → ℝ≥0} :
tendsto (λ a, (m a : ℝ)) f at_top ↔ tendsto m f at_top :=
tendsto_Ici_at_top.symm
lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) :
tendsto (λa, real.to_nnreal (m a)) f (𝓝 (real.to_nnreal x)) :=
(continuous_of_real.tendsto _).comp h
lemma nhds_zero : 𝓝 (0 : ℝ≥0) = ⨅a ≠ 0, 𝓟 (Iio a) :=
nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, set.Iio]
lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0)).has_basis (λ a : ℝ≥0, 0 < a) (λ a, Iio a) :=
nhds_bot_basis
instance : has_continuous_sub ℝ≥0 :=
⟨continuous_subtype_mk _ $
((continuous_coe.comp continuous_fst).sub
(continuous_coe.comp continuous_snd)).max continuous_const⟩
instance : has_continuous_inv₀ ℝ≥0 :=
⟨λ x hx, tendsto_coe.1 $ (real.tendsto_inv $ nnreal.coe_ne_zero.2 hx).comp
continuous_coe.continuous_at⟩
instance : has_continuous_smul ℝ≥0 ℝ :=
{ continuous_smul := continuous.comp real.continuous_mul $ continuous.prod_mk
(continuous.comp continuous_subtype_val continuous_fst) continuous_snd }
@[norm_cast] lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} :
has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r :=
by simp only [has_sum, coe_sum.symm, tendsto_coe]
lemma has_sum_of_real_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) :
has_sum (λ n, real.to_nnreal (f n)) (real.to_nnreal (∑' n, f n)) :=
begin
have h_sum : (λ s, ∑ b in s, real.to_nnreal (f b)) = λ s, real.to_nnreal (∑ b in s, f b),
from funext (λ _, (real.to_nnreal_sum_of_nonneg (λ n _, hf_nonneg n)).symm),
simp_rw [has_sum, h_sum],
exact tendsto_of_real hf.has_sum,
end
@[norm_cast] lemma summable_coe {f : α → ℝ≥0} : summable (λa, (f a : ℝ)) ↔ summable f :=
begin
split,
exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩,
exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩
end
lemma summable_coe_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) :
@summable (ℝ≥0) _ _ _ (λ n, ⟨f n, hf₁ n⟩) ↔ summable f :=
begin
lift f to α → ℝ≥0 using hf₁ with f rfl hf₁,
simp only [summable_coe, subtype.coe_eta]
end
open_locale classical
@[norm_cast] lemma coe_tsum {f : α → ℝ≥0} : ↑∑'a, f a = ∑'a, (f a : ℝ) :=
if hf : summable f
then (eq.symm $ (has_sum_coe.2 $ hf.has_sum).tsum_eq)
else by simp [tsum, hf, mt summable_coe.1 hf]
lemma coe_tsum_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) :
(⟨∑' n, f n, tsum_nonneg hf₁⟩ : ℝ≥0) = (∑' n, ⟨f n, hf₁ n⟩ : ℝ≥0) :=
begin
lift f to α → ℝ≥0 using hf₁ with f rfl hf₁,
simp_rw [← nnreal.coe_tsum, subtype.coe_eta]
end
lemma tsum_mul_left (a : ℝ≥0) (f : α → ℝ≥0) : ∑' x, a * f x = a * ∑' x, f x :=
nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_left]
lemma tsum_mul_right (f : α → ℝ≥0) (a : ℝ≥0) : (∑' x, f x * a) = (∑' x, f x) * a :=
nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_right]
lemma summable_comp_injective {β : Type*} {f : α → ℝ≥0} (hf : summable f)
{i : β → α} (hi : function.injective i) :
summable (f ∘ i) :=
nnreal.summable_coe.1 $
show summable ((coe ∘ f) ∘ i), from (nnreal.summable_coe.2 hf).comp_injective hi
lemma summable_nat_add (f : ℕ → ℝ≥0) (hf : summable f) (k : ℕ) : summable (λ i, f (i + k)) :=
summable_comp_injective hf $ add_left_injective k
lemma summable_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) : summable (λ i, f (i + k)) ↔ summable f :=
begin
rw [← summable_coe, ← summable_coe],
exact @summable_nat_add_iff ℝ _ _ _ (λ i, (f i : ℝ)) k,
end
lemma has_sum_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) {a : ℝ≥0} :
has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) :=
by simp [← has_sum_coe, coe_sum, nnreal.coe_add, ← has_sum_nat_add_iff k]
lemma sum_add_tsum_nat_add {f : ℕ → ℝ≥0} (k : ℕ) (hf : summable f) :
∑' i, f i = (∑ i in range k, f i) + ∑' i, f (i + k) :=
by rw [←nnreal.coe_eq, coe_tsum, nnreal.coe_add, coe_sum, coe_tsum,
sum_add_tsum_nat_add k (nnreal.summable_coe.2 hf)]
lemma infi_real_pos_eq_infi_nnreal_pos [complete_lattice α] {f : ℝ → α} :
(⨅ (n : ℝ) (h : 0 < n), f n) = (⨅ (n : ℝ≥0) (h : 0 < n), f n) :=
le_antisymm
(infi_le_infi2 $ assume r, ⟨r, infi_le_infi $ assume hr, le_rfl⟩)
(le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, hr.le⟩ $ infi_le _ hr)
end coe
lemma tendsto_cofinite_zero_of_summable {α} {f : α → ℝ≥0} (hf : summable f) :
tendsto f cofinite (𝓝 0) :=
begin
have h_f_coe : f = λ n, real.to_nnreal (f n : ℝ), from funext (λ n, real.to_nnreal_coe.symm),
rw [h_f_coe, ← @real.to_nnreal_coe 0],
exact tendsto_of_real ((summable_coe.mpr hf).tendsto_cofinite_zero),
end
lemma tendsto_at_top_zero_of_summable {f : ℕ → ℝ≥0} (hf : summable f) :
tendsto f at_top (𝓝 0) :=
by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_summable hf }
/-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole
space. This does not need a summability assumption, as otherwise all sums are zero. -/
lemma tendsto_tsum_compl_at_top_zero {α : Type*} (f : α → ℝ≥0) :
tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) :=
begin
simp_rw [← tendsto_coe, coe_tsum, nnreal.coe_zero],
exact tendsto_tsum_compl_at_top_zero (λ (a : α), (f a : ℝ))
end
end nnreal
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.