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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b71c1fd2af1a583d761cbe1763af180115a7154 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/qpf/multivariate/basic.lean | 3aba3258e6ac91ff209516877e51d245460bfaaf | [
"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 | 8,867 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Simon Hudon
-/
import data.pfunctor.multivariate.basic
/-!
# Multivariate quotients of polynomial functors.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Basic definition of multivariate QPF. QPFs form a compositional framework
for defining inductive and coinductive types, their quotients and nesting.
The idea is based on building ever larger functors. For instance, we can define
a list using a shape functor:
```lean
inductive list_shape (a b : Type)
| nil : list_shape
| cons : a -> b -> list_shape
```
This shape can itself be decomposed as a sum of product which are themselves
QPFs. It follows that the shape is a QPF and we can take its fixed point
and create the list itself:
```lean
def list (a : Type) := fix list_shape a -- not the actual notation
```
We can continue and define the quotient on permutation of lists and create
the multiset type:
```lean
def multiset (a : Type) := qpf.quot list.perm list a -- not the actual notion
```
And `multiset` is also a QPF. We can then create a novel data type (for Lean):
```lean
inductive tree (a : Type)
| node : a -> multiset tree -> tree
```
An unordered tree. This is currently not supported by Lean because it nests
an inductive type inside of a quotient. We can go further and define
unordered, possibly infinite trees:
```lean
coinductive tree' (a : Type)
| node : a -> multiset tree' -> tree'
```
by using the `cofix` construct. Those options can all be mixed and
matched because they preserve the properties of QPF. The latter example,
`tree'`, combines fixed point, co-fixed point and quotients.
## Related modules
* constructions
* fix
* cofix
* quot
* comp
* sigma / pi
* prj
* const
each proves that some operations on functors preserves the QPF structure
## Reference
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
open_locale mvfunctor
/--
Multivariate quotients of polynomial functors.
-/
class mvqpf {n : ℕ} (F : typevec.{u} n → Type*) [mvfunctor F] :=
(P : mvpfunctor.{u} n)
(abs : Π {α}, P.obj α → F α)
(repr : Π {α}, F α → P.obj α)
(abs_repr : ∀ {α} (x : F α), abs (repr x) = x)
(abs_map : ∀ {α β} (f : α ⟹ β) (p : P.obj α), abs (f <$$> p) = f <$$> abs p)
namespace mvqpf
variables {n : ℕ} {F : typevec.{u} n → Type*} [mvfunctor F] [q : mvqpf F]
include q
open mvfunctor (liftp liftr)
/-!
### Show that every mvqpf is a lawful mvfunctor.
-/
protected theorem id_map {α : typevec n} (x : F α) : typevec.id <$$> x = x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map], reflexivity }
@[simp] theorem comp_map {α β γ : typevec n} (f : α ⟹ β) (g : β ⟹ γ) (x : F α) :
(g ⊚ f) <$$> x = g <$$> f <$$> x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map, ←abs_map, ←abs_map], reflexivity }
@[priority 100]
instance is_lawful_mvfunctor : is_lawful_mvfunctor F :=
{ id_map := @mvqpf.id_map n F _ _,
comp_map := @comp_map n F _ _ }
/- Lifting predicates and relations -/
theorem liftp_iff {α : typevec n} (p : Π ⦃i⦄, α i → Prop) (x : F α) :
liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i j, p (f i j) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : repr y with a f,
use [a, λ i j, (f i j).val], split,
{ rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity },
intros i j, apply (f i j).property },
rintros ⟨a, f, h₀, h₁⟩, dsimp at *,
use abs (⟨a, λ i j, ⟨f i j, h₁ i j⟩⟩),
rw [←abs_map, h₀], reflexivity
end
theorem liftr_iff {α : typevec n} (r : Π ⦃i⦄, α i → α i → Prop) (x y : F α) :
liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) :=
begin
split,
{ rintros ⟨u, xeq, yeq⟩, cases h : repr u with a f,
use [a, λ i j, (f i j).val.fst, λ i j, (f i j).val.snd],
split, { rw [←xeq, ←abs_repr u, h, ←abs_map], refl },
split, { rw [←yeq, ←abs_repr u, h, ←abs_map], refl },
intros i j, exact (f i j).property },
rintros ⟨a, f₀, f₁, xeq, yeq, h⟩,
use abs ⟨a, λ i j, ⟨(f₀ i j, f₁ i j), h i j⟩⟩,
dsimp, split,
{ rw [xeq, ←abs_map], refl },
rw [yeq, ←abs_map], refl
end
open set
open mvfunctor
theorem mem_supp {α : typevec n} (x : F α) (i) (u : α i) :
u ∈ supp x i ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ :=
begin
rw [supp], dsimp, split,
{ intros h a f haf,
have : liftp (λ i u, u ∈ f i '' univ) x,
{ rw liftp_iff, refine ⟨a, f, haf.symm, _⟩,
intros i u, exact mem_image_of_mem _ (mem_univ _) },
exact h this },
intros h p, rw liftp_iff,
rintros ⟨a, f, xeq, h'⟩,
rcases h a f xeq.symm with ⟨i, _, hi⟩,
rw ←hi, apply h'
end
theorem supp_eq {α : typevec n} {i} (x : F α) :
supp x i = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ } :=
by ext; apply mem_supp
theorem has_good_supp_iff {α : typevec n} (x : F α) :
(∀ p, liftp p x ↔ ∀ i (u ∈ supp x i), p i u) ↔
∃ a f, abs ⟨a, f⟩ = x ∧ ∀ i a' f', abs ⟨a', f'⟩ = x → f i '' univ ⊆ f' i '' univ :=
begin
split,
{ intros h,
have : liftp (supp x) x, by { rw h, introv, exact id, },
rw liftp_iff at this, rcases this with ⟨a, f, xeq, h'⟩,
refine ⟨a, f, xeq.symm, _⟩,
intros a' f' h'',
rintros hu u ⟨j, h₂, hfi⟩,
have hh : u ∈ supp x a', by rw ←hfi; apply h',
refine (mem_supp x _ u).mp hh _ _ hu, },
rintros ⟨a, f, xeq, h⟩ p, rw liftp_iff, split,
{ rintros ⟨a', f', xeq', h'⟩ i u usuppx,
rcases (mem_supp x _ u).mp @usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩,
rw ←f'ieq, apply h' },
intro h',
refine ⟨a, f, xeq.symm, _⟩, intros j y,
apply h', rw mem_supp,
intros a' f' xeq',
apply h _ a' f' xeq',
apply mem_image_of_mem _ (mem_univ _)
end
variable (q)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def is_uniform : Prop := ∀ ⦃α : typevec n⦄ (a a' : q.P.A)
(f : q.P.B a ⟹ α) (f' : q.P.B a' ⟹ α),
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → ∀ i, f i '' univ = f' i '' univ
/-- does `abs` preserve `liftp`? -/
def liftp_preservation : Prop :=
∀ ⦃α : typevec n⦄ (p : Π ⦃i⦄, α i → Prop) (x : q.P.obj α), liftp p (abs x) ↔ liftp p x
/-- does `abs` preserve `supp`? -/
def supp_preservation : Prop :=
∀ ⦃α⦄ (x : q.P.obj α), supp (abs x) = supp x
variable [q]
theorem supp_eq_of_is_uniform (h : q.is_uniform) {α : typevec n} (a : q.P.A) (f : q.P.B a ⟹ α) :
∀ i, supp (abs ⟨a, f⟩) i = f i '' univ :=
begin
intro, ext u, rw [mem_supp], split,
{ intro h', apply h' _ _ rfl },
intros h' a' f' e,
rw [←h _ _ _ _ e.symm], apply h'
end
theorem liftp_iff_of_is_uniform (h : q.is_uniform) {α : typevec n} (x : F α) (p : Π i, α i → Prop) :
liftp p x ↔ ∀ i (u ∈ supp x i), p i u :=
begin
rw [liftp_iff, ←abs_repr x],
cases repr x with a f, split,
{ rintros ⟨a', f', abseq, hf⟩ u,
rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq],
rintros b ⟨i, _, hi⟩, rw ←hi, apply hf },
intro h',
refine ⟨a, f, rfl, λ _ i, h' _ _ _⟩,
rw supp_eq_of_is_uniform h,
exact ⟨i, mem_univ i, rfl⟩
end
theorem supp_map (h : q.is_uniform) {α β : typevec n} (g : α ⟹ β) (x : F α) (i) :
supp (g <$$> x) i = g i '' supp x i :=
begin
rw ←abs_repr x, cases repr x with a f, rw [←abs_map, mvpfunctor.map_eq],
rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, ← image_comp],
refl,
end
theorem supp_preservation_iff_uniform :
q.supp_preservation ↔ q.is_uniform :=
begin
split,
{ intros h α a a' f f' h' i,
rw [← mvpfunctor.supp_eq,← mvpfunctor.supp_eq,← h,h',h] },
{ rintros h α ⟨a,f⟩, ext, rwa [supp_eq_of_is_uniform,mvpfunctor.supp_eq], }
end
theorem supp_preservation_iff_liftp_preservation :
q.supp_preservation ↔ q.liftp_preservation :=
begin
split; intro h,
{ rintros α p ⟨a,f⟩,
have h' := h, rw supp_preservation_iff_uniform at h',
dsimp only [supp_preservation,supp] at h,
simp only [liftp_iff_of_is_uniform, supp_eq_of_is_uniform, mvpfunctor.liftp_iff', h',
image_univ, mem_range, exists_imp_distrib],
split; intros; subst_vars; solve_by_elim },
{ rintros α ⟨a,f⟩,
simp only [liftp_preservation] at h,
ext, simp [supp,h] }
end
theorem liftp_preservation_iff_uniform :
q.liftp_preservation ↔ q.is_uniform :=
by rw [← supp_preservation_iff_liftp_preservation, supp_preservation_iff_uniform]
end mvqpf
|
68d6cf29a22275ff3ab057bcee1caab7c508a31b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/eqn_lemma.lean | be3beb1f69254107ef5fd86543627bfd9ae27fe7 | [
"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 | 483 | lean | def foo : ℕ → ℕ
| 0 := 1
| (n+1) := match n with 0 := 2 | _ := 1 end
lemma foo.faux_eqn (n) : foo n = 42 := sorry
open tactic
run_cmd do
e ← get_env,
trace $ e.get_eqn_lemmas_for ``foo,
trace $ e.get_ext_eqn_lemmas_for ``foo,
set_env $ e.add_eqn_lemma ``foo.faux_eqn
#eval do
e ← get_env,
trace $ e.get_eqn_lemmas_for ``foo,
trace $ e.get_ext_eqn_lemmas_for ``foo
-- success: we've taught lean a new and exciting simp lemma!
example : ∀ n, foo n = 42 := by simp [foo] |
89f00b277ac7f5e97434c46bf899be1fae7d8828 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/fin/tuple/basic.lean | cfc60e1bedab6067a9ac0e661daefdeb3c445a1c | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 27,857 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Yury Kudryashov, Sébastien Gouëzel, Chris Hughes
-/
import data.fin.basic
import data.pi.lex
/-!
# Operation on tuples
We interpret maps `Π i : fin n, α i` as `n`-tuples of elements of possibly varying type `α i`,
`(α 0, …, α (n-1))`. A particular case is `fin n → α` of elements with all the same type.
In this case when `α i` is a constant map, then tuples are isomorphic (but not definitionally equal)
to `vector`s.
We define the following operations:
* `fin.tail` : the tail of an `n+1` tuple, i.e., its last `n` entries;
* `fin.cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple;
* `fin.init` : the beginning of an `n+1` tuple, i.e., its first `n` entries;
* `fin.snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc`
comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order.
* `fin.insert_nth` : insert an element to a tuple at a given position.
* `fin.find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied.
-/
universes u v
namespace fin
variables {m n : ℕ}
open function
section tuple
/-- There is exactly one tuple of size zero. -/
example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) :=
by apply_instance
@[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g :=
fin_zero_elim
variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ))
(i : fin n) (y : α i.succ) (z : α 0)
/-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/
def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ
lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} :
tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl
/-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/
def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i :=
λ j, fin.cases x p j
@[simp] lemma tail_cons : tail (cons x p) = p :=
by simp [tail, cons]
@[simp] lemma cons_succ : cons x p i.succ = p i :=
by simp [cons]
@[simp] lemma cons_zero : cons x p 0 = x :=
by simp [cons]
/-- Updating a tuple and adding an element at the beginning commute. -/
@[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp [ne.symm (succ_ne_zero i)] },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ],
by_cases h' : j' = i,
{ rw h', simp },
{ have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj],
rw [update_noteq h', update_noteq this, cons_succ] } }
end
/-- As a binary function, `fin.cons` is injective. -/
lemma cons_injective2 : function.injective2 (@cons n α) :=
λ x₀ y₀ x y h, ⟨congr_fun h 0, funext $ λ i, by simpa using congr_fun h (fin.succ i)⟩
@[simp] lemma cons_eq_cons {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)} :
cons x₀ x = cons y₀ y ↔ x₀ = y₀ ∧ x = y :=
cons_injective2.eq_iff
lemma cons_left_injective (x : Π i : fin n, α (i.succ)) : function.injective (λ x₀, cons x₀ x) :=
cons_injective2.left _
lemma cons_right_injective (x₀ : α 0) : function.injective (cons x₀) :=
cons_injective2.right _
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_cons_zero : update (cons x p) 0 z = cons z p :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ simp only [h, update_noteq, ne.def, not_false_iff],
let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, cons_succ] }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma cons_self_tail : cons (q 0) (tail q) = q :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, tail, cons_succ] }
end
/-- Recurse on an `n+1`-tuple by splitting it into a single element and an `n`-tuple. -/
@[elab_as_eliminator]
def cons_induction {P : (Π i : fin n.succ, α i) → Sort v}
(h : ∀ x₀ x, P (fin.cons x₀ x)) (x : (Π i : fin n.succ, α i)) : P x :=
_root_.cast (by rw cons_self_tail) $ h (x 0) (tail x)
@[simp] lemma cons_induction_cons {P : (Π i : fin n.succ, α i) → Sort v}
(h : Π x₀ x, P (fin.cons x₀ x)) (x₀ : α 0) (x : Π i : fin n, α i.succ) :
@cons_induction _ _ _ h (cons x₀ x) = h x₀ x :=
begin
rw [cons_induction, cast_eq],
congr',
exact tail_cons _ _
end
@[simp] lemma forall_fin_zero_pi {α : fin 0 → Sort*} {P : (Π i, α i) → Prop} :
(∀ x, P x) ↔ P fin_zero_elim :=
⟨λ h, h _, λ h x, subsingleton.elim fin_zero_elim x ▸ h⟩
@[simp] lemma exists_fin_zero_pi {α : fin 0 → Sort*} {P : (Π i, α i) → Prop} :
(∃ x, P x) ↔ P fin_zero_elim :=
⟨λ ⟨x, h⟩, subsingleton.elim x fin_zero_elim ▸ h, λ h, ⟨_, h⟩⟩
lemma forall_fin_succ_pi {P : (Π i, α i) → Prop} :
(∀ x, P x) ↔ (∀ a v, P (fin.cons a v)) :=
⟨λ h a v, h (fin.cons a v), cons_induction⟩
lemma exists_fin_succ_pi {P : (Π i, α i) → Prop} :
(∃ x, P x) ↔ (∃ a v, P (fin.cons a v)) :=
⟨λ ⟨x, h⟩, ⟨x 0, tail x, (cons_self_tail x).symm ▸ h⟩, λ ⟨a, v, h⟩, ⟨_, h⟩⟩
/-- Updating the first element of a tuple does not change the tail. -/
@[simp] lemma tail_update_zero : tail (update q 0 z) = tail q :=
by { ext j, simp [tail, fin.succ_ne_zero] }
/-- Updating a nonzero element and taking the tail commute. -/
@[simp] lemma tail_update_succ :
tail (update q i.succ y) = update (tail q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [tail] },
{ simp [tail, (fin.succ_injective n).ne h, h] }
end
lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) :
g ∘ (cons y q) = cons (g y) (g ∘ q) :=
begin
ext j,
by_cases h : j = 0,
{ rw h, refl },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, comp_app, cons_succ] }
end
lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (tail q) = tail (g ∘ q) :=
by { ext j, simp [tail] }
lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p :=
forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail]
lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q :=
@le_cons _ (λ i, (α i)ᵒᵈ) _ x q p
lemma cons_le_cons [Π i, preorder (α i)] {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)} :
cons x₀ x ≤ cons y₀ y ↔ x₀ ≤ y₀ ∧ x ≤ y :=
forall_fin_succ.trans $ and_congr_right' $ by simp only [cons_succ, pi.le_def]
lemma pi_lex_lt_cons_cons {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)}
(s : Π {i : fin n.succ}, α i → α i → Prop) :
pi.lex (<) @s (fin.cons x₀ x) (fin.cons y₀ y) ↔
s x₀ y₀ ∨ x₀ = y₀ ∧ pi.lex (<) (λ i : fin n, @s i.succ) x y :=
begin
simp_rw [pi.lex, fin.exists_fin_succ, fin.cons_succ, fin.cons_zero, fin.forall_fin_succ],
simp [and_assoc, exists_and_distrib_left],
end
@[simp]
lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) :
set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) :=
begin
ext y,
simp only [set.mem_range, set.mem_insert_iff],
split,
{ rintros ⟨i, rfl⟩,
refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i,
rw cons_succ },
{ rintros (rfl | ⟨i, hi⟩),
{ exact ⟨0, fin.cons_zero _ _⟩ },
{ refine ⟨i.succ, _⟩,
rw [cons_succ, hi] } }
end
/-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce
one of length `o = m + n`. `ho` provides control of definitional equality
for the vector length. -/
def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α :=
λ i, if h : (i : ℕ) < m
then u ⟨i, h⟩
else v ⟨(i : ℕ) - m, (tsub_lt_iff_left (le_of_not_lt h)).2 (ho ▸ i.property)⟩
@[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n)
(u : fin (m + 1) → α) (v : fin n → α) :
fin.append ho u v 0 = u 0 := rfl
end tuple
section tuple_right
/-! In the previous section, we have discussed inserting or removing elements on the left of a
tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed
inductively from `fin n` starting from the left, not from the right. This implies that Lean needs
more help to realize that elements belong to the right types, i.e., we need to insert casts at
several places. -/
variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ)
(i : fin n) (y : α i.cast_succ) (z : α (last n))
/-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/
def init (q : Πi, α i) (i : fin n) : α i.cast_succ :=
q i.cast_succ
lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} :
init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl
/-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from
`cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/
def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i :=
if h : i.val < n
then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h))
else _root_.cast (by rw eq_last_of_not_lt h) x
@[simp] lemma init_snoc : init (snoc p x) = p :=
begin
ext i,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [init, snoc, i.is_lt, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i :=
begin
have : i.cast_succ.val < n := i.is_lt,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [snoc, this, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_comp_cast_succ {n : ℕ} {α : Sort*} {a : α} {f : fin n → α} :
(snoc f a : fin (n + 1) → α) ∘ cast_succ = f :=
funext (λ i, by rw [function.comp_app, snoc_cast_succ])
@[simp] lemma snoc_last : snoc p x (last n) = x :=
by { simp [snoc] }
@[simp] lemma snoc_comp_nat_add {n m : ℕ} {α : Sort*} (f : fin (m + n) → α) (a : α) :
(snoc f a : fin _ → α) ∘ (nat_add m : fin (n + 1) → fin (m + n + 1)) = snoc (f ∘ nat_add m) a :=
begin
ext i,
refine fin.last_cases _ (λ i, _) i,
{ simp only [function.comp_app],
rw [snoc_last, nat_add_last, snoc_last] },
{ simp only [function.comp_app],
rw [snoc_cast_succ, nat_add_cast_succ, snoc_cast_succ] }
end
@[simp] lemma snoc_cast_add {α : fin (n + m + 1) → Type*}
(f : Π i : fin (n + m), α (cast_succ i)) (a : α (last (n + m)))
(i : fin n) :
(snoc f a) (cast_add (m + 1) i) = f (cast_add m i) :=
dif_pos _
@[simp] lemma snoc_comp_cast_add {n m : ℕ} {α : Sort*} (f : fin (n + m) → α) (a : α) :
(snoc f a : fin _ → α) ∘ cast_add (m + 1) = f ∘ cast_add m :=
funext (snoc_cast_add f a)
/-- Updating a tuple and adding an element at the end commute. -/
@[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y :=
begin
ext j,
by_cases h : j.val < n,
{ simp only [snoc, h, dif_pos],
by_cases h' : j = cast_succ i,
{ have C1 : α i.cast_succ = α j, by rw h',
have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y,
{ have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp,
convert this,
{ exact h'.symm },
{ exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } },
have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)),
by rw [cast_succ_cast_lt, h'],
have E2 : update p i y (cast_lt j h) = _root_.cast C2 y,
{ have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y,
by simp,
convert this,
{ simp [h, h'] },
{ exact heq_of_cast_eq C2 rfl } },
rw [E1, E2],
exact eq_rec_compose _ _ _ },
{ have : ¬(cast_lt j h = i),
by { assume E, apply h', rw [← E, cast_succ_cast_lt] },
simp [h', this, snoc, h] } },
{ rw eq_last_of_not_lt h,
simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] }
end
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc] },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt],
have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _,
rw ← cast_eq rfl (q j),
congr' 1; rw A },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Updating the last element of a tuple does not change the beginning. -/
@[simp] lemma init_update_last : init (update q (last n) z) = init q :=
by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] }
/-- Updating an element and taking the beginning commute. -/
@[simp] lemma init_update_cast_succ :
init (update q i.cast_succ y) = update (init q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [init] },
{ simp [init, h] }
end
/-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) :
tail (init q) = init (tail q) :=
by { ext i, simp [tail, init, cast_succ_fin_succ] }
/-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) :
@cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b :=
begin
ext i,
by_cases h : i = 0,
{ rw h, refl },
set j := pred i h with ji,
have : i = j.succ, by rw [ji, succ_pred],
rw [this, cons_succ],
by_cases h' : j.val < n,
{ set k := cast_lt j h' with jk,
have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt],
rw [this, ← cast_succ_fin_succ],
simp },
rw [eq_last_of_not_lt h', succ_last],
simp
end
lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) :
g ∘ (snoc q y) = snoc (g ∘ q) (g y) :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, this, snoc, cast_succ_cast_lt] },
{ rw eq_last_of_not_lt h,
simp }
end
lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (init q) = init (g ∘ q) :=
by { ext j, simp [init] }
end tuple_right
section insert_nth
variables {α : fin (n+1) → Type u} {β : Type v}
/-- Define a function on `fin (n + 1)` from a value on `i : fin (n + 1)` and values on each
`fin.succ_above i j`, `j : fin n`. This version is elaborated as eliminator and works for
propositions, see also `fin.insert_nth` for a version without an `@[elab_as_eliminator]`
attribute. -/
@[elab_as_eliminator]
def succ_above_cases {α : fin (n + 1) → Sort u} (i : fin (n + 1)) (x : α i)
(p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j :=
if hj : j = i then eq.rec x hj.symm
else if hlt : j < i then eq.rec_on (succ_above_cast_lt hlt) (p _)
else eq.rec_on (succ_above_pred $ (ne.lt_or_lt hj).resolve_left hlt) (p _)
lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) :
(∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) :=
⟨λ h, ⟨h _, λ j, h _⟩, λ h, succ_above_cases i h.1 h.2⟩
/-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`,
for `i = fin.last n` see `fin.snoc`. See also `fin.succ_above_cases` for a version elaborated
as an eliminator. -/
def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) :
α j :=
succ_above_cases i x p j
@[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) :
insert_nth i x p i = x :=
by simp [insert_nth, succ_above_cases]
@[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j))
(j : fin n) :
insert_nth i x p (i.succ_above j) = p j :=
begin
simp only [insert_nth, succ_above_cases, dif_neg (succ_above_ne _ _)],
by_cases hlt : j.cast_succ < i,
{ rw [dif_pos ((succ_above_lt_iff _ _).2 hlt)],
apply eq_of_heq ((eq_rec_heq _ _).trans _),
rw [cast_lt_succ_above hlt] },
{ rw [dif_neg (mt (succ_above_lt_iff _ _).1 hlt)],
apply eq_of_heq ((eq_rec_heq _ _).trans _),
rw [pred_succ_above (le_of_not_lt hlt)] }
end
@[simp] lemma succ_above_cases_eq_insert_nth :
@succ_above_cases.{u + 1} = @insert_nth.{u} := rfl
@[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) :
insert_nth i x p ∘ i.succ_above = p :=
funext $ insert_nth_apply_succ_above i x p
lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
by simp [funext_iff, forall_iff_succ_above i, eq_comm]
lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
eq_comm.trans insert_nth_eq_iff
lemma insert_nth_apply_below {i j : fin (n + 1)} (h : j < i) (x : α i)
(p : Π k, α (i.succ_above k)) :
i.insert_nth x p j = eq.rec_on (succ_above_cast_lt h) (p $ j.cast_lt _) :=
by rw [insert_nth, succ_above_cases, dif_neg h.ne, dif_pos h]
lemma insert_nth_apply_above {i j : fin (n + 1)} (h : i < j) (x : α i)
(p : Π k, α (i.succ_above k)) :
i.insert_nth x p j = eq.rec_on (succ_above_pred h) (p $ j.pred _) :=
by rw [insert_nth, succ_above_cases, dif_neg h.ne', dif_neg h.not_lt]
lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) :
insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
convert (cons_succ _ _ _).symm
end
@[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) 0 x p = cons x p :=
by simp [insert_nth_zero]
lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) :
insert_nth (last n) x p =
snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
apply eq_of_heq,
transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ,
{ rw [snoc_cast_succ], exact (cast_heq _ _).symm },
{ apply congr_arg_heq,
rw [succ_above_last] }
end
@[simp] lemma insert_nth_last' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) (last n) x p = snoc p x :=
by simp [insert_nth_last]
@[simp] lemma insert_nth_zero_right [Π j, has_zero (α j)] (i : fin (n + 1)) (x : α i) :
i.insert_nth x 0 = pi.single i x :=
insert_nth_eq_iff.2 $ by simp [succ_above_ne, pi.zero_def]
lemma insert_nth_binop (op : Π j, α j → α j → α j) (i : fin (n + 1))
(x y : α i) (p q : Π j, α (i.succ_above j)) :
i.insert_nth (op i x y) (λ j, op _ (p j) (q j)) =
λ j, op j (i.insert_nth x p j) (i.insert_nth y q j) :=
insert_nth_eq_iff.2 $ by simp
@[simp] lemma insert_nth_mul [Π j, has_mul (α j)] (i : fin (n + 1))
(x y : α i) (p q : Π j, α (i.succ_above j)) :
i.insert_nth (x * y) (p * q) = i.insert_nth x p * i.insert_nth y q :=
insert_nth_binop (λ _, (*)) i x y p q
@[simp] lemma insert_nth_add [Π j, has_add (α j)] (i : fin (n + 1))
(x y : α i) (p q : Π j, α (i.succ_above j)) :
i.insert_nth (x + y) (p + q) = i.insert_nth x p + i.insert_nth y q :=
insert_nth_binop (λ _, (+)) i x y p q
@[simp] lemma insert_nth_div [Π j, has_div (α j)] (i : fin (n + 1))
(x y : α i) (p q : Π j, α (i.succ_above j)) :
i.insert_nth (x / y) (p / q) = i.insert_nth x p / i.insert_nth y q :=
insert_nth_binop (λ _, (/)) i x y p q
@[simp] lemma insert_nth_sub [Π j, has_sub (α j)] (i : fin (n + 1))
(x y : α i) (p q : Π j, α (i.succ_above j)) :
i.insert_nth (x - y) (p - q) = i.insert_nth x p - i.insert_nth y q :=
insert_nth_binop (λ _, has_sub.sub) i x y p q
@[simp] lemma insert_nth_sub_same [Π j, add_group (α j)] (i : fin (n + 1))
(x y : α i) (p : Π j, α (i.succ_above j)) :
i.insert_nth x p - i.insert_nth y p = pi.single i (x - y) :=
by simp_rw [← insert_nth_sub, ← insert_nth_zero_right, pi.sub_def, sub_self, pi.zero_def]
variables [Π i, preorder (α i)]
lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) :=
by simp [pi.le_def, forall_iff_succ_above i]
lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p :=
by simp [pi.le_def, forall_iff_succ_above i]
open set
lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)}
{q₁ q₂ : Π j, α j} :
i.insert_nth x p ∈ Icc q₁ q₂ ↔
x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm]
lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∈ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and]
lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∉ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq]
end insert_nth
section find
/-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied. -/
def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n)
| 0 p _ := none
| (n+1) p _ := by resetI; exact option.cases_on
(@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _)
(if h : p (fin.last n) then some (fin.last n) else none)
(λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2)))
/-- If `find p = some i`, then `p i` holds -/
lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p), p i
| 0 p I i hi := option.no_confusion hi
| (n+1) p I i hi := begin
dsimp [find] at hi,
resetI,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ rw h at hi,
dsimp at hi,
split_ifs at hi with hl hl,
{ exact hi ▸ hl },
{ exact hi.elim } },
{ rw h at hi,
rw [← option.some_inj.1 hi],
exact find_spec _ h }
end
/-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/
lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p],
by exactI (find p).is_some ↔ ∃ i, p i
| 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i)
| (n+1) p _ := ⟨λ h, begin
rw [option.is_some_iff_exists] at h,
cases h with i hi,
exactI ⟨i, find_spec _ hi⟩
end, λ ⟨⟨i, hin⟩, hi⟩,
begin
resetI,
dsimp [find],
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ split_ifs with hl hl,
{ exact option.is_some_some },
{ have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2
⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin)
(λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩,
rw h at this,
exact this } },
{ simp }
end⟩
/-- `find p` returns `none` if and only if `p i` never holds. -/
lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] :
find p = none ↔ ∀ i, ¬ p i :=
by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp
/-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among
the indices where `p` holds. -/
lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j
| 0 p _ i hi j hj hpj := option.no_confusion hi
| (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin
resetI,
dsimp [find] at hi,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k,
{ rw [h] at hi,
split_ifs at hi with hl hl,
{ subst hi,
rw [find_eq_none_iff] at h,
exact h ⟨j, hj⟩ hpj },
{ exact hi.elim } },
{ rw h at hi,
dsimp at hi,
obtain rfl := option.some_inj.1 hi,
exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj }
end
lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n}
(h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j :=
le_of_not_gt (λ hij, find_min h hij hj)
lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p]
(h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) :
(⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p :=
let ⟨i, hin, hi⟩ := h in
begin
cases hf : find p with f,
{ rw [find_eq_none_iff] at hf,
exact (hf ⟨i, hin⟩ hi).elim },
{ refine option.some_inj.2 (le_antisymm _ _),
{ exact find_min' hf (nat.find_spec h).snd },
{ exact nat.find_min' _ ⟨f.2, by convert find_spec p hf;
exact fin.eta _ _⟩ } }
end
lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j :=
⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩,
begin
rintros ⟨hpi, hj⟩,
cases hfp : fin.find p,
{ rw [find_eq_none_iff] at hfp,
exact (hfp _ hpi).elim },
{ exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) }
end⟩
lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j :=
mem_find_iff
lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p]
(h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p :=
mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩
end find
/-- To show two sigma pairs of tuples agree, it to show the second elements are related via
`fin.cast`. -/
lemma sigma_eq_of_eq_comp_cast {α : Type*} :
∀ {a b : Σ ii, fin ii → α} (h : a.fst = b.fst), a.snd = b.snd ∘ fin.cast h → a = b
| ⟨ai, a⟩ ⟨bi, b⟩ hi h :=
begin
dsimp only at hi,
subst hi,
simpa using h,
end
/-- `fin.sigma_eq_of_eq_comp_cast` as an `iff`. -/
lemma sigma_eq_iff_eq_comp_cast {α : Type*} {a b : Σ ii, fin ii → α} :
a = b ↔ ∃ (h : a.fst = b.fst), a.snd = b.snd ∘ fin.cast h :=
⟨λ h, h ▸ ⟨rfl, funext $ subtype.rec $ by exact λ i hi, rfl⟩,
λ ⟨h, h'⟩, sigma_eq_of_eq_comp_cast _ h'⟩
end fin
|
af41266a3dce937fbbb5f7faecc04caab861560f | cf39355caa609c0f33405126beee2739aa3cb77e | /leanpkg/leanpkg/main.lean | 458aaee75235d7b593523274f0fb2f0eb82e256f | [
"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 | 12,052 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
-/
import leanpkg.resolve leanpkg.git
namespace leanpkg
def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do
h ← io.mk_file_handle fn io.mode.write,
io.fs.write h cnts.to_char_buffer,
io.fs.close h
def read_manifest : io manifest := do
m ← manifest.from_file leanpkg_toml_fn,
when (m.lean_version ≠ lean_version_string) $
io.print_ln $ "\nWARNING: Lean version mismatch: installed version is " ++ lean_version_string
++ ", but package requires " ++ m.lean_version ++ "\n",
return m
def write_manifest (d : manifest) (fn := leanpkg_toml_fn) : io unit :=
write_file fn (repr d)
-- TODO(gabriel): implement a cross-platform api
def get_dot_lean_dir : io string := do
some home ← io.env.get "HOME" | io.fail "environment variable HOME is not set",
return $ home ++ "/.lean"
def mk_path_file : ∀ (paths : list string), string
| [] := "builtin_path\n"
| (x :: xs) := mk_path_file xs ++ "path " ++ x ++ "\n"
def configure : io unit := do
d ← read_manifest,
io.put_str_ln $ "configuring " ++ d.name ++ " " ++ d.version,
when (d.path ≠ some "src") $ io.put_str_ln "WARNING: leanpkg configurations not specifying `path = \"src\"` are deprecated.",
assg ← solve_deps d,
path_file_cnts ← mk_path_file <$> construct_path assg,
write_file "leanpkg.path" path_file_cnts
def make (lean_args : list string) : io unit := do
manifest ← read_manifest,
exec_cmd {
cmd := "lean",
args := (match manifest.timeout with some t := ["-T", repr t] | none := [] end) ++
["--make"] ++ manifest.effective_path ++ lean_args,
env := [("LEAN_PATH", none)]
}
def build (lean_args : list string) := configure >> make lean_args
def make_test (lean_args : list string) : io unit :=
exec_cmd { cmd := "lean", args := ["--make", "test"] ++ lean_args, env := [("LEAN_PATH", none)] }
def test (lean_args : list string) := build lean_args >> make_test lean_args
def init_gitignore_contents :=
"*.olean
/_target
/leanpkg.path
"
def init_pkg (n : string) (from_new : bool) : io unit := do
write_manifest { name := n, path := "src", version := "0.1" } leanpkg_toml_fn,
src_ex ← io.fs.dir_exists "src",
when (¬src_ex) (do
when ¬from_new $ io.put_str_ln "Move existing .lean files into the 'src' folder.",
io.fs.mkdir "src" >> return ()),
write_file ".gitignore" init_gitignore_contents io.mode.append,
git_ex ← io.fs.dir_exists ".git",
when (¬git_ex) (do {
exec_cmd {cmd := "git", args := ["init", "-q"]},
when (upstream_git_branch ≠ "master") $
exec_cmd {cmd := "git", args := ["checkout", "-b", upstream_git_branch]}
} <|> io.print_ln "WARNING: failed to initialize git repository"),
configure
def init (n : string) := init_pkg n false
-- TODO(gabriel): windows
def basename (s : string) : string :=
s.fold "" $ λ s c, if c = '/' then "" else s.str c
def add_dep_to_manifest (dep : dependency) : io unit := do
d ← read_manifest,
let d' := { d with dependencies := d.dependencies.filter (λ old_dep, old_dep.name ≠ dep.name) ++ [dep] },
write_manifest d'
def strip_dot_git (url : string) : string :=
if url.backn 4 = ".git" then url.popn_back 4 else url
def looks_like_git_url (dep : string) : bool :=
':' ∈ dep.to_list
def parse_add_dep (dep : string) (branch : option string) : io dependency :=
if looks_like_git_url dep then
pure { name := basename (strip_dot_git dep), src := source.git dep (git_default_revision branch) branch }
else do
ex ← io.fs.dir_exists dep,
if ex then match branch with
| some branch := io.fail sformat!"extraneous trailing path argument '{branch}'"
| none := pure { name := basename dep, src := source.path dep }
end
else do
[user, repo] ← pure $ dep.split (= '/')
| io.fail sformat!"path '{dep}' does not exist",
pure { name := repo, src := source.git sformat!"https://github.com/{user}/{repo}" (git_default_revision branch) branch }
def absolutize_dep (dep : dependency) : io dependency :=
match dep.src with
| source.path p := do
cwd ← io.env.get_cwd,
pure {src := source.path (resolve_dir p cwd), ..dep}
| _ := pure dep
end
def parse_install_dep (dep : string) (branch : option string) : io dependency := do
dep ← parse_add_dep dep none,
dep ← absolutize_dep dep,
dot_lean_dir ← get_dot_lean_dir,
io.fs.mkdir dot_lean_dir tt,
let user_toml_fn := dot_lean_dir ++ "/" ++ leanpkg_toml_fn,
ex ← io.fs.file_exists user_toml_fn,
when (¬ ex) $ write_manifest {
name := "_user_local_packages",
version := "1"
} user_toml_fn,
change_dir dot_lean_dir,
return dep
def fixup_git_version (dir : string) : ∀ (src : source), io source
| (source.git url _ _) := do
rev ← git_head_revision dir,
return $ source.git url rev none
| src := return src
def add (dep : dependency) : io unit := do
(_, assg) ← (materialize "." dep).run assignment.empty,
some downloaded_path ← return (assg.find dep.name),
manif ← manifest.from_file (downloaded_path ++ "/" ++ leanpkg_toml_fn),
src ← fixup_git_version downloaded_path dep.src,
let dep := { dep with name := manif.name, src := src },
add_dep_to_manifest dep,
configure
def new (dir : string) := do
ex ← io.fs.dir_exists dir,
when ex $ io.fail $ "directory already exists: " ++ dir,
io.fs.mkdir dir tt,
change_dir dir,
init_pkg (basename dir) true
def upgrade_dep (assg : assignment) (d : dependency) : io dependency :=
match d.src with
| (source.git url rev branch) := (do
some path ← return (assg.find d.name) | io.fail "unresolved dependency",
new_rev ← git_latest_origin_revision path branch,
return {d with src := source.git url new_rev branch})
<|> return d
| _ := return d
end
def upgrade := do
m ← read_manifest,
assg ← solve_deps m,
ds' ← m.dependencies.mmap (upgrade_dep assg),
write_manifest {m with dependencies := ds'},
configure
def usage :=
"Lean package manager, version " ++ ui_lean_version_string ++ "
Usage: leanpkg <command>
configure download dependencies
build [-- <lean-args>] download dependencies and build *.olean files
test [-- <lean-args>] download dependencies, build *.olean files, and run test files
new <dir> create a Lean package in a new directory
init <name> create a Lean package in the current directory
add <url> [branch] add a dependency from a git repository (uses latest upstream revision)
add <dir> add a local dependency
upgrade upgrade all git dependencies to the latest upstream version
install <url> [branch] install a user-wide package from git
install <dir> install a user-wide package from a local directory
dump print the parsed leanpkg.toml file (for debugging)
See `leanpkg help <command>` for more information on a specific command."
def main : ∀ (cmd : string) (leanpkg_args lean_args : list string), io unit
| "configure" [] [] := configure
| "build" _ lean_args := build lean_args
| "test" _ lean_args := test lean_args
| "new" [dir] [] := new dir
| "init" [name] [] := init name
| "add" [dep] [] := parse_add_dep dep none >>= add
| "add" [dep] [branch] := parse_add_dep dep branch >>= add
| "upgrade" [] [] := upgrade
| "install" [dep] [] := parse_install_dep dep none >>= add >> build []
| "install" [dep] [branch] := parse_install_dep dep branch >>= add >> build []
| "dump" [] [] := read_manifest >>= io.print_ln ∘ repr
| "help" ["configure"] [] := io.print_ln "Download dependencies
Usage:
leanpkg configure
This command sets up the `_target/deps` directory and the `leanpkg.path` file.
For each (transitive) git dependency, the specified commit is checked out
into a sub-directory of `_target/deps`. If there are dependencies on multiple
versions of the same package, the version materialized is undefined.
The `leanpkg.path` file used to resolve Lean imports is populated with paths
to the `src` directories of all (transitive) dependencies. No copy is made
of local dependencies."
| "help" ["build"] [] := io.print_ln "Download dependencies and build *.olean files
Usage:
leanpkg build [-- <lean-args>]
This command invokes `leanpkg configure` followed by
`lean --make src <lean-args>`, building the package's Lean files as well as
(transitively) imported files of dependencies. If defined, the `package.timeout`
configuration value is passed to Lean via its `-T` parameter."
| "help" ["test"] [] := io.print_ln "Download dependencies, build *.olean files, and run test files
Usage:
leanpkg test [-- <lean-args>]
This command invokes `leanpkg build <lean-args>` followed by
`lean --make test <lean-args>`, executing the package's test files. A failed
test should generate a Lean error message, which makes this command return a
non-zero exit code."
| "help" ["add"] [] := io.print_ln sformat!"Add a dependency
Usage:
leanpkg add <local-path>
leanpkg add <git-url>
leanpkg add <github-user>/<github-repo>
Examples:
leanpkg add ../mathlib
leanpkg add https://github.com/leanprover/mathlib
leanpkg add leanprover/mathlib
This command adds the specified local or git dependency, then calls
`leanpkg configure`. For git dependencies, the pinned commit is
the head of the branch `lean-<version>` (e.g. `lean-3.3.0`) on stable
releases of Lean, or else `master` (current branch: {upstream_git_branch})."
| "help" ["new"] [] := io.print_ln "Create a new Lean package in a new directory
Usage:
leanpkg new <path>/.../<name>
This command creates a new Lean package named '<name>' in a new directory
`<path>/.../<name>`. A new git repository is initialized to the branch name
expected by `leanpkg add` (see `leanpkg help add`).
For converting an existing directory into a Lean package, use `leanpkg init`."
| "help" ["init"] [] := io.print_ln "Create a new Lean package in the current directory
Usage:
leanpkg init <name>
This command creates a new Lean package with the given name in the current
directory. Existing Lean source files should be moved into the new `src`
directory."
| "help" ["upgrade"] [] := io.print_ln "Upgrade all git dependencies to the latest upstream version
Usage:
leanpkg upgrade
This command fetches the remote repositories of all git dependencies and updates
the pinned commits to the head of the respective branch (see
`leanpkg help add`)."
| "help" ["install"] [] := io.print_ln "Install a user-wide package
Usage:
leanpkg install <local-path>
leanpkg install <git-url>
leanpkg install <github-user>/<github-repo>
This command adds a dependency to a user-wide \"meta\" package in `~/.lean`.
For files not part of a Lean package, Lean falls back to the core library
and this meta package for import resolution.
For removing or upgrading user-wide dependencies, you currently have to change
into `~/.lean` yourself and edit the leanpkg.toml file or execute
`leanpkg upgrade`, respectively."
| "help" _ [] := io.print_ln usage
| _ _ _ := io.fail usage
private def split_cmdline_args_core : list string → list string × list string
| [] := ([], [])
| (arg::args) := if arg = "--"
then ([], args)
else match split_cmdline_args_core args with
| (outer_args, inner_args) := (arg::outer_args, inner_args)
end
def split_cmdline_args : list string → io (string × list string × list string)
| [] := io.fail usage
| [cmd] := return (cmd, [], [])
| (cmd::rest) := match split_cmdline_args_core rest with
| (outer_args, inner_args) := return (cmd, outer_args, inner_args)
end
end leanpkg
def main : io unit :=
do (cmd, outer_args, inner_args) ← io.cmdline_args >>= leanpkg.split_cmdline_args,
leanpkg.main cmd outer_args inner_args
|
a388c7061abba6f2715b296998127bbca37eecfa | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/analysis/analytic/basic.lean | f7771db2e91ab4f0d87a87e13a4492472369b1a4 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 37,862 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.times_cont_diff
import tactic.omega
import analysis.special_functions.pow
/-!
# Analytic functions
A function is analytic in one dimension around `0` if it can be written as a converging power series
`Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by
requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two
dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a
vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not
always possible in nonzero characteristic (in characteristic 2, the previous example has no
symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition,
and we only require the existence of a converging series.
The general framework is important to say that the exponential map on bounded operators on a Banach
space is analytic, as well as the inverse on invertible operators.
## Main definitions
Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n`
for `n : ℕ`.
* `p.radius`: the largest `r : ennreal` such that `∥p n∥ * r^n` grows subexponentially, defined as
a liminf.
* `p.le_radius_of_bound`, `p.bound_of_lt_radius`, `p.geometric_bound_of_lt_radius`: relating the
value of the radius with the growth of `∥p n∥ * r^n`.
* `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`.
* `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`.
Additionally, let `f` be a function from `E` to `F`.
* `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`,
`f (x + y) = ∑'_n pₙ yⁿ`.
* `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds
`has_fpower_series_on_ball f p x r`.
* `analytic_at 𝕜 f x`: there exists a power series `p` such that holds
`has_fpower_series_at f p x`.
We develop the basic properties of these notions, notably:
* If a function admits a power series, it is continuous (see
`has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and
`analytic_at.continuous_at`).
* In a complete space, the sum of a formal power series with positive radius is well defined on the
disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`.
* If a function admits a power series in a ball, then it is analytic at any point `y` of this ball,
and the power series there can be expressed in terms of the initial power series `p` as
`p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that
the set of points at which a given function is analytic is open, see `is_open_analytic_at`.
## Implementation details
We only introduce the radius of convergence of a power series, as `p.radius`.
For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent)
notion, describing the polydisk of convergence. This notion is more specific, and not necessary to
build the general theory. We do not define it here.
-/
noncomputable theory
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{G : Type*} [normed_group G] [normed_space 𝕜 G]
open_locale topological_space classical big_operators
open filter
/-! ### The radius of a formal multilinear series -/
namespace formal_multilinear_series
/-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ pₙ yⁿ`
converges for all `∥y∥ < r`. -/
def radius (p : formal_multilinear_series 𝕜 E F) : ennreal :=
liminf at_top (λ n, 1/((nnnorm (p n)) ^ (1 / (n : ℝ)) : nnreal))
/--If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/
lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : nnreal) {r : nnreal}
(h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ennreal) ≤ p.radius :=
begin
have L : tendsto (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal))
at_top (𝓝 ((r : ennreal) / ((C + 1)^(0 : ℝ) : nnreal))),
{ apply ennreal.tendsto.div tendsto_const_nhds,
{ simp },
{ rw ennreal.tendsto_coe,
apply tendsto_const_nhds.nnrpow (tendsto_const_div_at_top_nhds_0_nat 1),
simp },
{ simp } },
have A : ∀ n : ℕ , 0 < n →
(r : ennreal) ≤ ((C + 1)^(1/(n : ℝ)) : nnreal) * (1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal)),
{ assume n npos,
simp only [one_div_eq_inv, mul_assoc, mul_one, eq.symm ennreal.mul_div_assoc],
rw [ennreal.le_div_iff_mul_le _ _, ← nnreal.pow_nat_rpow_nat_inv r npos, ← ennreal.coe_mul,
ennreal.coe_le_coe, ← nnreal.mul_rpow, mul_comm],
{ exact nnreal.rpow_le_rpow (le_trans (h n) (le_add_right (le_refl _))) (by simp) },
{ simp },
{ simp } },
have B : ∀ᶠ (n : ℕ) in at_top,
(r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal) ≤ 1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal),
{ apply eventually_at_top.2 ⟨1, λ n hn, _⟩,
rw [ennreal.div_le_iff_le_mul, mul_comm],
{ apply A n hn },
{ simp },
{ simp } },
have D : liminf at_top (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) ≤ p.radius :=
liminf_le_liminf B,
rw L.liminf_eq at D,
simpa using D
end
/-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/
lemma bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal}
(h : (r : ennreal) < p.radius) : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C :=
begin
obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ n, n ≥ N → (r : ennreal) < 1 / ↑(nnnorm (p n) ^ (1 / (n : ℝ))) :=
eventually.exists_forall_of_at_top (eventually_lt_of_lt_liminf h),
obtain ⟨D, hD⟩ : ∃D, ∀ x ∈ (↑((finset.range N.succ).image (λ i, nnnorm (p i) * r^i))), x ≤ D :=
finset.bdd_above _,
refine ⟨max D 1, λ n, _⟩,
cases le_or_lt n N with hn hn,
{ refine le_trans _ (le_max_left D 1),
apply hD,
have : n ∈ finset.range N.succ := list.mem_range.mpr (nat.lt_succ_iff.mpr hn),
exact finset.mem_image_of_mem _ this },
{ by_cases hpn : nnnorm (p n) = 0, { simp [hpn] },
have A : nnnorm (p n) ^ (1 / (n : ℝ)) ≠ 0, by simp [nnreal.rpow_eq_zero_iff, hpn],
have B : r < (nnnorm (p n) ^ (1 / (n : ℝ)))⁻¹,
{ have := hN n (le_of_lt hn),
rwa [ennreal.div_def, ← ennreal.coe_inv A, one_mul, ennreal.coe_lt_coe] at this },
rw [nnreal.lt_inv_iff_mul_lt A, mul_comm] at B,
have : (nnnorm (p n) ^ (1 / (n : ℝ)) * r) ^ n ≤ 1 :=
pow_le_one n (zero_le (nnnorm (p n) ^ (1 / ↑n) * r)) (le_of_lt B),
rw [mul_pow, one_div_eq_inv, nnreal.rpow_nat_inv_pow_nat _ (lt_of_le_of_lt (zero_le _) hn)]
at this,
exact le_trans this (le_max_right _ _) },
end
/-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially. -/
lemma geometric_bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal}
(h : (r : ennreal) < p.radius) : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r^n ≤ C * a^n :=
begin
obtain ⟨t, rt, tp⟩ : ∃ (t : nnreal), (r : ennreal) < t ∧ (t : ennreal) < p.radius :=
ennreal.lt_iff_exists_nnreal_btwn.1 h,
rw ennreal.coe_lt_coe at rt,
have tpos : t ≠ 0 := ne_of_gt (lt_of_le_of_lt (zero_le _) rt),
obtain ⟨C, hC⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * t^n ≤ C := p.bound_of_lt_radius tp,
refine ⟨r / t, C, nnreal.div_lt_one_of_lt rt, λ n, _⟩,
calc nnnorm (p n) * r ^ n
= (nnnorm (p n) * t ^ n) * (r / t) ^ n : by { field_simp [tpos], ac_refl }
... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (zero_le _)
end
/-- The radius of the sum of two formal series is at least the minimum of their two radii. -/
lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) :
min p.radius q.radius ≤ (p + q).radius :=
begin
refine le_of_forall_ge_of_dense (λ r hr, _),
cases r, { simpa using hr },
obtain ⟨Cp, hCp⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C :=
p.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_left _ _)),
obtain ⟨Cq, hCq⟩ : ∃ (C : nnreal), ∀ n, nnnorm (q n) * r^n ≤ C :=
q.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_right _ _)),
have : ∀ n, nnnorm ((p + q) n) * r^n ≤ Cp + Cq,
{ assume n,
calc nnnorm (p n + q n) * r ^ n
≤ (nnnorm (p n) + nnnorm (q n)) * r ^ n :
mul_le_mul_of_nonneg_right (norm_add_le (p n) (q n)) (zero_le (r ^ n))
... ≤ Cp + Cq : by { rw add_mul, exact add_le_add (hCp n) (hCq n) } },
exact (p + q).le_radius_of_bound _ this
end
lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius :=
by simp [formal_multilinear_series.radius, nnnorm_neg]
/-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A
priori, it only behaves well when `∥x∥ < p.radius`. -/
protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F :=
tsum (λn:ℕ, p n (λ(i : fin n), x))
/-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum
`Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/
def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F :=
∑ k in finset.range n, p k (λ(i : fin k), x)
/-- The partial sums of a formal multilinear series are continuous. -/
lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
continuous (p.partial_sum n) :=
continuous_finset_sum (finset.range n) $ λ k hk, (p k).cont.comp (continuous_pi (λ i, continuous_id))
end formal_multilinear_series
/-! ### Expanding a function as a power series -/
section
variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ennreal}
/-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as
a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/
structure has_fpower_series_on_ball
(f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ennreal) : Prop :=
(r_le : r ≤ p.radius)
(r_pos : 0 < r)
(has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y)))
/-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as
a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/
def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) :=
∃ r, has_fpower_series_on_ball f p x r
variable (𝕜)
/-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power
series expansion around `x`. -/
def analytic_at (f : E → F) (x : E) :=
∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x
variable {𝕜}
lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) :
has_fpower_series_at f p x := ⟨r, hf⟩
lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x :=
⟨p, hf⟩
lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) :
analytic_at 𝕜 f x :=
hf.has_fpower_series_at.analytic_at
lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) :
0 < p.radius :=
lt_of_lt_of_le hf.r_pos hf.r_le
lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) :
0 < p.radius :=
let ⟨r, hr⟩ := hf in hr.radius_pos
lemma has_fpower_series_on_ball.mono
(hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) :
has_fpower_series_on_ball f p x r' :=
⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩
lemma has_fpower_series_on_ball.add
(hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) :
has_fpower_series_on_ball (f + g) (pf + pg) x r :=
{ r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg),
r_pos := hf.r_pos,
has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) }
lemma has_fpower_series_at.add
(hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) :
has_fpower_series_at (f + g) (pf + pg) x :=
begin
rcases hf with ⟨rf, hrf⟩,
rcases hg with ⟨rg, hrg⟩,
have P : 0 < min rf rg, by simp [hrf.r_pos, hrg.r_pos],
exact ⟨min rf rg, (hrf.mono P (min_le_left _ _)).add (hrg.mono P (min_le_right _ _))⟩
end
lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) :
analytic_at 𝕜 (f + g) x :=
let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at
lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) :
has_fpower_series_on_ball (-f) (-pf) x r :=
{ r_le := by { rw pf.radius_neg, exact hf.r_le },
r_pos := hf.r_pos,
has_sum := λ y hy, (hf.has_sum hy).neg }
lemma has_fpower_series_at.neg
(hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x :=
let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at
lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x :=
let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at
lemma has_fpower_series_on_ball.sub
(hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) :
has_fpower_series_on_ball (f - g) (pf - pg) x r :=
hf.add hg.neg
lemma has_fpower_series_at.sub
(hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) :
has_fpower_series_at (f - g) (pf - pg) x :=
hf.add hg.neg
lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) :
analytic_at 𝕜 (f - g) x :=
hf.add hg.neg
lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r)
(v : fin 0 → E) : pf 0 v = f x :=
begin
have v_eq : v = (λ i, 0), by { ext i, apply fin_zero_elim i },
have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos],
have : ∀ i ≠ 0, pf i (λ j, 0) = 0,
{ assume i hi,
have : 0 < i := bot_lt_iff_ne_bot.mpr hi,
apply continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i),
refl },
have A := (hf.has_sum zero_mem).unique (has_sum_single _ this),
simpa [v_eq] using A.symm,
end
lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) :
pf 0 v = f x :=
let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v
/-- If a function admits a power series expansion, then it is exponentially close to the partial
sums of this power series on strict subdisks of the disk of convergence. -/
lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : nnreal}
(hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) :
∃ (a C : nnreal), a < 1 ∧ (∀ y ∈ metric.ball (0 : E) r', ∀ n,
∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) :=
begin
obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r' ^n ≤ C * a^n :=
p.geometric_bound_of_lt_radius (lt_of_lt_of_le h hf.r_le),
refine ⟨a, C / (1 - a), ha, λ y hy n, _⟩,
have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy },
have : y ∈ emetric.ball (0 : E) r,
{ rw [emetric.mem_ball, edist_eq_coe_nnnorm],
apply lt_trans _ h,
rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe],
exact yr' },
simp only [nnreal.coe_sub (le_of_lt ha), nnreal.coe_sub, nnreal.coe_div, nnreal.coe_one],
rw [← dist_eq_norm, dist_comm, dist_eq_norm, ← mul_div_right_comm],
apply norm_sub_le_of_geometric_bound_of_has_sum ha _ (hf.has_sum this),
assume n,
calc ∥(p n) (λ (i : fin n), y)∥
≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _
... = nnnorm (p n) * (nnnorm y)^n : by simp
... ≤ nnnorm (p n) * r' ^ n :
mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left (nnreal.coe_nonneg _) (le_of_lt yr') _)
(nnreal.coe_nonneg _)
... ≤ C * a ^ n : by exact_mod_cast hC n,
end
/-- If a function admits a power series expansion at `x`, then it is the uniform limit of the
partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)`
is the uniform limit of `p.partial_sum n y` there. -/
lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : nnreal}
(hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) :
tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') :=
begin
rcases hf.uniform_geometric_approx h with ⟨a, C, ha, hC⟩,
refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _),
have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) :=
tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 (a.2) ha),
rw mul_zero at L,
apply ((tendsto_order.1 L).2 ε εpos).mono (λ n hn, _),
assume y hy,
rw dist_eq_norm,
exact lt_of_le_of_lt (hC y hy n) hn
end
/-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of
the partial sums of this power series on the disk of convergence, i.e., `f (x + y)`
is the locally uniform limit of `p.partial_sum n y` there. -/
lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on
(hf : has_fpower_series_on_ball f p x r) :
tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y))
at_top (emetric.ball (0 : E) r) :=
begin
assume u hu x hx,
rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩,
have : emetric.ball (0 : E) r' ∈ 𝓝 x :=
mem_nhds_sets emetric.is_open_ball xr',
refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩,
simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu
end
/-- If a function admits a power series expansion at `x`, then it is the uniform limit of the
partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y`
is the uniform limit of `p.partial_sum n (y - x)` there. -/
lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : nnreal}
(hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) :
tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') :=
begin
convert (hf.tendsto_uniformly_on h).comp (λ y, y - x),
{ ext z, simp },
{ ext z, simp [dist_eq_norm] }
end
/-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of
the partial sums of this power series on the disk of convergence, i.e., `f y`
is the locally uniform limit of `p.partial_sum n (y - x)` there. -/
lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on'
(hf : has_fpower_series_on_ball f p x r) :
tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) :=
begin
have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) :=
(continuous_id.sub continuous_const).continuous_on,
convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A,
{ ext z, simp },
{ assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] }
end
/-- If a function admits a power series expansion on a disk, then it is continuous there. -/
lemma has_fpower_series_on_ball.continuous_on
(hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) :=
hf.tendsto_locally_uniformly_on'.continuous_on $ λ n,
((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on
lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x :=
let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos))
lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x :=
let ⟨p, hp⟩ := hf in hp.continuous_at
/-- In a complete space, the sum of a converging power series `p` admits `p` as a power series.
This is not totally obvious as we need to check the convergence of the series. -/
lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F]
(p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) :
has_fpower_series_on_ball p.sum p 0 p.radius :=
{ r_le := le_refl _,
r_pos := h,
has_sum := λ y hy, begin
rw zero_add,
replace hy : (nnnorm y : ennreal) < p.radius,
by { convert hy, exact (edist_eq_coe_nnnorm _).symm },
obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm y)^n ≤ C * a^n :=
p.geometric_bound_of_lt_radius hy,
refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n)
((summable_geometric_of_lt_1 a.2 ha).mul_left _) (λ n, _)).has_sum,
calc ∥(p n) (λ (i : fin n), y)∥
≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _
... = nnnorm (p n) * (nnnorm y)^n : by simp
... ≤ C * a ^ n : by exact_mod_cast hC n
end }
lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r)
{y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y :=
begin
have A := h.has_sum hy,
have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le),
simpa using A.unique B
end
/-- The sum of a converging power series is continuous in its disk of convergence. -/
lemma formal_multilinear_series.continuous_on [complete_space F] :
continuous_on p.sum (emetric.ball 0 p.radius) :=
begin
by_cases h : 0 < p.radius,
{ exact (p.has_fpower_series_on_ball h).continuous_on },
{ simp at h,
simp [h, continuous_on_empty] }
end
end
/-!
### Changing origin in a power series
If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that
one. Indeed, one can write
$$
f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \choose n k p_n y^{n-k} z^k
= \sum_{k} (\sum_{n} \choose n k p_n y^{n-k}) z^k.
$$
The corresponding power series has thus a `k`-th coefficient equal to
`\sum_{n} \choose n k p_n y^{n-k}`. In the general case where `pₙ` is a multilinear map, this has
to be interpreted suitably: instead of having a binomial coefficient, one should sum over all
possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and
`y` to the indices outside of `s`.
In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we
check its convergence and the fact that its sum coincides with the original sum. The outcome of this
discussion is that the set of points where a function is analytic is open.
-/
namespace formal_multilinear_series
variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : nnreal}
/--
Changing the origin of a formal multilinear series `p`, so that
`p.sum (x+y) = (p.change_origin x).sum y` when this makes sense.
Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda,
as this leads to a bad definition with auxiliary `_match` statements,
but we will try to use pattern matching in lambdas as much as possible in the proofs below
to increase readability.
-/
def change_origin (x : E) :
formal_multilinear_series 𝕜 E F :=
λ k, tsum (λi, (p i.1).restr i.2.1 i.2.2 x :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))
/-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of
`p.change_origin`, first version. -/
-- Note here and below it is necessary to use `@` and provide implicit arguments using `_`,
-- so that it is possible to use pattern matching in the lambda.
-- Overall this seems a good trade-off in readability.
lemma change_origin_summable_aux1 (h : (nnnorm x + r : ennreal) < p.radius) :
@summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) :
(Σ (n : ℕ), finset (fin n)) → ℝ) :=
begin
obtain ⟨a, C, ha, hC⟩ :
∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm x + r) ^ n ≤ C * a^n :=
p.geometric_bound_of_lt_radius h,
let Bnnnorm : (Σ (n : ℕ), finset (fin n)) → nnreal :=
λ ⟨n, s⟩, nnnorm (p n) * (nnnorm x) ^ (n - s.card) * r ^ s.card,
have : ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) :
(Σ (n : ℕ), finset (fin n)) → ℝ) = (λ b, (Bnnnorm b : ℝ)),
by { ext ⟨n, s⟩, simp [Bnnnorm, nnreal.coe_pow, coe_nnnorm] },
rw [this, nnreal.summable_coe, ← ennreal.tsum_coe_ne_top_iff_summable],
apply ne_of_lt,
calc (∑' b, ↑(Bnnnorm b))
= (∑' n, (∑' s, ↑(Bnnnorm ⟨n, s⟩))) : by exact ennreal.tsum_sigma' _
... ≤ (∑' n, (((nnnorm (p n) * (nnnorm x + r)^n) : nnreal) : ennreal)) :
begin
refine ennreal.tsum_le_tsum (λ n, _),
rw [tsum_fintype, ← ennreal.coe_finset_sum, ennreal.coe_le_coe],
apply le_of_eq,
calc ∑ s : finset (fin n), Bnnnorm ⟨n, s⟩
= ∑ s : finset (fin n), nnnorm (p n) * ((nnnorm x) ^ (n - s.card) * r ^ s.card) :
by simp [← mul_assoc]
... = nnnorm (p n) * (nnnorm x + r) ^ n :
by { rw [add_comm, ← finset.mul_sum, ← fin.sum_pow_mul_eq_add_pow], congr, ext1 s, ring }
end
... ≤ (∑' (n : ℕ), (C * a ^ n : ennreal)) :
tsum_le_tsum (λ n, by exact_mod_cast hC n) ennreal.summable ennreal.summable
... < ⊤ :
by simp [ennreal.mul_eq_top, ha, ennreal.tsum_mul_left, ennreal.tsum_geometric,
ennreal.lt_top_iff_ne_top]
end
/-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of
`p.change_origin`, second version. -/
lemma change_origin_summable_aux2 (h : (nnnorm x + r : ennreal) < p.radius) :
@summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) :
(Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) :=
begin
let γ : ℕ → Type* := λ k, (Σ (n : ℕ), {s : finset (fin n) // s.card = k}),
let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card,
have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h,
let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card,
have SAnorm : summable Anorm,
{ refine summable_of_norm_bounded _ SBnorm (λ i, _),
rcases i with ⟨n, s⟩,
suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤
(∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card),
{ have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)],
simpa [Anorm, Bnorm, this] using H },
exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x)
(pow_nonneg (nnreal.coe_nonneg _) _) },
let e : (Σ (n : ℕ), finset (fin n)) ≃
(Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) :=
{ to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩,
inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩,
left_inv := λ ⟨n, s⟩, rfl,
right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } },
rw ← e.summable_iff,
convert SAnorm,
ext ⟨n, s⟩,
refl
end
/-- An auxiliary definition for `change_origin_radius`. -/
def change_origin_summable_aux_j (k : ℕ) :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k})
→ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) :=
λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩
lemma change_origin_summable_aux_j_injective (k : ℕ) :
function.injective (change_origin_summable_aux_j k) :=
begin
rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a,
simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a,
rcases a with ⟨rfl, a⟩,
simpa using a,
end
/-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of
`p.change_origin`, third version. -/
lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) :
@summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) :=
begin
obtain ⟨r, rpos, hr⟩ : ∃ (r : nnreal), 0 < r ∧ ((nnnorm x + r) : ennreal) < p.radius :=
ennreal.lt_iff_exists_add_pos_lt.mp h,
have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ),
{ convert (p.change_origin_summable_aux2 hr).comp_injective
(change_origin_summable_aux_j_injective k),
-- again, cleanup that could be done by `tidy`:
ext ⟨_, ⟨_, _⟩⟩, refl },
have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos],
apply (summable_mul_right_iff this).2,
convert S,
-- again, cleanup that could be done by `tidy`:
ext ⟨_, ⟨_, _⟩⟩, refl,
end
-- FIXME this causes a deterministic timeout with `-T50000`
/-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words,
`p.change_origin x` is well defined on the largest ball contained in the original ball of
convergence.-/
lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius :=
begin
by_cases h : p.radius ≤ nnnorm x,
{ have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h,
rw this,
exact zero_le _ },
replace h : (nnnorm x : ennreal) < p.radius, by simpa using h,
refine le_of_forall_ge_of_dense (λ r hr, _),
cases r, { simpa using hr },
rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr,
let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ :=
λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k,
have SA : summable A := p.change_origin_summable_aux2 hr,
have A_nonneg : ∀ i, 0 ≤ A i,
{ rintros ⟨k, n, s, hs⟩,
change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k,
refine mul_nonneg (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) },
have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg,
apply le_radius_of_bound _ (nnreal.of_real (tsum A)) (λ k, _),
rw [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_pow, coe_nnnorm,
nnreal.coe_of_real _ tsum_nonneg],
calc ∥change_origin p x k∥ * ↑r ^ k
= ∥@tsum (E [×k]→L[𝕜] F) _ _ _ (λ i, (p i.1).restr i.2.1 i.2.2 x :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))∥ * ↑r ^ k : rfl
... ≤ tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) * ↑r ^ k :
begin
apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _),
apply norm_tsum_le_tsum_norm,
convert p.change_origin_summable_aux3 k h,
ext a,
tidy
end
... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) :
by { rw tsum_mul_right, convert p.change_origin_summable_aux3 k h, tidy }
... = tsum (A ∘ change_origin_summable_aux_j k) : by { congr, tidy }
... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_injective k)
end
-- From this point on, assume that the space is complete, to make sure that series that converge
-- in norm also converge in `F`.
variable [complete_space F]
/-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/
lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) :
@has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) :
(Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))
(p.change_origin x k) :=
begin
apply summable.has_sum,
apply summable_of_summable_norm,
convert p.change_origin_summable_aux3 k h,
tidy
end
/-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/
theorem change_origin_eval (h : (nnnorm x + nnnorm y : ennreal) < p.radius) :
has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) :=
begin
/- The series on the left is a series of series. If we order the terms differently, we get back
to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below,
the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a
series of terms `B`, and we show that they correspond to each other by reordering to conclude the
proof. -/
have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h,
-- `A` is the terms of the series whose sum gives the series for `p.change_origin`
let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F :=
λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y),
-- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity.
let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y),
let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card,
have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h,
have SB : summable B,
{ refine summable_of_norm_bounded _ SBnorm _,
rintros ⟨n, s⟩,
calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥
≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card :
begin
convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y),
simp [(finset.prod_const (∥y∥))],
end
... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card :
mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) },
-- Check that indeed the sum of `B` is `p (x + y)`.
have has_sum_B : has_sum B (p.sum (x + y)),
{ have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)),
{ assume n,
have : (p n) (λ (i : fin n), y + x) = ∑ s : finset (fin n),
p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x)) :=
(p n).map_add_univ (λ i, y) (λ i, x),
simp [add_comm y x] at this,
rw this,
exact has_sum_fintype _ },
have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)),
{ have : x + y ∈ emetric.ball (0 : E) p.radius,
{ apply lt_of_le_of_lt _ h,
rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe],
exact norm_add_le x y },
simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this },
exact has_sum.sigma_of_has_sum K2 K1 SB },
-- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to
-- reordering
have has_sum_A : has_sum A (p.sum (x + y)),
{ let e : (Σ (n : ℕ), finset (fin n)) ≃
(Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) :=
{ to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩,
inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩,
left_inv := λ ⟨n, s⟩, rfl,
right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } },
have : A ∘ e = B, by { ext ⟨⟩, refl },
rw ← e.has_sum_iff,
convert has_sum_B },
-- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series
-- defining `p.change_origin`, by definition
have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)),
{ assume k,
have : (nnnorm x : ennreal) < radius p := lt_of_le_of_lt (le_add_right (le_refl _)) h,
convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this)
(λ(i : fin k), y),
ext i,
tidy },
exact has_sum_A.sigma J
end
end formal_multilinear_series
section
variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E}
{r : ennreal}
/-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a
power series on any subball of this ball (even with a different center), given by `p.change_origin`.
-/
theorem has_fpower_series_on_ball.change_origin
(hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ennreal) < r) :
has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) :=
{ r_le := begin
apply le_trans _ p.change_origin_radius,
exact ennreal.sub_le_sub hf.r_le (le_refl _)
end,
r_pos := by simp [h],
has_sum := begin
assume z hz,
have A : (nnnorm y : ennreal) + nnnorm z < r,
{ have : edist z 0 < r - ↑(nnnorm y) := hz,
rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this },
convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le),
have : y + z ∈ emetric.ball (0 : E) r := calc
edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) :
by { rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le y z }
... < r : A,
simpa only [add_assoc] using hf.sum this
end }
lemma has_fpower_series_on_ball.analytic_at_of_mem
(hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) :
analytic_at 𝕜 f y :=
begin
have : (nnnorm (y - x) : ennreal) < r, by simpa [edist_eq_coe_nnnorm_sub] using h,
have := hf.change_origin this,
rw [add_sub_cancel'_right] at this,
exact this.analytic_at
end
variables (𝕜 f)
lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} :=
begin
rw is_open_iff_forall_mem_open,
assume x hx,
rcases hx with ⟨p, r, hr⟩,
refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩,
simp only [edist_self, emetric.mem_ball, hr.r_pos]
end
variables {𝕜 f}
end
|
6a367cb66bb822c3eb8544a448657ae6add9dd49 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/set_theory/schroeder_bernstein.lean | 21e5211d3a00301cf3b0a4f0b0a1d4b81c65919f | [
"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 | 5,352 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import order.fixed_points
import order.zorn
/-!
# Schröder-Bernstein theorem, well-ordering of cardinals
This file proves the Schröder-Bernstein theorem (see `schroeder_bernstein`), the well-ordering of
cardinals (see `min_injective`) and the totality of their order (see `total`).
## Notes
Cardinals are naturally ordered by `α ≤ β ↔ ∃ f : a → β, injective f`:
* `schroeder_bernstein` states that, given injections `α → β` and `β → α`, one can get a
bijection `α → β`. This corresponds to the antisymmetry of the order.
* The order is also well-founded: any nonempty set of cardinals has a minimal element.
`min_injective` states that by saying that there exists an element of the set that injects into
all others.
Cardinals are defined and further developed in the file `set_theory.cardinal`.
-/
open set function
open_locale classical
universes u v
namespace function
namespace embedding
section antisymm
variables {α : Type u} {β : Type v}
/-- **The Schröder-Bernstein Theorem**:
Given injections `α → β` and `β → α`, we can get a bijection `α → β`. -/
theorem schroeder_bernstein {f : α → β} {g : β → α}
(hf : function.injective f) (hg : function.injective g) : ∃ h : α → β, bijective h :=
begin
casesI is_empty_or_nonempty β with hβ hβ,
{ haveI : is_empty α, from function.is_empty f,
exact ⟨_, ((equiv.equiv_empty α).trans (equiv.equiv_empty β).symm).bijective⟩ },
set F : set α →o set α :=
{ to_fun := λ s, (g '' (f '' s)ᶜ)ᶜ,
monotone' := λ s t hst, compl_subset_compl.mpr $ image_subset _ $
compl_subset_compl.mpr $ image_subset _ hst },
set s : set α := F.lfp,
have hs : (g '' (f '' s)ᶜ)ᶜ = s, from F.map_lfp,
have hns : g '' (f '' s)ᶜ = sᶜ, from compl_injective (by simp [hs]),
set g' := inv_fun g,
have g'g : left_inverse g' g, from left_inverse_inv_fun hg,
have hg'ns : g' '' sᶜ = (f '' s)ᶜ, by rw [← hns, g'g.image_image],
set h : α → β := s.piecewise f g',
have : surjective h, by rw [← range_iff_surjective, range_piecewise, hg'ns, union_compl_self],
have : injective h,
{ refine (injective_piecewise_iff _).2 ⟨hf.inj_on _, _, _⟩,
{ intros x hx y hy hxy,
obtain ⟨x', hx', rfl⟩ : x ∈ g '' (f '' s)ᶜ, by rwa hns,
obtain ⟨y', hy', rfl⟩ : y ∈ g '' (f '' s)ᶜ, by rwa hns,
rw [g'g _, g'g _] at hxy, rw hxy },
{ intros x hx y hy hxy,
obtain ⟨y', hy', rfl⟩ : y ∈ g '' (f '' s)ᶜ, by rwa hns,
rw [g'g _] at hxy,
exact hy' ⟨x, hx, hxy⟩ } },
exact ⟨h, ‹injective h›, ‹surjective h›⟩
end
/-- **The Schröder-Bernstein Theorem**: Given embeddings `α ↪ β` and `β ↪ α`, there exists an
equivalence `α ≃ β`. -/
theorem antisymm : (α ↪ β) → (β ↪ α) → nonempty (α ≃ β)
| ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ :=
let ⟨f, hf⟩ := schroeder_bernstein h₁ h₂ in
⟨equiv.of_bijective f hf⟩
end antisymm
section wo
parameters {ι : Type u} {β : ι → Type v}
@[reducible] private def sets := {s : set (∀ i, β i) |
∀ (x ∈ s) (y ∈ s) i, (x : ∀ i, β i) i = y i → x = y}
/-- The cardinals are well-ordered. We express it here by the fact that in any set of cardinals
there is an element that injects into the others. See `cardinal.linear_order` for (one of) the
lattice instance. -/
theorem min_injective (I : nonempty ι) : ∃ i, nonempty (∀ j, β i ↪ β j) :=
let ⟨s, hs, ms⟩ := show ∃ s ∈ sets, ∀ a ∈ sets, s ⊆ a → a = s, from
zorn_subset sets (λ c hc hcc, ⟨⋃₀ c,
λ x ⟨p, hpc, hxp⟩ y ⟨q, hqc, hyq⟩ i hi, (hcc.total hpc hqc).elim
(λ h, hc hqc x (h hxp) y hyq i hi) (λ h, hc hpc x hxp y (h hyq) i hi),
λ _, subset_sUnion_of_mem⟩) in
let ⟨i, e⟩ := show ∃ i, ∀ y, ∃ x ∈ s, (x : ∀ i, β i) i = y, from
classical.by_contradiction $ λ h,
have h : ∀ i, ∃ y, ∀ x ∈ s, (x : ∀ i, β i) i ≠ y,
by simpa only [not_exists, not_forall] using h,
let ⟨f, hf⟩ := classical.axiom_of_choice h in
have f ∈ s, from
have insert f s ∈ sets := λ x hx y hy, begin
cases hx; cases hy, {simp [hx, hy]},
{ subst x, exact λ i e, (hf i y hy e.symm).elim },
{ subst y, exact λ i e, (hf i x hx e).elim },
{ exact hs x hx y hy }
end, ms _ this (subset_insert f s) ▸ mem_insert _ _,
let ⟨i⟩ := I in hf i f this rfl in
let ⟨f, hf⟩ := classical.axiom_of_choice e in
⟨i, ⟨λ j, ⟨λ a, f a j, λ a b e',
let ⟨sa, ea⟩ := hf a, ⟨sb, eb⟩ := hf b in
by rw [← ea, ← eb, hs _ sa _ sb _ e']⟩⟩⟩
end wo
/-- The cardinals are totally ordered. See `cardinal.linear_order` for (one of) the lattice
instance. -/
theorem total {α : Type u} {β : Type v} : nonempty (α ↪ β) ∨ nonempty (β ↪ α) :=
match @min_injective bool (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) ⟨tt⟩ with
| ⟨tt, ⟨h⟩⟩ := let ⟨f, hf⟩ := h ff in or.inl ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩
| ⟨ff, ⟨h⟩⟩ := let ⟨f, hf⟩ := h tt in or.inr ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩
end
end embedding
end function
|
a690caa518f4e3766d9f6bf7c084036f7ddc31bc | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/calculus/local_extr.lean | 82f432932f2cfbef8f95abdc08c7ee01c1ce5105 | [
"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 | 18,196 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.deriv
import topology.algebra.ordered.extend_from
import topology.algebra.polynomial
import topology.local_extr
import data.polynomial.field_division
/-!
# Local extrema of smooth functions
## Main definitions
In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`.
This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields.
This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or
[Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions).
## Main statements
For each theorem name listed below,
we also prove similar theorems for `min`, `extr` (if applicable)`,
and `(f)deriv` instead of `has_fderiv`.
* `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum
of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent
cone of `s` at `a`.
* `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both
`y` and `-y` belong to the positive tangent cone, then `f' y = 0`.
* `is_local_max.has_fderiv_at_eq_zero` :
[Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)),
the derivative of a differentiable function at a local extremum point equals zero.
* `exists_has_deriv_at_eq_zero` :
[Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous
on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`.
## Implementation notes
For each mathematical fact we prove several versions of its formalization:
* for maxima and minima;
* using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`.
For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible
due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions.
## References
* [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points));
* [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem);
* [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone);
## Tags
local extremum, Fermat's Theorem, Rolle's Theorem
-/
universes u v
open filter set
open_locale topological_space classical
section module
variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E}
{f' : E →L[ℝ] ℝ}
/-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at`
is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at`
as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/
def pos_tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧
(tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) :=
begin
rintros s t hst y ⟨c, d, hd, hc, hcd⟩,
exact ⟨c, d, mem_of_superset hd $ λ h hn, hst hn, hc, hcd⟩
end
lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment ℝ x y ⊆ s) :
y - x ∈ pos_tangent_cone_at s x :=
begin
let c := λn:ℕ, (2:ℝ)^n,
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem' (λn, h _),
tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩,
show x + d n ∈ segment ℝ x y,
{ rw segment_eq_image',
refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩,
exacts [inv_nonneg.2 (pow_nonneg zero_le_two _),
inv_le_one (one_le_pow_of_one_le one_le_two _)] },
show tendsto (λ n, c n • d n) at_top (𝓝 (y - x)),
{ convert tendsto_const_nhds, ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ two_ne_zero }
end
lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E}
(h : segment ℝ x (x + y) ⊆ s) :
y ∈ pos_tangent_cone_at s x :=
by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h
lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ :=
eq_univ_of_forall $ λ x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _)
/-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
f' y ≤ 0 :=
begin
rcases hy with ⟨c, d, hd, hc, hcd⟩,
have hc' : tendsto (λ n, ∥c n∥) at_top at_top,
from tendsto_at_top_mono (λ n, le_abs_self _) hc,
refine le_of_tendsto (hf.lim at_top hd hc' hcd) _,
replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)),
from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd),
by rwa tendsto_principal⟩,
rw [add_zero] at hd,
replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h),
replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))),
filter_upwards [h, hc],
simp only [smul_eq_mul, mem_preimage, subset_def],
assume n hnf hn,
exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf)
end
/-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y ≤ 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $
by simpa using h.has_fderiv_within_at_nonpos hf hy'
/-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
0 ≤ f' y :=
by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy
/-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy'
/-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
begin
ext y,
apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at;
rw pos_tangent_cone_at_univ; apply mem_univ
end
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) :
has_fderiv_at f f' a → f' = 0 :=
h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 :=
h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero
end module
section real
variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ}
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
by simpa using continuous_linear_map.ext_iff.1
(h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) :
has_deriv_at f f' a → f' = 0 :=
h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 :=
h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero
end real
section Rolle
variables (f f' : ℝ → ℝ) {a b : ℝ}
/-- A continuous function on a closed interval with `f a = f b` takes either its maximum
or its minimum value at a point in the interior of the interval. -/
lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c :=
begin
have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab),
-- Consider absolute min and max points
obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x,
from is_compact_Icc.exists_forall_le ne hfc,
obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C,
from is_compact_Icc.exists_forall_ge ne hfc,
by_cases hc : f c = f a,
{ by_cases hC : f C = f a,
{ have : ∀ x ∈ Icc a b, f x = f a,
from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx),
-- `f` is a constant, so we can take any point in `Ioo a b`
rcases exists_between hab with ⟨c', hc'⟩,
refine ⟨c', hc', or.inl _⟩,
assume x hx,
rw [mem_set_of_eq, this x hx, ← hC],
exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ },
{ refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] } },
{ refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] }
end
/-- A continuous function on a closed interval with `f a = f b` has a local extremum at some
point of the corresponding open interval. -/
lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
∃ c ∈ Ioo a b, is_local_extr f c :=
let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI
in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩
/-- **Rolle's Theorem** `has_deriv_at` version -/
lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b)
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) :
∃ c ∈ Ioo a b, f' c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩
/-- **Rolle's Theorem** `deriv` version -/
lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
∃ c ∈ Ioo a b, deriv f c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.deriv_eq_zero⟩
variables {f f'} {l : ℝ}
/-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has derivative `f'`
on `(a, b)` and has the same limit `l` at `𝓝[>] a` and `𝓝[<] b`, then `f' c = 0`
for some `c ∈ (a, b)`. -/
lemma exists_has_deriv_at_eq_zero' (hab : a < b)
(hfa : tendsto f (𝓝[>] a) (𝓝 l)) (hfb : tendsto f (𝓝[<] b) (𝓝 l))
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) :
∃ c ∈ Ioo a b, f' c = 0 :=
begin
have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at,
have hcont := continuous_on_Icc_extend_from_Ioo hab.ne this hfa hfb,
obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c,
{ apply exists_local_extr_Ioo _ hab hcont,
rw eq_lim_at_right_extend_from_Ioo hab hfb,
exact eq_lim_at_left_extend_from_Ioo hab hfa },
use [c, hc],
apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc),
rw eventually_eq_iff_exists_mem,
exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩
end
/-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has the same limit
`l` at `𝓝[>] a` and `𝓝[<] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version
does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not
differentiable at `c`. -/
lemma exists_deriv_eq_zero' (hab : a < b)
(hfa : tendsto f (𝓝[>] a) (𝓝 l)) (hfb : tendsto f (𝓝[<] b) (𝓝 l)) :
∃ c ∈ Ioo a b, deriv f c = 0 :=
classical.by_cases
(assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x,
show ∃ c ∈ Ioo a b, deriv f c = 0,
from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at))
(assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x,
have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h },
let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩)
end Rolle
namespace polynomial
lemma card_root_set_le_derivative {F : Type*} [field F] [algebra F ℝ] (p : polynomial F) :
fintype.card (p.root_set ℝ) ≤ fintype.card (p.derivative.root_set ℝ) + 1 :=
begin
haveI : char_zero F :=
(ring_hom.char_zero_iff (algebra_map F ℝ).injective).mpr (by apply_instance),
by_cases hp : p = 0,
{ simp_rw [hp, derivative_zero, root_set_zero, set.empty_card', zero_le_one] },
by_cases hp' : p.derivative = 0,
{ rw eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_derivative_eq_zero hp'),
simp_rw [root_set_C, set.empty_card', zero_le] },
simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe],
refine finset.card_le_of_interleaved (λ x hx y hy hxy, _),
rw [←finset.mem_coe, ←root_set_def, mem_root_set hp] at hx hy,
obtain ⟨z, hz1, hz2⟩ := exists_deriv_eq_zero (λ x : ℝ, aeval x p) hxy
p.continuous_aeval.continuous_on (hx.trans hy.symm),
refine ⟨z, _, hz1⟩,
rw [←finset.mem_coe, ←root_set_def, mem_root_set hp', ←hz2],
simp_rw [aeval_def, ←eval_map, polynomial.deriv, derivative_map],
end
end polynomial
|
2457d2037db924ca663f0ffeb4da806acc8ce6a6 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/precissues.lean | b2bd418e1238e764c84811417c8f127a21ac4efa | [
"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 | 555 | lean | new_frontend
#check id fun x => x -- should fail
def f (x : Nat) (g : Nat → Nat) := g x
#check f 1 fun x => x -- should fail
#check f 1 (fun x => x)
#check id have True from ⟨⟩; this -- should fail
#check 1
#check id (have True from ⟨⟩; this)
#check 0 = have Nat from 1; this
#check 0 = let x := 0; x
variables (p q r : Prop)
macro_rules `(¬ $p) => `(Not $p)
#check p ↔ ¬ q
#check True = ¬ False
#check p ∧ ¬q
#check ¬p ∧ q
#check ¬p ↔ q
#check ¬(p = q)
#check ¬ p = q
#check id ¬p
#check Nat → ∀ (a : Nat), a = a
|
a6690039a8ef83d4dfc1820867315526b226fbff | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/localization/module.lean | efdab085b7ee2cbfffa0cd23104fe4ef3fca0f68 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,549 | lean | /-
Copyright (c) 2022 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu, Anne Baanen
-/
import linear_algebra.basis
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
/-!
# Modules / vector spaces over localizations / fraction fields
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains some results about vector spaces over the field of fractions of a ring.
## Main results
* `linear_independent.localization`: `b` is linear independent over a localization of `R`
if it is linear independent over `R` itself
* `basis.localization_localization`: promote an `R`-basis `b` of `A` to an `Rₛ`-basis of `Aₛ`,
where `Rₛ` and `Aₛ` are localizations of `R` and `A` at `s` respectively
* `linear_independent.iff_fraction_ring`: `b` is linear independent over `R` iff it is
linear independent over `Frac(R)`
-/
open_locale big_operators
open_locale non_zero_divisors
section localization
variables {R : Type*} (Rₛ : Type*) [comm_ring R] [comm_ring Rₛ] [algebra R Rₛ]
variables (S : submonoid R) [hT : is_localization S Rₛ]
include hT
section add_comm_monoid
variables {M : Type*} [add_comm_monoid M] [module R M] [module Rₛ M] [is_scalar_tower R Rₛ M]
lemma linear_independent.localization {ι : Type*} {b : ι → M} (hli : linear_independent R b) :
linear_independent Rₛ b :=
begin
rw linear_independent_iff' at ⊢ hli,
intros s g hg i hi,
choose! a g' hg' using is_localization.exist_integer_multiples S s g,
specialize hli s g' _ i hi,
{ rw [← @smul_zero _ M _ _ (a : R), ← hg, finset.smul_sum],
refine finset.sum_congr rfl (λ i hi, _),
rw [← is_scalar_tower.algebra_map_smul Rₛ, hg' i hi, smul_assoc],
apply_instance },
refine ((is_localization.map_units Rₛ a).mul_right_eq_zero).mp _,
rw [← algebra.smul_def, ← map_zero (algebra_map R Rₛ), ← hli, hg' i hi],
end
end add_comm_monoid
section localization_localization
variables {A : Type*} [comm_ring A] [algebra R A]
variables (Aₛ : Type*) [comm_ring Aₛ] [algebra A Aₛ]
variables [algebra Rₛ Aₛ] [algebra R Aₛ] [is_scalar_tower R Rₛ Aₛ] [is_scalar_tower R A Aₛ]
variables [hA : is_localization (algebra.algebra_map_submonoid A S) Aₛ]
include hA
open submodule
lemma linear_independent.localization_localization
{ι : Type*} {v : ι → A} (hv : linear_independent R v) :
linear_independent Rₛ (algebra_map A Aₛ ∘ v) :=
begin
rw linear_independent_iff' at ⊢ hv,
intros s g hg i hi,
choose! a g' hg' using is_localization.exist_integer_multiples S s g,
have h0 : algebra_map A Aₛ (∑ i in s, g' i • v i) = 0,
{ apply_fun ((•) (a : R)) at hg,
rw [smul_zero, finset.smul_sum] at hg,
rw [map_sum, ← hg],
refine finset.sum_congr rfl (λ i hi, _),
rw [← smul_assoc, ← hg' i hi, algebra.smul_def, map_mul,
← is_scalar_tower.algebra_map_apply, ← algebra.smul_def, algebra_map_smul] },
obtain ⟨⟨_, r, hrS, rfl⟩, (hr : algebra_map R A r * _ = 0)⟩ :=
(is_localization.map_eq_zero_iff (algebra.algebra_map_submonoid A S) _ _).1 h0,
simp_rw [finset.mul_sum, ← algebra.smul_def, smul_smul] at hr,
specialize hv s _ hr i hi,
rw [← (is_localization.map_units Rₛ a).mul_right_eq_zero, ← algebra.smul_def, ← hg' i hi],
exact (is_localization.map_eq_zero_iff S _ _).2 ⟨⟨r, hrS⟩, hv⟩,
end
lemma span_eq_top.localization_localization {v : set A} (hv : span R v = ⊤) :
span Rₛ (algebra_map A Aₛ '' v) = ⊤ :=
begin
rw eq_top_iff,
rintros a' -,
obtain ⟨a, ⟨_, s, hs, rfl⟩, rfl⟩ := is_localization.mk'_surjective
(algebra.algebra_map_submonoid A S) a',
rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, ← map_one (algebra_map R A)],
erw ← is_localization.algebra_map_mk' A Rₛ Aₛ (1 : R) ⟨s, hs⟩, -- `erw` needed to unify `⟨s, hs⟩`
rw ← algebra.smul_def,
refine smul_mem _ _ (span_subset_span R _ _ _),
rw [← algebra.coe_linear_map, ← linear_map.coe_restrict_scalars R, ← linear_map.map_span],
exact mem_map_of_mem (hv.symm ▸ mem_top),
{ apply_instance }
end
/-- If `A` has an `R`-basis, then localizing `A` at `S` has a basis over `R` localized at `S`.
A suitable instance for `[algebra A Aₛ]` is `localization_algebra`.
-/
noncomputable def basis.localization_localization {ι : Type*} (b : basis ι R A) : basis ι Rₛ Aₛ :=
basis.mk
(b.linear_independent.localization_localization _ S _)
(by { rw [set.range_comp, span_eq_top.localization_localization Rₛ S Aₛ b.span_eq],
exact le_rfl })
@[simp] lemma basis.localization_localization_apply {ι : Type*} (b : basis ι R A) (i) :
b.localization_localization Rₛ S Aₛ i = algebra_map A Aₛ (b i) :=
basis.mk_apply _ _ _
@[simp] lemma basis.localization_localization_repr_algebra_map
{ι : Type*} (b : basis ι R A) (x i) :
(b.localization_localization Rₛ S Aₛ).repr (algebra_map A Aₛ x) i =
algebra_map R Rₛ (b.repr x i) :=
calc (b.localization_localization Rₛ S Aₛ).repr (algebra_map A Aₛ x) i
= (b.localization_localization Rₛ S Aₛ).repr
((b.repr x).sum (λ j c, algebra_map R Rₛ c • algebra_map A Aₛ (b j))) i :
by simp_rw [is_scalar_tower.algebra_map_smul, algebra.smul_def,
is_scalar_tower.algebra_map_apply R A Aₛ, ← _root_.map_mul, ← map_finsupp_sum,
← algebra.smul_def, ← finsupp.total_apply, basis.total_repr]
... = (b.repr x).sum (λ j c, algebra_map R Rₛ c • finsupp.single j 1 i) :
by simp_rw [← b.localization_localization_apply Rₛ S Aₛ, map_finsupp_sum,
linear_equiv.map_smul, basis.repr_self, finsupp.sum_apply, finsupp.smul_apply]
... = _ : finset.sum_eq_single i
(λ j _ hj, by simp [hj])
(λ hi, by simp [finsupp.not_mem_support_iff.mp hi])
... = algebra_map R Rₛ (b.repr x i) : by simp [algebra.smul_def]
end localization_localization
end localization
section fraction_ring
variables (R K : Type*) [comm_ring R] [field K] [algebra R K] [is_fraction_ring R K]
variables {V : Type*} [add_comm_group V] [module R V] [module K V] [is_scalar_tower R K V]
lemma linear_independent.iff_fraction_ring {ι : Type*} {b : ι → V} :
linear_independent R b ↔ linear_independent K b :=
⟨linear_independent.localization K (R⁰),
linear_independent.restrict_scalars (smul_left_injective R one_ne_zero)⟩
end fraction_ring
|
3d096f81b00b6556b3647d5c634c193b7d8641d4 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/data/subtype/basic.lean | 8fad6a04feec0074bf20cf9707797e6b58b6aa8d | [
"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 | 916 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad
-/
prelude
import init.logic
open decidable
universes u
namespace subtype
lemma exists_of_subtype {α : Type u} {p : α → Prop} : { x // p x } → ∃ x, p x
| ⟨a, h⟩ := ⟨a, h⟩
variables {α : Type u} {p : α → Prop}
lemma tag_irrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 :=
rfl
protected lemma eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl
lemma ne_of_val_ne {a1 a2 : {x // p x}} : val a1 ≠ val a2 → a1 ≠ a2 :=
mt $ congr_arg _
lemma eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a :=
subtype.eq rfl
end subtype
open subtype
def subtype.inhabited {α : Type u} {p : α → Prop} {a : α} (h : p a) : inhabited {x // p x} :=
⟨⟨a, h⟩⟩
|
078897861eceee57a6d27177dc335d0daf1e9c67 | de4548698671d50981659ecc9f4910de15969d3d | /Metamath.lean | 7273d88b208a76b3e8f49e90e3e6396e16c898b5 | [] | no_license | digama0/mm-lean4 | 7ad17c81853816c6cd4bb97b8abe4bea0fd35ff6 | 6a427edecb851cec04818848a755c0145a5f2e98 | refs/heads/master | 1,688,934,520,262 | 1,687,937,043,000 | 1,687,937,043,000 | 365,257,017 | 15 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 347 | lean | import Metamath.Verify
open Metamath.Verify in
def main (n : List String) : IO UInt32 := do
let db ← check $ n.getD 0 "set.mm"
match db.error? with
| none =>
IO.println s!"verified, {db.objects.size} objects"
pure 0
| some ⟨Error.error pos err, _⟩ =>
IO.println s!"at {pos}: {err}"
pure 1
| some _ => unreachable!
|
0b3784ae9323b87880de25e32809c7353e198df4 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Server/InfoUtils.lean | 8a809a2c2e31c51e937ad91d1d634fce0886822c | [
"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 | 9,432 | lean | /-
Copyright (c) 2021 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.DocString
import Lean.Elab.InfoTree
import Lean.Util.Sorry
protected structure String.Range where
start : String.Pos
stop : String.Pos
deriving Inhabited, Repr
def String.Range.contains (r : String.Range) (pos : String.Pos) : Bool :=
r.start <= pos && pos < r.stop
def Lean.Syntax.getRange? (stx : Syntax) (originalOnly := false) : Option String.Range :=
match stx.getPos? originalOnly, stx.getTailPos? originalOnly with
| some start, some stop => some { start, stop }
| _, _ => none
namespace Lean.Elab
/--
For every branch, find the deepest node in that branch matching `p`
with a surrounding context (the innermost one) and return all of them. -/
partial def InfoTree.deepestNodes (p : ContextInfo → Info → Std.PersistentArray InfoTree → Option α) : InfoTree → List α :=
go none
where go ctx?
| context ctx t => go ctx t
| n@(node i cs) =>
let ccs := cs.toList.map (go <| i.updateContext? ctx?)
let cs' := ccs.join
if !cs'.isEmpty then cs'
else match ctx? with
| some ctx => match p ctx i cs with
| some a => [a]
| _ => []
| _ => []
| _ => []
partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α :=
go none init
where go ctx? a
| context ctx t => go ctx a t
| node i ts =>
let a := match ctx? with
| none => a
| some ctx => f ctx i a
ts.foldl (init := a) (go <| i.updateContext? ctx?)
| _ => a
def Info.isTerm : Info → Bool
| ofTermInfo _ => true
| _ => false
def Info.isCompletion : Info → Bool
| ofCompletionInfo .. => true
| _ => false
def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) :=
infoTree.foldInfo (init := #[]) fun ctx info result =>
match info with
| Info.ofCompletionInfo info => result.push (ctx, info)
| _ => result
def Info.stx : Info → Syntax
| ofTacticInfo i => i.stx
| ofTermInfo i => i.stx
| ofCommandInfo i => i.stx
| ofMacroExpansionInfo i => i.stx
| ofFieldInfo i => i.stx
| ofCompletionInfo i => i.stx
def Info.lctx : Info → LocalContext
| Info.ofTermInfo i => i.lctx
| Info.ofFieldInfo i => i.lctx
| _ => LocalContext.empty
def Info.pos? (i : Info) : Option String.Pos :=
i.stx.getPos? (originalOnly := true)
def Info.tailPos? (i : Info) : Option String.Pos :=
i.stx.getTailPos? (originalOnly := true)
def Info.range? (i : Info) : Option String.Range :=
i.stx.getRange? (originalOnly := true)
def Info.contains (i : Info) (pos : String.Pos) : Bool :=
i.range?.any (·.contains pos)
def Info.size? (i : Info) : Option Nat := OptionM.run do
let pos ← i.pos?
let tailPos ← i.tailPos?
return tailPos - pos
-- `Info` without position information are considered to have "infinite" size
def Info.isSmaller (i₁ i₂ : Info) : Bool :=
match i₁.size?, i₂.pos? with
| some sz₁, some sz₂ => sz₁ < sz₂
| some _, none => true
| _, _ => false
def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option Nat := OptionM.run do
let tailPos ← i.tailPos?
guard (tailPos ≤ hoverPos)
return hoverPos - tailPos
def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) :=
let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none
let infos := ts.map fun (ci, i) =>
let diff := i.tailPos?.get! - i.pos?.get!
(diff, ci, i)
infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i)
/-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/
partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) :=
t.smallestInfo? fun i => do
if let Info.ofTermInfo ti := i then
if ti.expr.isSyntheticSorry then
return false
if i matches Info.ofFieldInfo _ || i.toElabInfo?.isSome then
return i.contains hoverPos
return false
def Info.type? (i : Info) : MetaM (Option Expr) :=
match i with
| Info.ofTermInfo ti => Meta.inferType ti.expr
| Info.ofFieldInfo fi => Meta.inferType fi.val
| _ => return none
def Info.docString? (i : Info) : MetaM (Option String) := do
let env ← getEnv
if let Info.ofTermInfo ti := i then
if let some n := ti.expr.constName? then
return ← findDocString? env n
if let Info.ofFieldInfo fi := i then
return ← findDocString? env fi.projName
if let some ei := i.toElabInfo? then
return ← findDocString? env ei.elaborator <||> findDocString? env ei.stx.getKind
return none
/-- Construct a hover popup, if any, from an info node in a context.-/
def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do
ci.runMetaM i.lctx do
let mut fmts := #[]
try
if let some f ← fmtTerm? then
fmts := fmts.push f
catch _ => pure ()
if let some m ← i.docString? then
fmts := fmts.push m
if fmts.isEmpty then
none
else
f!"\n***\n".joinSep fmts.toList
where
fmtTerm? : MetaM (Option Format) := do
match i with
| Info.ofTermInfo ti =>
let tp ← Meta.inferType ti.expr
let eFmt ← Meta.ppExpr ti.expr
let tpFmt ← Meta.ppExpr tp
-- try not to show too scary internals
let fmt := if isAtomicFormat eFmt then f!"{eFmt} : {tpFmt}" else f!"{tpFmt}"
return some f!"```lean
{fmt}
```"
| Info.ofFieldInfo fi =>
let tp ← Meta.inferType fi.val
let tpFmt ← Meta.ppExpr tp
return some f!"```lean
{fi.fieldName} : {tpFmt}
```"
| _ => return none
isAtomicFormat : Format → Bool
| Std.Format.text _ => true
| Std.Format.group f _ => isAtomicFormat f
| Std.Format.nest _ f => isAtomicFormat f
| Std.Format.tag _ f => isAtomicFormat f
| _ => false
structure GoalsAtResult where
ctxInfo : ContextInfo
tacticInfo : TacticInfo
useAfter : Bool
/-
Try to retrieve `TacticInfo` for `hoverPos`.
We retrieve the `TacticInfo` `info`, if there is a node of the form `node (ofTacticInfo info) children` s.t.
- `hoverPos` is sufficiently inside `info`'s range (see code), and
- None of the `children` satisfy the condition above. That is, for composite tactics such as
`induction`, we always give preference for information stored in nested (children) tactics.
Moreover, we instruct the LSP server to use the state after the tactic execution if the hover is inside the info *and*
there is no nested tactic info (i.e. it is a leaf tactic; tactic combinators should decide for themselves
where to show intermediate/final states)
-/
partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := do
t.deepestNodes fun
| ctx, i@(Info.ofTacticInfo ti), cs => OptionM.run do
if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then
let trailSize := i.stx.getTrailingSize
-- show info at EOF even if strictly outside token + trail
let atEOF := tailPos == text.source.bsize
guard <| pos ≤ hoverPos ∧ (hoverPos < tailPos + trailSize || atEOF)
return { ctxInfo := ctx, tacticInfo := ti, useAfter :=
hoverPos > pos && (hoverPos >= tailPos || !cs.any (hasNestedTactic pos tailPos)) }
else
failure
| _, _, _ => none
where
hasNestedTactic (pos tailPos) : InfoTree → Bool
| InfoTree.node i@(Info.ofTacticInfo _) cs => do
if let `(by $t) := i.stx then
return false -- ignore term-nested proofs such as in `simp [show p by ...]`
if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then
-- ignore nested infos of the same tactic, e.g. from expansion
if (pos', tailPos') != (pos, tailPos) then
return true
cs.any (hasNestedTactic pos tailPos)
| InfoTree.node (Info.ofMacroExpansionInfo _) cs =>
cs.any (hasNestedTactic pos tailPos)
| _ => false
/--
Find info nodes that should be used for the term goal feature.
The main complication concerns applications
like `f a b` where `f` is an identifier.
In this case, the term goal at `f`
should be the goal for the full application `f a b`.
Therefore we first gather the position of
these head function symbols such as `f`,
and later ignore identifiers at these positions.
-/
partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) :=
let headFns : Std.HashSet String.Pos := t.foldInfo (init := {}) fun ctx i headFns => do
if let some pos := getHeadFnPos? i.stx then
headFns.insert pos
else
headFns
t.smallestInfo? fun i => do
if i.contains hoverPos then
if let Info.ofTermInfo ti := i then
return !ti.stx.isIdent || !headFns.contains i.pos?.get!
false
where
/- Returns the position of the head function symbol, if it is an identifier. -/
getHeadFnPos? (s : Syntax) (foundArgs := false) : Option String.Pos :=
match s with
| `(($s)) => getHeadFnPos? s foundArgs
| `($f $as*) => getHeadFnPos? f (foundArgs := foundArgs || !as.isEmpty)
| stx => if foundArgs && stx.isIdent then stx.getPos? else none
end Lean.Elab
|
6e523063834da0e82e7080c84d72c1715b5898c9 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/category/transformers.lean | f4c273cb5d781d82fdb57fc9da222c81125cb540 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 1,618 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
prelude
import init.category.state init.function init.coe
namespace monad
class monad_transformer (transformer : ∀m [monad m], Type → Type) :=
(is_monad : ∀m [monad m], monad (transformer m))
(monad_lift : ∀m [monad m] α, m α → transformer m α)
instance transformed_monad (m t) [monad_transformer t] [monad m] : monad (t m) :=
monad_transformer.is_monad t m
class has_monad_lift (m n : Type → Type) :=
(monad_lift : ∀α, m α → n α)
instance monad_transformer_lift (t m) [monad_transformer t] [monad m] : has_monad_lift m (t m) :=
⟨monad_transformer.monad_lift t m⟩
class has_monad_lift_t (m n : Type → Type) :=
(monad_lift : ∀α, m α → n α)
def monad_lift {m n} [has_monad_lift_t m n] {α} : m α → n α :=
has_monad_lift_t.monad_lift n α
@[reducible] def has_monad_lift_to_has_coe {m n} [has_monad_lift_t m n] {α} : has_coe (m α) (n α) :=
⟨monad_lift⟩
instance has_monad_lift_t_trans (m n o) [has_monad_lift n o] [has_monad_lift_t m n] : has_monad_lift_t m o :=
⟨ λα (ma : m α), has_monad_lift.monad_lift o α $ has_monad_lift_t.monad_lift n α ma ⟩
instance has_monad_lift_t_refl (m) [monad m] : has_monad_lift_t m m :=
⟨ λα, id ⟩
end monad
namespace state_t
def state_t_monad_lift (S) (m) [monad m] (α) (f : m α) : state_t S m α :=
take state, do res ← f, return (res, state)
instance (S) : monad.monad_transformer (state_t S) :=
⟨ state_t.monad S, state_t_monad_lift S ⟩
end state_t
|
485d40f2849dec2fb665b3523c13f05aca6a9cbd | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/eval_expr_error.lean | ceb111fa31ca3dc4315b9544420abf45b9560325 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 352 | lean | open tactic
meta def tst1 (A : Type) : tactic unit :=
do a ← to_expr `(0),
v ← eval_expr A a,
return ()
run_command do
a ← to_expr `(nat.add),
v ← eval_expr nat a,
trace v,
return ()
run_command do
a ← to_expr `(λ x : nat, x + 1),
v ← (eval_expr nat a <|> trace "tactic failed" >> return 1),
trace v,
return ()
|
3faf34435fd3173333fd121dbab762f6179273a5 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/t10.lean | 10f2c3b7a8f2b67332fee9eabcfc47d0052a0276 | [
"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 | 111 | lean | set_option pp.colors true
set_option pp.unicode false
#print options
set_option pp.unicode true
#print options
|
52f283e0f5ece79d341ea02853b2eb6538c75a72 | 0845ae2ca02071debcfd4ac24be871236c01784f | /tests/lean/run/csimp_type_error.lean | 403c70b63d5bdf9d2d78cdd2cb61d0d031e219ff | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 301 | lean | namespace scratch
inductive type
| bv (w:Nat) : type
open type
def value : type -> Type
| (bv w) := {n // n < w}
def tester_fails : ∀ {tp : type}, value tp -> Bool
| (bv _) v1 := decide (v1.val = 0)
def tester_ok : ∀ {tp : type}, value tp -> Prop
| (bv _) v1 := v1.val = 0
end scratch
|
596e87db22b4b6386addb2a01a2341b217283d8e | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/order/lattice.lean | e42a6d380704e9def4bf559b433581dabfca1bf3 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,389 | lean | /-
Copyright (c) 2021 Christopher Hoskin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christopher Hoskin
-/
import topology.algebra.order.basic
import topology.constructions
/-!
# Topological lattices
In this file we define mixin classes `has_continuous_inf` and `has_continuous_sup`. We define the
class `topological_lattice` as a topological space and lattice `L` extending `has_continuous_inf`
and `has_continuous_sup`.
## References
* [Gierz et al, A Compendium of Continuous Lattices][GierzEtAl1980]
## Tags
topological, lattice
-/
open filter
open_locale topological_space
/--
Let `L` be a topological space and let `L×L` be equipped with the product topology and let
`⊓:L×L → L` be an infimum. Then `L` is said to have *(jointly) continuous infimum* if the map
`⊓:L×L → L` is continuous.
-/
class has_continuous_inf (L : Type*) [topological_space L] [has_inf L] : Prop :=
(continuous_inf : continuous (λ p : L × L, p.1 ⊓ p.2))
/--
Let `L` be a topological space and let `L×L` be equipped with the product topology and let
`⊓:L×L → L` be a supremum. Then `L` is said to have *(jointly) continuous supremum* if the map
`⊓:L×L → L` is continuous.
-/
class has_continuous_sup (L : Type*) [topological_space L] [has_sup L] : Prop :=
(continuous_sup : continuous (λ p : L × L, p.1 ⊔ p.2))
@[priority 100] -- see Note [lower instance priority]
instance order_dual.has_continuous_sup
(L : Type*) [topological_space L] [has_inf L] [has_continuous_inf L] : has_continuous_sup Lᵒᵈ :=
{ continuous_sup := @has_continuous_inf.continuous_inf L _ _ _ }
@[priority 100] -- see Note [lower instance priority]
instance order_dual.has_continuous_inf
(L : Type*) [topological_space L] [has_sup L] [has_continuous_sup L] : has_continuous_inf Lᵒᵈ :=
{ continuous_inf := @has_continuous_sup.continuous_sup L _ _ _ }
/--
Let `L` be a lattice equipped with a topology such that `L` has continuous infimum and supremum.
Then `L` is said to be a *topological lattice*.
-/
class topological_lattice (L : Type*) [topological_space L] [lattice L]
extends has_continuous_inf L, has_continuous_sup L
@[priority 100] -- see Note [lower instance priority]
instance order_dual.topological_lattice
(L : Type*) [topological_space L] [lattice L] [topological_lattice L] :
topological_lattice Lᵒᵈ := {}
variables {L : Type*} [topological_space L]
variables {X : Type*} [topological_space X]
@[continuity] lemma continuous_inf [has_inf L] [has_continuous_inf L] :
continuous (λp:L×L, p.1 ⊓ p.2) :=
has_continuous_inf.continuous_inf
@[continuity] lemma continuous.inf [has_inf L] [has_continuous_inf L]
{f g : X → L} (hf : continuous f) (hg : continuous g) :
continuous (λx, f x ⊓ g x) :=
continuous_inf.comp (hf.prod_mk hg : _)
@[continuity] lemma continuous_sup [has_sup L] [has_continuous_sup L] :
continuous (λp:L×L, p.1 ⊔ p.2) :=
has_continuous_sup.continuous_sup
@[continuity] lemma continuous.sup [has_sup L] [has_continuous_sup L]
{f g : X → L} (hf : continuous f) (hg : continuous g) :
continuous (λx, f x ⊔ g x) :=
continuous_sup.comp (hf.prod_mk hg : _)
lemma filter.tendsto.sup_right_nhds' {ι β} [topological_space β] [has_sup β] [has_continuous_sup β]
{l : filter ι} {f g : ι → β} {x y : β}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) :
tendsto (f ⊔ g) l (𝓝 (x ⊔ y)) :=
(continuous_sup.tendsto _).comp (tendsto.prod_mk_nhds hf hg)
lemma filter.tendsto.sup_right_nhds {ι β} [topological_space β] [has_sup β] [has_continuous_sup β]
{l : filter ι} {f g : ι → β} {x y : β}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) :
tendsto (λ i, f i ⊔ g i) l (𝓝 (x ⊔ y)) :=
hf.sup_right_nhds' hg
lemma filter.tendsto.inf_right_nhds' {ι β} [topological_space β] [has_inf β] [has_continuous_inf β]
{l : filter ι} {f g : ι → β} {x y : β}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) :
tendsto (f ⊓ g) l (𝓝 (x ⊓ y)) :=
(continuous_inf.tendsto _).comp (tendsto.prod_mk_nhds hf hg)
lemma filter.tendsto.inf_right_nhds {ι β} [topological_space β] [has_inf β] [has_continuous_inf β]
{l : filter ι} {f g : ι → β} {x y : β}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) :
tendsto (λ i, f i ⊓ g i) l (𝓝 (x ⊓ y)) :=
hf.inf_right_nhds' hg
|
a5a03bf8cbc4f2430fa6060ebb23a08712c12384 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/string_imp2.lean | 7bfd1d5ebe793462e415068b8a543a9601f247e1 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,693 | lean | def f (s : String) : String :=
s ++ " " ++ s
def g (s : String) : String :=
s.push ' ' ++ s.push '-'
def h (s : String) : String :=
let it₁ := s.mkIterator;
let it₂ := it₁.next;
it₁.remainingToString ++ "-" ++ it₂.remainingToString
#eval "hello" ++ "hello"
#eval f "hello"
#eval (f "αβ").length
#eval "hello".toList
#eval "αβ".toList
#eval "".toList
#eval "αβγ".toList
#eval "αβγ".mkIterator.1
#eval "αβγ".mkIterator.next.1
#eval "αβγ".mkIterator.next.next.1
#eval "αβγ".mkIterator.next.2
#eval "αβ".1
#eval "αβ".push 'a'
#eval g "α"
#eval "".mkIterator.curr
#eval ("αβγ".mkIterator.setCurr 'a').toString
#eval (("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').toString
#eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').next.setCurr 'c').toString
#eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').prev.setCurr 'c').toString
#eval ("abc".mkIterator.setCurr '0').toString
#eval (("abc".mkIterator.setCurr '0').next.setCurr '1').toString
#eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').next.setCurr '2').toString
#eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').prev.setCurr '2').toString
#eval ("abc".mkIterator.setCurr (Char.ofNat 955)).toString
#eval h "abc"
#eval "abc".mkIterator.remainingToString
#eval ("a".push (Char.ofNat 0)) ++ "bb"
#eval (("a".push (Char.ofNat 0)) ++ "αb").length
#eval "".mkIterator.hasNext
#eval "a".mkIterator.hasNext
#eval "a".mkIterator.next.hasNext
#eval "".mkIterator.hasPrev
#eval "a".mkIterator.next.hasPrev
#eval "αβ".mkIterator.next.hasPrev
#eval "αβ".mkIterator.next.prev.hasPrev
#eval "abc" == "abc"
#eval "abc" == "abd"
#eval "αβγ".drop 1
#eval "αβγ".takeRight 1
|
156004a238263812f7e47b78d3f1678d49426e71 | 6214e13b31733dc9aeb4833db6a6466005763162 | /src/definitions2.lean | 154789b85549af8acf0672548506d3c5dd6e747f | [] | no_license | joshua0pang/esverify-theory | 272a250445f3aeea49a7e72d1ab58c2da6618bbe | 8565b123c87b0113f83553d7732cd6696c9b5807 | refs/heads/master | 1,585,873,849,081 | 1,527,304,393,000 | 1,527,304,393,000 | 154,901,199 | 1 | 0 | null | 1,540,593,067,000 | 1,540,593,067,000 | null | UTF-8 | Lean | false | false | 27,510 | lean | -- second part of definitions
import .definitions1 .qiaux
-- ################################
-- ### QUANTIFIER INSTANTIATION ###
-- ################################
-- first part is in definitions1.lean
-- the following definitions need some additional lemmas from qiaux.lean to prove termination
-- lift_all(P) performs repeated lifting of quantifiers in positive
-- positions until there is no more quantifier to be lifted
def prop.lift_all: prop → prop
| P :=
let r := P.lift_p P.fresh_var in
let z := r in
have h: z = r, from rfl,
@option.cases_on prop (λr, (z = r) → prop) r (
assume : z = none,
P
) (
assume P': prop,
assume : z = (some P'),
have r_id: r = (some P'), from eq.trans h this,
have P'.num_quantifiers < P.num_quantifiers,
from (lifted_prop_smaller P').left r_id,
prop.lift_all P'
) rfl
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.num_quantifiers ⟩],
dec_tac := tactic.assumption
}
-- erase_p(P) / erase_n(P) replaces all triggers and quantifiers
-- in either positive or negative position with 'true'
mutual def prop.erased_p, prop.erased_n
with prop.erased_p: prop → vc
| (prop.term t) := vc.term t
| (prop.not P) := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
vc.not P.erased_n
| (prop.and P₁ P₂) := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.erased_p ⋀ P₂.erased_p
| (prop.or P₁ P₂) := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.erased_p ⋁ P₂.erased_p
| (prop.pre t₁ t₂) := vc.pre t₁ t₂
| (prop.pre₁ op t) := vc.pre₁ op t
| (prop.pre₂ op t₁ t₂) := vc.pre₂ op t₁ t₂
| (prop.post t₁ t₂) := vc.post t₁ t₂
| (prop.call _) := vc.term value.true
| (prop.forallc x P) := vc.term value.true
| (prop.exis x P) := have P.sizeof < (prop.exis x P).sizeof, from sizeof_prop_exis,
vc.not (vc.univ x (vc.not P.erased_p))
with prop.erased_n: prop → vc
| (prop.term t) := vc.term t
| (prop.not P) := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
vc.not P.erased_p
| (prop.and P₁ P₂) := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.erased_n ⋀ P₂.erased_n
| (prop.or P₁ P₂) := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.erased_n ⋁ P₂.erased_n
| (prop.pre t₁ t₂) := vc.pre t₁ t₂
| (prop.pre₁ op t) := vc.pre₁ op t
| (prop.pre₂ op t₁ t₂) := vc.pre₂ op t₁ t₂
| (prop.post t₁ t₂) := vc.post t₁ t₂
| (prop.call _) := vc.term value.true
| (prop.forallc x P) := have P.sizeof < (prop.forallc x P).sizeof, from sizeof_prop_forall,
vc.univ x P.erased_n
| (prop.exis x P) := have P.sizeof < (prop.exis x P).sizeof, from sizeof_prop_exis,
vc.not (vc.univ x (vc.not P.erased_n))
using_well_founded {
rel_tac := λ _ _, `[exact erased_measure],
dec_tac := tactic.assumption
}
-- given a call trigger t, inst_with_p(P, t) / inst_with_n(P, t) instantiates all quantifiers in
-- either positive or negative positions by adding a conjunction where the quantified
-- variable is replaced by the term in the given trigger
mutual def prop.instantiate_with_p, prop.instantiate_with_n
with prop.instantiate_with_p: prop → calltrigger → prop
| (prop.term t) _ := prop.term t
| (prop.not P) t := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
prop.not (P.instantiate_with_n t)
| (prop.and P₁ P₂) t := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.instantiate_with_p t ⋀ P₂.instantiate_with_p t
| (prop.or P₁ P₂) t := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.instantiate_with_p t ⋁ P₂.instantiate_with_p t
| (prop.pre t₁ t₂) _ := prop.pre t₁ t₂
| (prop.pre₁ op t) _ := prop.pre₁ op t
| (prop.pre₂ op t₁ t₂) _ := prop.pre₂ op t₁ t₂
| (prop.post t₁ t₂) _ := prop.post t₁ t₂
| (prop.call t) _ := prop.call t
| (prop.forallc x P) t := prop.forallc x P ⋀ P.substt x t.x -- instantiate
| (prop.exis x P) t := prop.exis x P
with prop.instantiate_with_n: prop → calltrigger → prop
| (prop.term t) _ := prop.term t
| (prop.not P) t := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
prop.not (P.instantiate_with_p t)
| (prop.and P₁ P₂) t := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.instantiate_with_n t ⋀ P₂.instantiate_with_n t
| (prop.or P₁ P₂) t := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.instantiate_with_n t ⋁ P₂.instantiate_with_n t
| (prop.pre t₁ t₂) _ := prop.pre t₁ t₂
| (prop.pre₁ op t) _ := prop.pre₁ op t
| (prop.pre₂ op t₁ t₂) _ := prop.pre₂ op t₁ t₂
| (prop.post t₁ t₂) _ := prop.post t₁ t₂
| (prop.call t) _ := prop.call t
| (prop.forallc x P) t := prop.forallc x P
| (prop.exis x P) t := prop.exis x P
using_well_founded {
rel_tac := λ _ _, `[exact instantiate_with_measure],
dec_tac := tactic.assumption
}
-- finds all call triggers in either positive or negative positions and returns these as list
mutual def prop.find_calls_p, prop.find_calls_n
with prop.find_calls_p: prop → list calltrigger
| (prop.term t) := []
| (prop.not P) := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
P.find_calls_n
| (prop.and P₁ P₂) := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.find_calls_p ++ P₂.find_calls_p
| (prop.or P₁ P₂) := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.find_calls_p ++ P₂.find_calls_p
| (prop.pre t₁ t₂) := []
| (prop.pre₁ op t) := []
| (prop.pre₂ op t₁ t₂) := []
| (prop.post t₁ t₂) := []
| (prop.call t) := [ ⟨ t ⟩ ]
| (prop.forallc x P) := []
| (prop.exis x P) := []
with prop.find_calls_n: prop → list calltrigger
| (prop.term t) := []
| (prop.not P) := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
P.find_calls_p
| (prop.and P₁ P₂) := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
P₁.find_calls_n ++ P₂.find_calls_n
| (prop.or P₁ P₂) := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
P₁.find_calls_n ++ P₂.find_calls_n
| (prop.pre t₁ t₂) := []
| (prop.pre₁ op t) := []
| (prop.pre₂ op t₁ t₂) := []
| (prop.post t₁ t₂) := []
| (prop.call t) := []
| (prop.forallc x P) := []
| (prop.exis x P) := []
using_well_founded {
rel_tac := λ _ _, `[exact find_calls_measure],
dec_tac := tactic.assumption
}
-- performs one full instantiation for each of the triggers in the provided list
def prop.instantiate_with_all: prop → list calltrigger → prop
| P list.nil := P
| P (list.cons t r) := (P.instantiate_with_n t).instantiate_with_all r
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.2.sizeof⟩]
}
-- performs n rounds of instantiations. each round also involves a repeated lifting.
-- once all rounds are complete, remaining quantifiers and triggers in negative positions will be erased
def prop.instantiate_rep: prop → ℕ → vc
| P 0 := P.lift_all.erased_n
| P (nat.succ n) := have n < n + 1, from lt_of_add_one,
(P.lift_all.instantiate_with_all (P.lift_all.find_calls_n)).instantiate_rep n
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.2⟩]
}
-- finds the maximum quantifier nesting level of a given proposition
def prop.max_nesting_level: prop → ℕ
| (prop.term t) := 0
| (prop.not P) := have P.sizeof < P.not.sizeof, from sizeof_prop_not,
P.max_nesting_level
| (prop.and P₁ P₂) := have P₁.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₁,
have P₂.sizeof < (P₁ ⋀ P₂).sizeof, from sizeof_prop_and₂,
max P₁.max_nesting_level P₂.max_nesting_level
| (prop.or P₁ P₂) := have P₁.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₁,
have P₂.sizeof < (P₁ ⋁ P₂).sizeof, from sizeof_prop_or₂,
max P₁.max_nesting_level P₂.max_nesting_level
| (prop.pre t₁ t₂) := 0
| (prop.pre₁ op t) := 0
| (prop.pre₂ op t₁ t₂) := 0
| (prop.post t₁ t₂) := 0
| (prop.call t) := 0
| (prop.forallc x P) := have P.sizeof < (prop.forallc x P).sizeof, from sizeof_prop_forall,
nat.succ P.max_nesting_level
| (prop.exis x P) := 0
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.sizeof⟩],
dec_tac := tactic.assumption
}
-- the main instantiation algorithm performs n rounds of instantiations
-- where n is the maximum quantifier nesting level and returns the erased proposition
def prop.instantiated_n (P: prop): vc := P.instantiate_rep P.max_nesting_level
-- #############################
-- ### OPERATIONAL SEMANTICS ###
-- #############################
-- semantics of unary operators
def unop.apply: unop → value → option value
| unop.not value.true := value.false
| unop.not value.false := value.true
| unop.isInt (value.num _) := value.true
| unop.isInt _ := value.false
| unop.isBool value.true := value.true
| unop.isBool value.false := value.true
| unop.isBool _ := value.false
| unop.isFunc (value.func _ _ _ _ _ _) := value.true
| unop.isFunc _ := value.false
| _ _ := none
-- semantics of binary operators
def binop.apply: binop → value → value → option value
| binop.plus (value.num n₁) (value.num n₂) := value.num (n₁ + n₂)
| binop.minus (value.num n₁) (value.num n₂) := value.num (n₁ - n₂)
| binop.times (value.num n₁) (value.num n₂) := value.num (n₁ * n₂)
| binop.div (value.num n₁) (value.num n₂) := value.num (n₁ / n₂)
| binop.and value.true value.true := value.true
| binop.and value.true value.false := value.false
| binop.and value.false value.true := value.false
| binop.and value.false value.false := value.false
| binop.or value.true value.true := value.true
| binop.or value.true value.false := value.true
| binop.or value.false value.true := value.true
| binop.or value.false value.false := value.false
| binop.eq v₁ v₂ := if v₁ = v₂ then value.true else value.false
| binop.lt (value.num n₁) (value.num n₂) := if n₁ < n₂ then value.true else value.false
| _ _ _ := none
-- small-step stack-based semantics
inductive step : stack → stack → Prop
notation s₁ `⟶` s₂:100 := step s₁ s₂
| ctx {s s': stack} {σ: env} {y f x: var} {e: exp}:
(s ⟶ s') →
(s · [σ, letapp y = f[x] in e] ⟶ (s' · [σ, letapp y = f[x] in e]))
| tru {σ: env} {x: var} {e: exp}:
(σ, lett x = true in e) ⟶ (σ[x↦value.true], e)
| fals {σ: env} {x: var} {e: exp}:
(σ, letf x = false in e) ⟶ (σ[x↦value.false], e)
| num {σ: env} {x: var} {e: exp} {n: ℤ}:
(σ, letn x = n in e) ⟶ (σ[x↦value.num n], e)
| closure {σ: env} {R' R S: spec} {f x: var} {e₁ e₂: exp}:
(σ, letf f[x] req R ens S {e₁} in e₂) ⟶ (σ[f↦value.func f x R S e₁ σ], e₂)
| unop {op: unop} {σ: env} {x y: var} {e: exp} {v₁ v: value}:
(σ x = v₁) →
(unop.apply op v₁ = v) →
((σ, letop y = op [x] in e) ⟶ (σ[y↦v], e))
| binop {op: binop} {σ: env} {x y z: var} {e: exp} {v₁ v₂ v: value}:
(σ x = v₁) →
(σ y = v₂) →
(binop.apply op v₁ v₂ = v) →
((σ, letop2 z = op [x, y] in e) ⟶ (σ[z↦v], e))
| app {σ σ': env} {R S: spec} {f g x y z: var} {e e': exp} {v: value}:
(σ f = value.func g z R S e σ') →
(σ x = v) →
((σ, letapp y = f[x] in e') ⟶ ((σ'[g↦value.func g z R S e σ'][z↦v], e) · [σ, letapp y = f[x] in e']))
| return {σ₁ σ₂ σ₃: env} {f g gx x y z: var} {R S: spec} {e e': exp} {v vₓ: value}:
(σ₁ z = v) →
(σ₂ f = value.func g gx R S e σ₃) →
(σ₂ x = vₓ) →
((σ₁, exp.return z) · [σ₂, letapp y = f[x] in e'] ⟶ (σ₂[y↦v], e'))
| ite_true {σ: env} {e₁ e₂: exp} {x: var}:
(σ x = value.true) →
((σ, exp.ite x e₁ e₂) ⟶ (σ, e₁))
| ite_false {σ: env} {e₁ e₂: exp} {x: var}:
(σ x = value.false) →
((σ, exp.ite x e₁ e₂) ⟶ (σ, e₂))
notation s₁ `⟶` s₂:100 := step s₁ s₂
-- transitive closure
inductive trans_step : stack → stack → Prop
notation s `⟶*` s':100 := trans_step s s'
| rfl {s: stack} : s ⟶* s
| trans {s s' s'': stack} : (s ⟶* s') → (s' ⟶ s'') → (s ⟶* s'')
notation s `⟶*` s':100 := trans_step s s'
def is_value (s: stack) :=
∃(σ: env) (x: var) (v: value), s = (σ, exp.return x) ∧ (σ x = v)
-- #######################################
-- ### VALIDTY OF LOGICAL PROPOSITIONS ###
-- #######################################
-- validity is axiomatized instead defined
-- see axioms below
constant valid : vc → Prop
notation `⊨` p: 20 := valid p
notation σ `⊨` p: 20 := ⊨ (vc.subst_env σ p)
notation `⟪` P `⟫`: 100 := ∀ (σ: env), closed_subst σ P → ⊨ (prop.subst_env σ P).instantiated_n
-- simple axioms for logical reasoning
axiom valid.tru:
⊨ value.true
axiom valid.and {P Q: vc}:
(⊨ P) ∧ (⊨ Q)
↔
⊨ P ⋀ Q
axiom valid.or.left {P Q: vc}:
(⊨ P) →
⊨ P ⋁ Q
axiom valid.or.right {P Q: vc}:
(⊨ Q) →
⊨ P ⋁ Q
axiom valid.or.elim {P Q: vc}:
(⊨ P ⋁ Q)
→
(⊨ P) ∨ (⊨ Q)
-- no contradictions
axiom valid.contradiction {P: vc}:
¬ (⊨ P ⋀ P.not)
-- law of excluded middle
axiom valid.em {P: vc}:
(⊨ P ⋁ P.not)
-- a term is valid if it equals true
axiom valid.eq.true {t: term}:
⊨ t
↔
⊨ value.true ≡ t
-- universal quantifier valid if true for all values
axiom valid.univ.mp {x: var} {P: vc}:
(∀v, ⊨ vc.subst x v P)
→
⊨ vc.univ x P
-- a free top-level variable is implicitly universally quantified
axiom valid.univ.free {x: var} {P: vc}:
(x ∈ FV P ∧ ⊨ P)
→
⊨ vc.univ x P
-- universal quantifier can be instantiated with any term
axiom valid.univ.mpr {x: var} {P: vc}:
(⊨ vc.univ x P)
→
(∀t, ⊨ vc.substt x t P)
-- unary and binary operators are decidable, so equalities with operators are decidable
axiom valid.unop {op: unop} {vₓ v: value}:
unop.apply op vₓ = some v
↔
⊨ v ≡ term.unop op vₓ
axiom valid.binop {op: binop} {v₁ v₂ v: value}:
binop.apply op v₁ v₂ = some v
↔
⊨ v ≡ term.binop op v₁ v₂
-- can write pre₁ and pre₂ to check domain of operators
axiom valid.pre₁ {vₓ: value} {op: unop}:
(⊨ vc.pre₁ op vₓ)
→
option.is_some (unop.apply op vₓ)
axiom valid.pre₂ {v₁ v₂: value} {op: binop}:
(⊨ vc.pre₂ op v₁ v₂)
→
option.is_some (binop.apply op v₁ v₂)
-- #####################################
-- ### VERIFICATION RELATION (VCGEN) ###
-- #####################################
reserve infix `⊢`:10
-- verification of expressions
inductive exp.vcgen : prop → exp → propctx → Prop
notation P `⊢` e `:` Q : 10 := exp.vcgen P e Q
| tru {P: prop} {x: var} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.true ⊢ e : Q) →
(P ⊢ lett x = true in e : propctx.exis x (x ≡ value.true ⋀ Q))
| fals {P: prop} {x: var} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.false ⊢ e : Q) →
(P ⊢ letf x = false in e : propctx.exis x (x ≡ value.false ⋀ Q))
| num {P: prop} {x: var} {n: ℕ} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.num n ⊢ e : Q) →
(P ⊢ letn x = n in e : propctx.exis x (x ≡ value.num n ⋀ Q))
| func {P: prop} {f x: var} {R S: spec} {e₁ e₂: exp} {Q₁ Q₂: propctx}:
f ∉ FV P →
x ∉ FV P →
f ≠ x →
x ∈ FV R.to_prop.to_vc →
FV R.to_prop ⊆ FV P ∪ { f, x } →
FV S.to_prop ⊆ FV P ∪ { f, x } →
(P ⋀ spec.func f x R S ⋀ R ⊢ e₁ : Q₁) →
(P ⋀ prop.func f x R (Q₁ (term.app f x) ⋀ S) ⊢ e₂ : Q₂) →
⟪ prop.implies (P ⋀ spec.func f x R S ⋀ R ⋀ Q₁ (term.app f x)) S ⟫ →
(P ⊢ letf f[x] req R ens S {e₁} in e₂ : propctx.exis f (prop.func f x R (Q₁ (term.app f x) ⋀ S) ⋀ Q₂))
| unop {P: prop} {op: unop} {e: exp} {x y: var} {Q: propctx}:
x ∈ FV P →
y ∉ FV P →
(P ⋀ y ≡ term.unop op x ⊢ e : Q) →
⟪ prop.implies P (prop.pre₁ op x) ⟫ →
(P ⊢ letop y = op [x] in e : propctx.exis y (y ≡ term.unop op x ⋀ Q))
| binop {P: prop} {op: binop} {e: exp} {x y z: var} {Q: propctx}:
x ∈ FV P →
y ∈ FV P →
z ∉ FV P →
(P ⋀ z ≡ term.binop op x y ⊢ e : Q) →
⟪ prop.implies P (prop.pre₂ op x y) ⟫ →
(P ⊢ letop2 z = op [x, y] in e : propctx.exis z (z ≡ term.binop op x y ⋀ Q))
| app {P: prop} {e: exp} {y f x: var} {Q: propctx}:
f ∈ FV P →
x ∈ FV P →
y ∉ FV P →
(P ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⊢ e : Q) →
⟪ prop.implies (P ⋀ prop.call x) (term.unop unop.isFunc f ⋀ prop.pre f x) ⟫ →
(P ⊢ letapp y = f [x] in e : propctx.exis y (prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⋀ Q))
| ite {P: prop} {e₁ e₂: exp} {x: var} {Q₁ Q₂: propctx}:
x ∈ FV P →
(P ⋀ x ⊢ e₁ : Q₁) →
(P ⋀ prop.not x ⊢ e₂ : Q₂) →
⟪ prop.implies P (term.unop unop.isBool x) ⟫ →
(P ⊢ exp.ite x e₁ e₂ : propctx.implies x Q₁ ⋀ propctx.implies (prop.not x) Q₂)
| return {P: prop} {x: var}:
x ∈ FV P →
(P ⊢ exp.return x : x ≣ •)
notation P `⊢` e `:` Q : 10 := exp.vcgen P e Q
-- verification of environments/translation into logic
inductive env.vcgen : env → prop → Prop
notation `⊢` σ `:` Q : 10 := env.vcgen σ Q
| empty:
⊢ env.empty : value.true
| tru {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊢ σ : Q) →
(⊢ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true)
| fls {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊢ σ : Q) →
(⊢ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false)
| num {n: ℤ} {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊢ σ : Q) →
(⊢ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n)
| func {σ₁ σ₂: env} {f g x: var} {R S: spec} {e: exp} {Q₁ Q₂: prop} {Q₃: propctx}:
f ∉ σ₁ →
g ∉ σ₂ →
x ∉ σ₂ →
g ≠ x →
(⊢ σ₁ : Q₁) →
(⊢ σ₂ : Q₂) →
x ∈ FV R.to_prop.to_vc →
FV R.to_prop ⊆ FV Q₂ ∪ { g, x } →
FV S.to_prop ⊆ FV Q₂ ∪ { g, x } →
(Q₂ ⋀ spec.func g x R S ⋀ R ⊢ e : Q₃) →
⟪ prop.implies (Q₂ ⋀ spec.func g x R S ⋀ R ⋀ Q₃ (term.app g x)) S ⟫ →
(⊢ (σ₁[f ↦ value.func g x R S e σ₂]) :
(Q₁
⋀ f ≡ value.func g x R S e σ₂
⋀ prop.subst_env (σ₂[g↦value.func g x R S e σ₂]) (prop.func g x R (Q₃ (term.app g x) ⋀ S))))
notation `⊢` σ `:` Q : 10 := env.vcgen σ Q
-- ###############################
-- ### VERIFICATION WITHOUT QI ###
-- ###############################
-- verification conditions without quantifier instantiation algorithm
notation `⦃` P `⦄`: 100 := ∀ (σ: env), closed_subst σ P → σ ⊨ P.to_vc
reserve infix `⊩`:10
-- verification of expressions
inductive exp.dvcgen : prop → exp → propctx → Prop
notation P `⊩` e `:` Q : 10 := exp.dvcgen P e Q
| tru {P: prop} {x: var} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.true ⊩ e : Q) →
(P ⊩ lett x = true in e : propctx.exis x (x ≡ value.true ⋀ Q))
| fals {P: prop} {x: var} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.false ⊩ e : Q) →
(P ⊩ letf x = false in e : propctx.exis x (x ≡ value.false ⋀ Q))
| num {P: prop} {x: var} {n: ℕ} {e: exp} {Q: propctx}:
x ∉ FV P →
(P ⋀ x ≡ value.num n ⊩ e : Q) →
(P ⊩ letn x = n in e : propctx.exis x (x ≡ value.num n ⋀ Q))
| func {P: prop} {f x: var} {R S: spec} {e₁ e₂: exp} {Q₁ Q₂: propctx}:
f ∉ FV P →
x ∉ FV P →
f ≠ x →
x ∈ FV R.to_prop.to_vc →
FV R.to_prop ⊆ FV P ∪ { f, x } →
FV S.to_prop ⊆ FV P ∪ { f, x } →
(P ⋀ spec.func f x R S ⋀ R ⊩ e₁ : Q₁) →
(P ⋀ prop.func f x R (Q₁ (term.app f x) ⋀ S) ⊩ e₂ : Q₂) →
⦃ prop.implies (P ⋀ spec.func f x R S ⋀ R ⋀ Q₁ (term.app f x)) S ⦄ →
(P ⊩ letf f[x] req R ens S {e₁} in e₂ : propctx.exis f (prop.func f x R (Q₁ (term.app f x) ⋀ S) ⋀ Q₂))
| unop {P: prop} {op: unop} {e: exp} {x y: var} {Q: propctx}:
x ∈ FV P →
y ∉ FV P →
(P ⋀ y ≡ term.unop op x ⊩ e : Q) →
⦃ prop.implies P (prop.pre₁ op x) ⦄ →
(P ⊩ letop y = op [x] in e : propctx.exis y (y ≡ term.unop op x ⋀ Q))
| binop {P: prop} {op: binop} {e: exp} {x y z: var} {Q: propctx}:
x ∈ FV P →
y ∈ FV P →
z ∉ FV P →
(P ⋀ z ≡ term.binop op x y ⊩ e : Q) →
⦃ prop.implies P (prop.pre₂ op x y) ⦄ →
(P ⊩ letop2 z = op [x, y] in e : propctx.exis z (z ≡ term.binop op x y ⋀ Q))
| app {P: prop} {e: exp} {y f x: var} {Q: propctx}:
f ∈ FV P →
x ∈ FV P →
y ∉ FV P →
(P ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⊩ e : Q) →
⦃ prop.implies (P ⋀ prop.call x) (term.unop unop.isFunc f ⋀ prop.pre f x) ⦄ →
(P ⊩ letapp y = f [x] in e : propctx.exis y (prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⋀ Q))
| ite {P: prop} {e₁ e₂: exp} {x: var} {Q₁ Q₂: propctx}:
x ∈ FV P →
(P ⋀ x ⊩ e₁ : Q₁) →
(P ⋀ prop.not x ⊩ e₂ : Q₂) →
⦃ prop.implies P (term.unop unop.isBool x) ⦄ →
(P ⊩ exp.ite x e₁ e₂ : propctx.implies x Q₁ ⋀ propctx.implies (prop.not x) Q₂)
| return {P: prop} {x: var}:
x ∈ FV P →
(P ⊩ exp.return x : x ≣ •)
notation P `⊩` e `:` Q : 10 := exp.dvcgen P e Q
-- verification of environments/translation into logic
inductive env.dvcgen : env → prop → Prop
notation `⊩` σ `:` Q : 10 := env.dvcgen σ Q
| empty:
⊩ env.empty : value.true
| tru {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊩ σ : Q) →
(⊩ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true)
| fls {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊩ σ : Q) →
(⊩ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false)
| num {n: ℤ} {σ: env} {x: var} {Q: prop}:
x ∉ σ →
(⊩ σ : Q) →
(⊩ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n)
| func {σ₁ σ₂: env} {f g x: var} {R S: spec} {e: exp} {Q₁ Q₂: prop} {Q₃: propctx}:
f ∉ σ₁ →
g ∉ σ₂ →
x ∉ σ₂ →
g ≠ x →
(⊩ σ₁ : Q₁) →
(⊩ σ₂ : Q₂) →
x ∈ FV R.to_prop.to_vc →
FV R.to_prop ⊆ FV Q₂ ∪ { g, x } →
FV S.to_prop ⊆ FV Q₂ ∪ { g, x } →
(Q₂ ⋀ spec.func g x R S ⋀ R ⊩ e : Q₃) →
⦃ prop.implies (Q₂ ⋀ spec.func g x R S ⋀ R ⋀ Q₃ (term.app g x)) S ⦄ →
(⊩ (σ₁[f ↦ value.func g x R S e σ₂]) :
(Q₁
⋀ f ≡ value.func g x R S e σ₂
⋀ prop.subst_env (σ₂[g↦value.func g x R S e σ₂]) (prop.func g x R (Q₃ (term.app g x) ⋀ S))))
notation `⊩` σ `:` Q : 10 := env.dvcgen σ Q
-- #################################################################
-- ### AXIOMS ABOUT FUNCTION EXPRESSIONS, PRE and POSTCONDITIONS ###
-- #################################################################
-- The following equality axiom is non-standard and makes validity undecidable.
-- It is only used in the preservation proof of e-return and in no other lemmas.
-- The logic treats `f(x)` uninterpreted, so there is no way to derive it naturally.
-- However, given a complete evaluation derivation of a function call, we can add the
-- equality `f(x)=y` as new axiom for closed values f, x, y and the resulting set
-- of axioms is still sound due to deterministic evaluation.
axiom valid.app {vₓ v: value} {σ σ': env} {f x y: var} {R S: spec} {e: exp}:
(σ[f↦value.func f x R S e σ][x↦vₓ], e) ⟶* (σ', exp.return y) →
(σ' y = some v)
→
⊨ v ≡ term.app (value.func f x R S e σ) vₓ
-- can write pre and post to extract pre- and postcondition of function values
axiom valid.pre {vₓ: value} {σ: env} {f x: var} {R S: spec} {e: exp}:
(σ[f↦value.func f x R S e σ][x↦vₓ] ⊨ R.to_prop.to_vc)
↔
⊨ vc.pre (value.func f x R S e σ) vₓ
axiom valid.post.mp {vₓ: value} {σ: env} {Q: prop} {Q₂: propctx} {f x: var} {R S: spec} {e: exp}:
(⊩ σ : Q) →
(Q ⋀ spec.func f x R S ⋀ R ⊩ e : Q₂) →
(σ[f↦value.func f x R S e σ][x↦vₓ] ⊨ (Q₂ (term.app f x) ⋀ S.to_prop).to_vc)
→
(⊨ vc.post (value.func f x R S e σ) vₓ)
axiom valid.post.mpr {vₓ: value} {σ: env} {Q: prop} {Q₂: propctx} {f x: var} {R S: spec} {e: exp}:
(⊩ σ : Q) →
(Q ⋀ spec.func f x R S ⋀ R ⊩ e : Q₂) →
(⊨ vc.post (value.func f x R S e σ) vₓ)
→
(σ[f↦value.func f x R S e σ][x↦vₓ] ⊨ (Q₂ (term.app f x) ⋀ S.to_prop).to_vc)
|
ca3da8937f80b5910ae5866ce35df7e0716e86f6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/additive/energy.lean | cb6bbc075dfa7d9b58b32d68bf84e7c761eaa22a | [
"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,297 | lean | /-
Copyright (c) 2022 Yaël Dillies, Ella Yu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Ella Yu
-/
import data.finset.prod
import data.fintype.prod
/-!
# Additive energy
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the additive energy of two finsets of a group. This is a central quantity in
additive combinatorics.
## TODO
It's possibly interesting to have
`(s ×ˢ s) ×ˢ t ×ˢ t).filter (λ x : (α × α) × α × α, x.1.1 * x.2.1 = x.1.2 * x.2.2)` (whose `card` is
`multiplicative_energy s t`) as a standalone definition.
-/
section
variables {α : Type*} [partial_order α] {x y : α}
end
variables {α : Type*} [decidable_eq α]
namespace finset
section has_mul
variables [has_mul α] {s s₁ s₂ t t₁ t₂ : finset α}
/-- The multiplicative energy of two finsets `s` and `t` in a group is the number of quadruples
`(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ * b₁ = a₂ * b₂`. -/
@[to_additive additive_energy "The additive energy of two finsets `s` and `t` in a group is the
number of quadruples `(a₁, a₂, b₁, b₂) ∈ s × s × t × t` such that `a₁ + b₁ = a₂ + b₂`."]
def multiplicative_energy (s t : finset α) : ℕ :=
(((s ×ˢ s) ×ˢ t ×ˢ t).filter $ λ x : (α × α) × α × α, x.1.1 * x.2.1 = x.1.2 * x.2.2).card
@[to_additive additive_energy_mono]
lemma multiplicative_energy_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) :
multiplicative_energy s₁ t₁ ≤ multiplicative_energy s₂ t₂ :=
card_le_of_subset $ filter_subset_filter _ $ product_subset_product (product_subset_product hs hs) $
product_subset_product ht ht
@[to_additive additive_energy_mono_left]
lemma multiplicative_energy_mono_left (hs : s₁ ⊆ s₂) :
multiplicative_energy s₁ t ≤ multiplicative_energy s₂ t :=
multiplicative_energy_mono hs subset.rfl
@[to_additive additive_energy_mono_right]
lemma multiplicative_energy_mono_right (ht : t₁ ⊆ t₂) :
multiplicative_energy s t₁ ≤ multiplicative_energy s t₂ :=
multiplicative_energy_mono subset.rfl ht
@[to_additive le_additive_energy]
lemma le_multiplicative_energy : s.card * t.card ≤ multiplicative_energy s t :=
begin
rw ←card_product,
refine card_le_card_of_inj_on (λ x, ((x.1, x.1), x.2, x.2)) (by simp [←and_imp]) (λ a _ b _, _),
simp only [prod.mk.inj_iff, and_self, and_imp],
exact prod.ext,
end
@[to_additive additive_energy_pos]
lemma multiplicative_energy_pos (hs : s.nonempty) (ht : t.nonempty) :
0 < multiplicative_energy s t :=
(mul_pos hs.card_pos ht.card_pos).trans_le le_multiplicative_energy
variables (s t)
@[simp, to_additive additive_energy_empty_left]
lemma multiplicative_energy_empty_left : multiplicative_energy ∅ t = 0 :=
by simp [multiplicative_energy]
@[simp, to_additive additive_energy_empty_right]
lemma multiplicative_energy_empty_right : multiplicative_energy s ∅ = 0 :=
by simp [multiplicative_energy]
variables {s t}
@[simp, to_additive additive_energy_pos_iff]
lemma multiplicative_energy_pos_iff : 0 < multiplicative_energy s t ↔ s.nonempty ∧ t.nonempty :=
⟨λ h, of_not_not $ λ H, begin
simp_rw [not_and_distrib, not_nonempty_iff_eq_empty] at H,
obtain rfl | rfl := H; simpa [nat.not_lt_zero] using h,
end, λ h, multiplicative_energy_pos h.1 h.2⟩
@[simp, to_additive additive_energy_eq_zero_iff]
lemma multiplicative_energy_eq_zero_iff : multiplicative_energy s t = 0 ↔ s = ∅ ∨ t = ∅ :=
by simp [←(nat.zero_le _).not_gt_iff_eq, not_and_distrib]
end has_mul
section comm_monoid
variables [comm_monoid α]
@[to_additive additive_energy_comm]
lemma multiplicative_energy_comm (s t : finset α) :
multiplicative_energy s t = multiplicative_energy t s :=
begin
rw [multiplicative_energy, ←finset.card_map (equiv.prod_comm _ _).to_embedding, map_filter],
simp [-finset.card_map, eq_comm, multiplicative_energy, mul_comm, map_eq_image, function.comp],
end
end comm_monoid
section comm_group
variables [comm_group α] [fintype α] (s t : finset α)
@[simp, to_additive additive_energy_univ_left]
lemma multiplicative_energy_univ_left :
multiplicative_energy univ t = fintype.card α * t.card ^ 2 :=
begin
simp only [multiplicative_energy, univ_product_univ, fintype.card, sq, ←card_product],
set f : α × α × α → (α × α) × α × α := λ x, ((x.1 * x.2.2, x.1 * x.2.1), x.2) with hf,
have : (↑((univ : finset α) ×ˢ t ×ˢ t) : set (α × α × α)).inj_on f,
{ rintro ⟨a₁, b₁, c₁⟩ h₁ ⟨a₂, b₂, c₂⟩ h₂ h,
simp_rw prod.ext_iff at h,
obtain ⟨h, rfl, rfl⟩ := h,
rw mul_right_cancel h.1 },
rw [←card_image_of_inj_on this],
congr' with a,
simp only [hf, mem_filter, mem_product, mem_univ, true_and, mem_image, exists_prop, prod.exists],
refine ⟨λ h, ⟨a.1.1 * a.2.2⁻¹, _, _, h.1, by simp [mul_right_comm, h.2]⟩, _⟩,
rintro ⟨b, c, d, hcd, rfl⟩,
simpa [mul_right_comm],
end
@[simp, to_additive additive_energy_univ_right]
lemma multiplicative_energy_univ_right :
multiplicative_energy s univ = fintype.card α * s.card ^ 2 :=
by rw [multiplicative_energy_comm, multiplicative_energy_univ_left]
end comm_group
end finset
|
10b5ce091d3a21aca67838da452f95c9f19b42d2 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/topology/metric_space/contracting.lean | 7fd5e5418829cab3075601d3a65e58e7c18a8880 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 5,067 | lean | /-
Copyright (c) 2019 Rohan Mitta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov
-/
import topology.metric_space.lipschitz analysis.specific_limits
/-!
# Contracting maps
A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*.
In this file we prove the Banach fixed point theorem, some explicit estimates on the rate
of convergence, and some properties of the map sending a contracting map to its fixed point.
-/
universes u v
open_locale nnreal topological_space
open filter
variables {α : Type u} {ι : Sort v}
/-- If the iterates `f^[n] x₀` converge to `x` and `f` is continuous at `x`,
then `x` is a fixed point for `f`. -/
lemma fixed_point_of_tendsto_iterate [topological_space α] [t2_space α] {f : α → α} {x : α}
(hf : continuous_at f x) (hx : ∃ x₀ : α, tendsto (λ n, f^[n] x₀) at_top (𝓝 x)) :
f x = x :=
begin
rcases hx with ⟨x₀, hx⟩,
refine tendsto_nhds_unique at_top_ne_bot _ hx,
rw [← tendsto_add_at_top_iff_nat 1, funext (assume n, nat.iterate_succ' f n x₀)],
exact tendsto.comp hf hx
end
/-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/
def contracting_with [metric_space α] (K : ℝ≥0) (f : α → α) :=
(K < 1) ∧ lipschitz_with K f
namespace contracting_with
variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f)
include hf
lemma to_lipschitz_with : lipschitz_with K f := hf.2
lemma one_sub_K_pos : (0:ℝ) < 1 - K := sub_pos_of_lt hf.1
lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) :=
suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y,
by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add],
calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _
... ≤ dist x (f x) + dist y (f y) + K * dist x y :
add_le_add_left (hf.to_lipschitz_with _ _) _
lemma dist_le_of_fixed_point (x) {y} (hy : f y = y) :
dist x y ≤ (dist x (f x)) / (1 - K) :=
by simpa only [hy, dist_self, add_zero] using hf.dist_inequality x y
theorem fixed_point_unique' {x y} (hx : f x = x) (hy : f y = y) : x = y :=
dist_le_zero.1 $ by simpa only [hx, dist_self, add_zero, zero_div]
using hf.dist_le_of_fixed_point x hy
/-- Banach fixed-point theorem, contraction mapping theorem -/
theorem exists_fixed_point [hα : nonempty α] [complete_space α] : ∃x, f x = x :=
let ⟨x₀⟩ := hα in
have cauchy_seq (λ n, f^[n] x₀),
from cauchy_seq_of_le_geometric K (dist x₀ (f x₀)) hf.1 $
hf.to_lipschitz_with.dist_iterate_succ_le_geometric x₀,
let ⟨x, hx⟩ := cauchy_seq_tendsto_of_complete this in
⟨x, fixed_point_of_tendsto_iterate (hf.to_lipschitz_with.to_continuous.tendsto x) ⟨x₀, hx⟩⟩
/-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly
`C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/
lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α)
{x y} (hx : f x = x) (hy : g y = y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist x y ≤ C / (1 - K) :=
calc dist x y = dist y x : dist_comm x y
... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx
... = (dist (f y) (g y)) / (1 - K) : by rw [hy, dist_comm]
... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y)
noncomputable theory
variables [inhabited α] [complete_space α]
/-- The unique fixed point of a contracting map. -/
protected def fixed_point : α := classical.some hf.exists_fixed_point
/-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/
lemma fixed_point_is_fixed : f hf.fixed_point = hf.fixed_point :=
classical.some_spec hf.exists_fixed_point
lemma fixed_point_unique {x} (hx : f x = x) : x = hf.fixed_point :=
hf.fixed_point_unique' hx hf.fixed_point_is_fixed
lemma dist_fixed_point_le (x) : dist x hf.fixed_point ≤ (dist x (f x)) / (1 - K) :=
hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed
/-- Aposteriori estimates on the convergence of iterates to the fixed point. -/
lemma aposteriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) hf.fixed_point ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) :=
by { rw [nat.iterate_succ'], apply hf.dist_fixed_point_le }
lemma apriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) hf.fixed_point ≤ (dist x (f x)) * K^n / (1 - K) :=
le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $
(div_le_div_right hf.one_sub_K_pos).2 $
hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n
lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g)
{C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist hf.fixed_point hg.fixed_point ≤ C / (1 - K) :=
hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed hg.fixed_point_is_fixed hfg
end contracting_with
|
d563e48a5de8d926481240007d8c2fd81d16fdd6 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /src/Lean/Parser.lean | 21bc210d21c3e1b1ab67c5d42657d14ba6f7c5ff | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,674 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Basic
import Lean.Parser.Level
import Lean.Parser.Term
import Lean.Parser.Tactic
import Lean.Parser.Command
import Lean.Parser.Module
import Lean.Parser.Syntax
import Lean.Parser.Do
namespace Lean
namespace Parser
open Lean.PrettyPrinter
open Lean.PrettyPrinter.Parenthesizer
open Lean.PrettyPrinter.Formatter
builtin_initialize
register_parser_alias "ws" checkWsBefore
register_parser_alias "noWs" checkNoWsBefore
register_parser_alias "linebreak" checkLinebreakBefore
register_parser_alias "num" numLit
register_parser_alias "str" strLit
register_parser_alias "char" charLit
register_parser_alias "name" nameLit
register_parser_alias "ident" ident
register_parser_alias "colGt" checkColGt
register_parser_alias "colGe" checkColGe
register_parser_alias "lookahead" lookahead
register_parser_alias "atomic" atomic
register_parser_alias "many" many
register_parser_alias "many1" many1
register_parser_alias "optional" optional
register_parser_alias "withPosition" withPosition
register_parser_alias "interpolatedStr" interpolatedStr
register_parser_alias "orelse" orelse
register_parser_alias "andthen" andthen
register_parser_alias "incQuotDepth" incQuotDepth
registerAlias "notFollowedBy" (notFollowedBy · "element")
Parenthesizer.registerAlias "notFollowedBy" notFollowedBy.parenthesizer
Formatter.registerAlias "notFollowedBy" notFollowedBy.formatter
end Parser
namespace PrettyPrinter
namespace Parenthesizer
-- Close the mutual recursion loop; see corresponding `[extern]` in the parenthesizer.
@[export lean_mk_antiquot_parenthesizer]
def mkAntiquot.parenthesizer (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parenthesizer :=
Parser.mkAntiquot.parenthesizer name kind anonymous
-- The parenthesizer auto-generated these instances correctly, but tagged them with the wrong kind, since the actual kind
-- (e.g. `ident`) is not equal to the parser name `Lean.Parser.Term.ident`.
@[builtinParenthesizer ident] def ident.parenthesizer : Parenthesizer := Parser.Term.ident.parenthesizer
@[builtinParenthesizer numLit] def numLit.parenthesizer : Parenthesizer := Parser.Term.num.parenthesizer
@[builtinParenthesizer scientificLit] def scientificLit.parenthesizer : Parenthesizer := Parser.Term.scientific.parenthesizer
@[builtinParenthesizer charLit] def charLit.parenthesizer : Parenthesizer := Parser.Term.char.parenthesizer
@[builtinParenthesizer strLit] def strLit.parenthesizer : Parenthesizer := Parser.Term.str.parenthesizer
open Lean.Parser
@[export lean_pretty_printer_parenthesizer_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr → CoreM Parenthesizer
| ParserDescr.const n => getConstAlias parenthesizerAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂)
| ParserDescr.node k prec d => return leadingNode.parenthesizer k prec (← interpretParserDescr d)
| ParserDescr.nodeWithAntiquot _ k d => return node.parenthesizer k (← interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.parenthesizer k prec lhsPrec (← interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.parenthesizer tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.parenthesizer tk includeIdent
| ParserDescr.parser constName => combinatorParenthesizerAttribute.runDeclFor constName
| ParserDescr.cat catName prec => return categoryParser.parenthesizer catName prec
end Parenthesizer
namespace Formatter
@[export lean_mk_antiquot_formatter]
def mkAntiquot.formatter (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter :=
Parser.mkAntiquot.formatter name kind anonymous
@[builtinFormatter ident] def ident.formatter : Formatter := Parser.Term.ident.formatter
@[builtinFormatter numLit] def numLit.formatter : Formatter := Parser.Term.num.formatter
@[builtinFormatter scientificLit] def scientificLit.formatter : Formatter := Parser.Term.scientific.formatter
@[builtinFormatter charLit] def charLit.formatter : Formatter := Parser.Term.char.formatter
@[builtinFormatter strLit] def strLit.formatter : Formatter := Parser.Term.str.formatter
open Lean.Parser
@[export lean_pretty_printer_formatter_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr → CoreM Formatter
| ParserDescr.const n => getConstAlias formatterAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias formatterAliasesRef n) (← interpretParserDescr d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias formatterAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂)
| ParserDescr.node k prec d => return node.formatter k (← interpretParserDescr d)
| ParserDescr.nodeWithAntiquot _ k d => return node.formatter k (← interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.formatter k prec lhsPrec (← interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.formatter tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.formatter tk
| ParserDescr.parser constName => combinatorFormatterAttribute.runDeclFor constName
| ParserDescr.cat catName prec => return categoryParser.formatter catName
end Formatter
end PrettyPrinter
end Lean
|
0c5c06dc534ab850fc85f49417dd70b344e67375 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/commandPrefix.lean | 2af64cec430adfa6f1fcc2b130709851f73a7f83 | [
"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 | 37 | lean | #check show Id Unit from do ()
abbr
|
064ed4452cc6b94077d78f294968851727d3dd9e | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/jacobson_ideal.lean | 9631d16cc61324bf8ecad34982588d481ad2535a | [
"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 | 14,871 | lean | /-
Copyright (c) 2020 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Devon Tuma
-/
import ring_theory.ideal.quotient
import ring_theory.polynomial.basic
/-!
# Jacobson radical
The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`.
This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`.
We can extend the idea of the nilradical to ideals of `R`,
by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`.
Under this extension, the original nilradical is the radical of the zero ideal `⊥`.
Here we define the Jacobson radical of an ideal `I` in a similar way,
as the intersection of maximal ideals containing `I`.
## Main definitions
Let `R` be a commutative ring, and `I` be an ideal of `R`
* `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I.
* `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal
## Main statements
* `mem_jacobson_iff` gives a characterization of members of the jacobson of I
* `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical
## Tags
Jacobson, Jacobson radical, Local Ideal
-/
universes u v
namespace ideal
variables {R : Type u} [comm_ring R] {I : ideal R}
variables {S : Type v} [comm_ring S]
section jacobson
/-- The Jacobson radical of `I` is the infimum of all maximal ideals containing `I`. -/
def jacobson (I : ideal R) : ideal R :=
Inf {J : ideal R | I ≤ J ∧ is_maximal J}
lemma le_jacobson : I ≤ jacobson I :=
λ x hx, mem_Inf.mpr (λ J hJ, hJ.left hx)
@[simp] lemma jacobson_idem : jacobson (jacobson I) = jacobson I :=
le_antisymm (Inf_le_Inf (λ J hJ, ⟨Inf_le hJ, hJ.2⟩)) le_jacobson
lemma radical_le_jacobson : radical I ≤ jacobson I :=
le_Inf (λ J hJ, (radical_eq_Inf I).symm ▸ Inf_le ⟨hJ.left, is_maximal.is_prime hJ.right⟩)
lemma eq_radical_of_eq_jacobson : jacobson I = I → radical I = I :=
λ h, le_antisymm (le_trans radical_le_jacobson (le_of_eq h)) le_radical
@[simp] lemma jacobson_top : jacobson (⊤ : ideal R) = ⊤ :=
eq_top_iff.2 le_jacobson
@[simp] theorem jacobson_eq_top_iff : jacobson I = ⊤ ↔ I = ⊤ :=
⟨λ H, classical.by_contradiction $ λ hi, let ⟨M, hm, him⟩ := exists_le_maximal I hi in
lt_top_iff_ne_top.1
(lt_of_le_of_lt (show jacobson I ≤ M, from Inf_le ⟨him, hm⟩) $
lt_top_iff_ne_top.2 hm.ne_top) H,
λ H, eq_top_iff.2 $ le_Inf $ λ J ⟨hij, hj⟩, H ▸ hij⟩
lemma jacobson_eq_bot : jacobson I = ⊥ → I = ⊥ :=
λ h, eq_bot_iff.mpr (h ▸ le_jacobson)
lemma jacobson_eq_self_of_is_maximal [H : is_maximal I] : I.jacobson = I :=
le_antisymm (Inf_le ⟨le_of_eq rfl, H⟩) le_jacobson
@[priority 100]
instance jacobson.is_maximal [H : is_maximal I] : is_maximal (jacobson I) :=
⟨⟨λ htop, H.1.1 (jacobson_eq_top_iff.1 htop),
λ J hJ, H.1.2 _ (lt_of_le_of_lt le_jacobson hJ)⟩⟩
theorem mem_jacobson_iff {x : R} : x ∈ jacobson I ↔ ∀ y, ∃ z, x * y * z + z - 1 ∈ I :=
⟨λ hx y, classical.by_cases
(assume hxy : I ⊔ span {x * y + 1} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 hxy) in
let ⟨r, hr⟩ := mem_span_singleton.1 hq in
⟨r, by rw [← one_mul r, ← mul_assoc, ← add_mul, mul_one, ← hr, ← hpq, ← neg_sub,
add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume hxy : I ⊔ span {x * y + 1} ≠ ⊤,
let ⟨M, hm1, hm2⟩ := exists_le_maximal _ hxy in
suffices x ∉ M, from (this $ mem_Inf.1 hx ⟨le_trans le_sup_left hm2, hm1⟩).elim,
λ hxm, hm1.1.1 $ (eq_top_iff_one _).2 $ add_sub_cancel' (x * y) 1 ▸ M.sub_mem
(le_sup_right.trans hm2 $ mem_span_singleton.2 dvd_rfl)
(M.mul_mem_right _ hxm)),
λ hx, mem_Inf.2 $ λ M ⟨him, hm⟩, classical.by_contradiction $ λ hxm,
let ⟨y, hy⟩ := hm.exists_inv hxm, ⟨z, hz⟩ := hx (-y) in
hm.1.1 $ (eq_top_iff_one _).2 $ sub_sub_cancel (x * -y * z + z) 1 ▸ M.sub_mem
(by { rw [← one_mul z, ← mul_assoc, ← add_mul, mul_one, mul_neg_eq_neg_mul_symm, neg_add_eq_sub,
← neg_sub, neg_mul_eq_neg_mul_symm, neg_mul_eq_mul_neg, mul_comm x y, mul_comm _ (- z)],
rcases hy with ⟨i, hi, df⟩,
rw [← (sub_eq_iff_eq_add.mpr df.symm), sub_sub, add_comm, ← sub_sub, sub_self, zero_sub],
refine M.mul_mem_left (-z) ((neg_mem_iff _).mpr hi) }) (him hz)⟩
lemma exists_mul_sub_mem_of_sub_one_mem_jacobson {I : ideal R} (r : R)
(h : r - 1 ∈ jacobson I) : ∃ s, r * s - 1 ∈ I :=
begin
cases mem_jacobson_iff.1 h 1 with s hs,
use s,
simpa [sub_mul] using hs
end
lemma is_unit_of_sub_one_mem_jacobson_bot (r : R)
(h : r - 1 ∈ jacobson (⊥ : ideal R)) : is_unit r :=
begin
cases exists_mul_sub_mem_of_sub_one_mem_jacobson r h with s hs,
rw [mem_bot, sub_eq_zero] at hs,
exact is_unit_of_mul_eq_one _ _ hs
end
/-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals.
Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/
theorem eq_jacobson_iff_Inf_maximal :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M :=
begin
use λ hI, ⟨{J : ideal R | I ≤ J ∧ J.is_maximal}, ⟨λ _ hJ, or.inl hJ.right, hI.symm⟩⟩,
rintros ⟨M, hM, hInf⟩,
refine le_antisymm (λ x hx, _) le_jacobson,
rw [hInf, mem_Inf],
intros I hI,
cases hM I hI with is_max is_top,
{ exact (mem_Inf.1 hx) ⟨le_Inf_iff.1 (le_of_eq hInf) I hI, is_max⟩ },
{ exact is_top.symm ▸ submodule.mem_top }
end
theorem eq_jacobson_iff_Inf_maximal' :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M :=
eq_jacobson_iff_Inf_maximal.trans
⟨λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ K hK, or.rec_on (hM.1 J hJ) (λ h, h.1.2 K hK)
(λ h, eq_top_iff.2 (le_of_lt (h ▸ hK))), hM.2⟩⟩,
λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ, or.rec_on (classical.em (J = ⊤)) (λ h, or.inr h)
(λ h, or.inl ⟨⟨h, hM.1 J hJ⟩⟩), hM.2⟩⟩⟩
/-- An ideal `I` equals its Jacobson radical if and only if every element outside `I`
also lies outside of a maximal ideal containing `I`. -/
lemma eq_jacobson_iff_not_mem :
I.jacobson = I ↔ ∀ x ∉ I, ∃ M : ideal R, (I ≤ M ∧ M.is_maximal) ∧ x ∉ M :=
begin
split,
{ intros h x hx,
erw [← h, mem_Inf] at hx,
push_neg at hx,
exact hx },
{ refine λ h, le_antisymm (λ x hx, _) le_jacobson,
contrapose hx,
erw mem_Inf,
push_neg,
exact h x hx }
end
theorem map_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) :
ring_hom.ker f ≤ I → map f (I.jacobson) = (map f I).jacobson :=
begin
intro h,
unfold ideal.jacobson,
have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_maximal}, f.ker ≤ J := λ J hJ, le_trans h hJ.left,
refine trans (map_Inf hf this) (le_antisymm _ _),
{ refine Inf_le_Inf (λ J hJ, ⟨comap f J, ⟨⟨le_comap_of_map_le hJ.1, _⟩,
map_comap_of_surjective f hf J⟩⟩),
haveI : J.is_maximal := hJ.right,
exact comap_is_maximal_of_surjective f hf },
{ refine Inf_le_Inf_of_subset_insert_top (λ j hj, hj.rec_on (λ J hJ, _)),
rw ← hJ.2,
cases map_eq_top_or_is_maximal_of_surjective f hf hJ.left.right with htop hmax,
{ exact htop.symm ▸ set.mem_insert ⊤ _ },
{ exact set.mem_insert_of_mem ⊤ ⟨map_mono hJ.1.1, hmax⟩ } },
end
lemma map_jacobson_of_bijective {f : R →+* S} (hf : function.bijective f) :
map f (I.jacobson) = (map f I).jacobson :=
map_jacobson_of_surjective hf.right
(le_trans (le_of_eq (f.injective_iff_ker_eq_bot.1 hf.left)) bot_le)
lemma comap_jacobson {f : R →+* S} {K : ideal S} :
comap f (K.jacobson) = Inf (comap f '' {J : ideal S | K ≤ J ∧ J.is_maximal}) :=
trans (comap_Inf' f _) (Inf_eq_infi).symm
theorem comap_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) {K : ideal S} :
comap f (K.jacobson) = (comap f K).jacobson :=
begin
unfold ideal.jacobson,
refine le_antisymm _ _,
{ refine le_trans (comap_mono (le_of_eq (trans top_inf_eq.symm Inf_insert.symm))) _,
rw [comap_Inf', Inf_eq_infi],
refine infi_le_infi_of_subset (λ J hJ, _),
have : comap f (map f J) = J := trans (comap_map_of_surjective f hf J)
(le_antisymm (sup_le_iff.2 ⟨le_of_eq rfl, le_trans (comap_mono bot_le) hJ.left⟩) le_sup_left),
cases map_eq_top_or_is_maximal_of_surjective _ hf hJ.right with htop hmax,
{ refine ⟨⊤, ⟨set.mem_insert ⊤ _, htop ▸ this⟩⟩ },
{ refine ⟨map f J, ⟨set.mem_insert_of_mem _
⟨le_map_of_comap_le_of_surjective f hf hJ.1, hmax⟩, this⟩⟩ } },
{ rw comap_Inf,
refine le_infi_iff.2 (λ J, (le_infi_iff.2 (λ hJ, _))),
haveI : J.is_maximal := hJ.right,
refine Inf_le ⟨comap_mono hJ.left, comap_is_maximal_of_surjective _ hf⟩ }
end
lemma mem_jacobson_bot {x : R} : x ∈ jacobson (⊥ : ideal R) ↔ ∀ y, is_unit (x * y + 1) :=
⟨λ hx y, let ⟨z, hz⟩ := (mem_jacobson_iff.1 hx) y in
is_unit_iff_exists_inv.2 ⟨z, by rwa [add_mul, one_mul, ← sub_eq_zero]⟩,
λ h, mem_jacobson_iff.mpr (λ y, (let ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (h y) in
⟨b, (submodule.mem_bot R).2 (hb ▸ (by ring))⟩))⟩
/-- An ideal `I` of `R` is equal to its Jacobson radical if and only if
the Jacobson radical of the quotient ring `R/I` is the zero ideal -/
theorem jacobson_eq_iff_jacobson_quotient_eq_bot :
I.jacobson = I ↔ jacobson (⊥ : ideal (R ⧸ I)) = ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
replace h := congr_arg (map (quotient.mk I)) h,
rw map_jacobson_of_surjective hf (le_of_eq mk_ker) at h,
simpa using h },
{ intro h,
replace h := congr_arg (comap (quotient.mk I)) h,
rw [comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at h,
simpa using h }
end
/-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if
the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/
theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot :
I.radical = I.jacobson ↔ radical (⊥ : ideal (R ⧸ I)) = jacobson ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
have := congr_arg (map (quotient.mk I)) h,
rw [map_radical_of_surjective hf (le_of_eq mk_ker),
map_jacobson_of_surjective hf (le_of_eq mk_ker)] at this,
simpa using this },
{ intro h,
have := congr_arg (comap (quotient.mk I)) h,
rw [comap_radical, comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at this,
simpa using this }
end
@[mono] lemma jacobson_mono {I J : ideal R} : I ≤ J → I.jacobson ≤ J.jacobson :=
begin
intros h x hx,
erw mem_Inf at ⊢ hx,
exact λ K ⟨hK, hK_max⟩, hx ⟨trans h hK, hK_max⟩
end
lemma jacobson_radical_eq_jacobson :
I.radical.jacobson = I.jacobson :=
le_antisymm (le_trans (le_of_eq (congr_arg jacobson (radical_eq_Inf I)))
(Inf_le_Inf (λ J hJ, ⟨Inf_le ⟨hJ.1, hJ.2.is_prime⟩, hJ.2⟩))) (jacobson_mono le_radical)
end jacobson
section polynomial
open polynomial
lemma jacobson_bot_polynomial_le_Inf_map_maximal :
jacobson (⊥ : ideal (polynomial R)) ≤ Inf (map C '' {J : ideal R | J.is_maximal}) :=
begin
refine le_Inf (λ J, exists_imp_distrib.2 (λ j hj, _)),
haveI : j.is_maximal := hj.1,
refine trans (jacobson_mono bot_le) (le_of_eq _ : J.jacobson ≤ J),
suffices : (⊥ : ideal (polynomial (R ⧸ j))).jacobson = ⊥,
{ rw [← hj.2, jacobson_eq_iff_jacobson_quotient_eq_bot],
replace this :=
congr_arg (map (polynomial_quotient_equiv_quotient_polynomial j).to_ring_hom) this,
rwa [map_jacobson_of_bijective _, map_bot] at this,
exact (ring_equiv.bijective (polynomial_quotient_equiv_quotient_polynomial j)) },
refine eq_bot_iff.2 (λ f hf, _),
simpa [(λ hX, by simpa using congr_arg (λ f, coeff f 1) hX : (X : polynomial (R ⧸ j)) ≠ 0)]
using eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit ((mem_jacobson_bot.1 hf) X)),
end
lemma jacobson_bot_polynomial_of_jacobson_bot (h : jacobson (⊥ : ideal R) = ⊥) :
jacobson (⊥ : ideal (polynomial R)) = ⊥ :=
begin
refine eq_bot_iff.2 (le_trans jacobson_bot_polynomial_le_Inf_map_maximal _),
refine (λ f hf, ((submodule.mem_bot _).2 (polynomial.ext (λ n, trans _ (coeff_zero n).symm)))),
suffices : f.coeff n ∈ ideal.jacobson ⊥, by rwa [h, submodule.mem_bot] at this,
exact mem_Inf.2 (λ j hj, (mem_map_C_iff.1 ((mem_Inf.1 hf) ⟨j, ⟨hj.2, rfl⟩⟩)) n),
end
end polynomial
section is_local
/-- An ideal `I` is local iff its Jacobson radical is maximal. -/
class is_local (I : ideal R) : Prop := (out : is_maximal (jacobson I))
theorem is_local_iff {I : ideal R} : is_local I ↔ is_maximal (jacobson I) :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem is_local_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) : is_local I :=
⟨have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
show is_maximal (jacobson I), from this ▸ hi⟩
theorem is_local.le_jacobson {I J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) :
J ≤ jacobson I :=
let ⟨M, hm, hjm⟩ := exists_le_maximal J hj in
le_trans hjm $ le_of_eq $ eq.symm $ hi.1.eq_of_le hm.1.1 $ Inf_le ⟨le_trans hij hjm, hm⟩
theorem is_local.mem_jacobson_or_exists_inv {I : ideal R} (hi : is_local I) (x : R) :
x ∈ jacobson I ∨ ∃ y, y * x - 1 ∈ I :=
classical.by_cases
(assume h : I ⊔ span {x} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
let ⟨r, hr⟩ := mem_span_singleton.1 hq in
or.inr ⟨r, by rw [← hpq, mul_comm, ← hr, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume h : I ⊔ span {x} ≠ ⊤,
or.inl $ le_trans le_sup_right (hi.le_jacobson le_sup_left h) $ mem_span_singleton.2 $
dvd_refl x)
end is_local
theorem is_primary_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) :
is_primary I :=
have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
⟨ne_top_of_lt $ lt_of_le_of_lt le_radical (lt_top_iff_ne_top.2 hi.1.1),
λ x y hxy, ((is_local_of_is_maximal_radical hi).mem_jacobson_or_exists_inv y).symm.imp
(λ ⟨z, hz⟩, by rw [← mul_one x, ← sub_sub_cancel (z * y) 1, mul_sub, mul_left_comm]; exact
I.sub_mem (I.mul_mem_left _ hxy) (I.mul_mem_left _ hz))
(this ▸ id)⟩
end ideal
|
591a7e8876adc9a7c1d02d108b88b11499510969 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/advanced_multiplication/4_alt.lean | 96810e59e79e2f04f1f67477166c378e9c083d61 | [
"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 | 2,422 | lean | theorem mul_left_cancel (a b c : mynat) (ha : a ≠ 0) : a * b = a * c → b = c :=
-- This is a longer proof that uses a little more lean machinery, and puts
-- more stress on my CPU, but to me what this proof is doing makes much more
-- sense:
-- + It first establishes that any two natural numbers have a difference
-- (ie one is less than or equal to the other, or can be written as some "d"
-- plus the other), which is actually proved later in inequality world.
-- + Then taking wlog b = c + d, we use distributivity and cancellation of
-- addition to get a * d = 0, and then we must have d = 0, so b = c.
-- + However I'm not sure how to do wlog properly in Lean, so I end up
-- introducing a general hypothesis of this form and then applying it twice,
-- using a lot of symmetry in the second case.
-- New sub-goal: for all natural numbers b, c, we can write one as `d` plus
-- the other. To prove this requires induction and lots of case-work (and you
-- need to know how existence proofs with the use tactic work!). It would
-- probably be nicer all round if we got the ring tactic at this point, but oh
-- well.
have h : ∃ d: mynat, b = c + d ∨ b + d = c,
induction b with n hn,
use c,
right,
rwa zero_add,
cases hn with d hd,
cases d,
repeat {rw add_zero at hd},
-- In this bit I have a hypothesis of the form "a or a", and I'd like to use
-- the idempotency of logical disjunction in some flashy way, but idk how so I
-- just claim it's equivalent to "a" and prove it in both cases (using cc
-- because it's easier to write).
have hnc: n = c,
cases hd,
cc, cc,
rw hnc,
use 1,
left,
rwa succ_eq_add_one,
cases hd,
use succ (succ d),
left,
rw hd,
repeat {rw add_succ},
use d,
right,
rw ← hd,
rwa [add_succ, succ_add],
-- Now we've demonstrated the existence of our d, expose it with cases
cases h with d hd,
-- This is my hack to avoid having to prove this twice
have h_lazy: ∀ x y z w: mynat, x ≠ 0 → y = z + w → x * y = x * z → y = z,
intros x y z w hxnz hyzw hxyxz,
rw [hyzw, mul_add] at hxyxz,
have hxzz := eq_zero_or_eq_zero_of_mul_eq_zero _ _ (eq_zero_of_add_right_eq_self _ _ hxyxz),
have hwz: w = 0,
cc,
rwa [hyzw, hwz, add_zero],
cases hd,
exact h_lazy a b c d ha hd,
intros h,
symmetry at h,
symmetry at hd,
symmetry,
exact h_lazy a c b d ha hd h,
end
|
9abb9f05913230096b396211f11ce2c25569311e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/specific_limits/floor_pow.lean | 1c7c1e209188a8d29ab020b92f0b5a9b1f07b312 | [
"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 | 17,773 | lean | /-
Copyright (c) 2022 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.specific_limits.basic
import analysis.special_functions.pow.real
/-!
# Results on discretized exponentials
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We state several auxiliary results pertaining to sequences of the form `⌊c^n⌋₊`.
* `tendsto_div_of_monotone_of_tendsto_div_floor_pow`: If a monotone sequence `u` is such that
`u ⌊c^n⌋₊ / ⌊c^n⌋₊` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`.
* `sum_div_nat_floor_pow_sq_le_div_sq`: The sum of `1/⌊c^i⌋₊^2` above a threshold `j` is comparable
to `1/j^2`, up to a multiplicative constant.
-/
open filter finset
open_locale topology big_operators
/-- If a monotone sequence `u` is such that `u n / n` tends to a limit `l` along subsequences with
exponential growth rate arbitrarily close to `1`, then `u n / n` tends to `l`. -/
lemma tendsto_div_of_monotone_of_exists_subseq_tendsto_div (u : ℕ → ℝ) (l : ℝ) (hmono : monotone u)
(hlim : ∀ (a : ℝ), 1 < a → ∃ c : ℕ → ℕ, (∀ᶠ n in at_top, (c (n+1) : ℝ) ≤ a * c n) ∧
tendsto c at_top at_top ∧ tendsto (λ n, u (c n) / (c n)) at_top (𝓝 l)) :
tendsto (λ n, u n / n) at_top (𝓝 l) :=
begin
/- To check the result up to some `ε > 0`, we use a sequence `c` for which the ratio
`c (N+1) / c N` is bounded by `1 + ε`. Sandwiching a given `n` between two consecutive values of
`c`, say `c N` and `c (N+1)`, one can then bound `u n / n` from above by `u (c N) / c (N - 1)`
and from below by `u (c (N - 1)) / c N` (using that `u` is monotone), which are both comparable
to the limit `l` up to `1 + ε`.
We give a version of this proof by clearing out denominators first, to avoid discussing the sign
of different quantities. -/
have lnonneg : 0 ≤ l,
{ rcases hlim 2 one_lt_two with ⟨c, cgrowth, ctop, clim⟩,
have : tendsto (λ n, u 0 / (c n)) at_top (𝓝 0) :=
tendsto_const_nhds.div_at_top (tendsto_coe_nat_at_top_iff.2 ctop),
apply le_of_tendsto_of_tendsto' this clim (λ n, _),
simp_rw [div_eq_inv_mul],
exact mul_le_mul_of_nonneg_left (hmono (zero_le _)) (inv_nonneg.2 (nat.cast_nonneg _)) },
have A : ∀ (ε : ℝ), 0 < ε → ∀ᶠ n in at_top, u n - n * l ≤ (ε * (1 + ε + l)) * n,
{ assume ε εpos,
rcases hlim (1 + ε) ((lt_add_iff_pos_right _).2 εpos) with ⟨c, cgrowth, ctop, clim⟩,
have L : ∀ᶠ n in at_top, u (c n) - c n * l ≤ ε * c n,
{ rw [← tendsto_sub_nhds_zero_iff, ← asymptotics.is_o_one_iff ℝ,
asymptotics.is_o_iff] at clim,
filter_upwards [clim εpos, ctop (Ioi_mem_at_top 0)] with n hn cnpos',
have cnpos : 0 < c n := cnpos',
calc u (c n) - c n * l
= (u (c n) / c n - l) * c n:
by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff] with field_simps
... ≤ ε * c n :
begin
refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _),
simp only [mul_one, real.norm_eq_abs, abs_one] at hn,
exact le_trans (le_abs_self _) hn,
end },
obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), a ≤ b → (c (b + 1) : ℝ) ≤ (1 + ε) * c b
∧ u (c b) - c b * l ≤ ε * c b := eventually_at_top.1 (cgrowth.and L),
let M := ((finset.range (a+1)).image (λ i, c i)).max' (by simp),
filter_upwards [Ici_mem_at_top M] with n hn,
have exN : ∃ N, n < c N,
{ rcases (tendsto_at_top.1 ctop (n+1)).exists with ⟨N, hN⟩,
exact ⟨N, by linarith only [hN]⟩ },
let N := nat.find exN,
have ncN : n < c N := nat.find_spec exN,
have aN : a + 1 ≤ N,
{ by_contra' h,
have cNM : c N ≤ M,
{ apply le_max',
apply mem_image_of_mem,
exact mem_range.2 h },
exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) },
have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN,
have cNn : c (N - 1) ≤ n,
{ have : N - 1 < N := nat.pred_lt Npos.ne',
simpa only [not_lt] using nat.find_min exN this },
have IcN : (c N : ℝ) ≤ (1 + ε) * (c (N - 1)),
{ have A : a ≤ N - 1, by linarith only [aN, Npos],
have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos,
have := (ha _ A).1,
rwa B at this },
calc u n - n * l ≤ u (c N) - c (N - 1) * l :
begin
apply sub_le_sub (hmono ncN.le),
apply mul_le_mul_of_nonneg_right (nat.cast_le.2 cNn) lnonneg,
end
... = (u (c N) - c N * l) + (c N - c (N - 1)) * l : by ring
... ≤ ε * c N + (ε * c (N - 1)) * l :
begin
apply add_le_add,
{ apply (ha _ _).2,
exact le_trans (by simp only [le_add_iff_nonneg_right, zero_le']) aN },
{ apply mul_le_mul_of_nonneg_right _ lnonneg,
linarith only [IcN] },
end
... ≤ ε * ((1 + ε) * c (N-1)) + (ε * c (N - 1)) * l :
add_le_add (mul_le_mul_of_nonneg_left IcN εpos.le) le_rfl
... = (ε * (1 + ε + l)) * c (N - 1) : by ring
... ≤ (ε * (1 + ε + l)) * n :
begin
refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _,
apply mul_nonneg εpos.le,
linarith only [εpos, lnonneg]
end },
have B : ∀ (ε : ℝ), 0 < ε → ∀ᶠ (n : ℕ) in at_top, (n : ℝ) * l - u n ≤ (ε * (1 + l)) * n,
{ assume ε εpos,
rcases hlim (1 + ε) ((lt_add_iff_pos_right _).2 εpos) with ⟨c, cgrowth, ctop, clim⟩,
have L : ∀ᶠ (n : ℕ) in at_top, (c n : ℝ) * l - u (c n) ≤ ε * c n,
{ rw [← tendsto_sub_nhds_zero_iff, ← asymptotics.is_o_one_iff ℝ,
asymptotics.is_o_iff] at clim,
filter_upwards [clim εpos, ctop (Ioi_mem_at_top 0)] with n hn cnpos',
have cnpos : 0 < c n := cnpos',
calc (c n : ℝ) * l - u (c n)
= -(u (c n) / c n - l) * c n:
by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff, neg_sub] with field_simps
... ≤ ε * c n :
begin
refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _),
simp only [mul_one, real.norm_eq_abs, abs_one] at hn,
exact le_trans (neg_le_abs_self _) hn,
end },
obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), a ≤ b → (c (b + 1) : ℝ) ≤ (1 + ε) * c b
∧ (c b : ℝ) * l - u (c b) ≤ ε * c b := eventually_at_top.1 (cgrowth.and L),
let M := ((finset.range (a+1)).image (λ i, c i)).max' (by simp),
filter_upwards [Ici_mem_at_top M] with n hn,
have exN : ∃ N, n < c N,
{ rcases (tendsto_at_top.1 ctop (n+1)).exists with ⟨N, hN⟩,
exact ⟨N, by linarith only [hN]⟩ },
let N := nat.find exN,
have ncN : n < c N := nat.find_spec exN,
have aN : a + 1 ≤ N,
{ by_contra' h,
have cNM : c N ≤ M,
{ apply le_max',
apply mem_image_of_mem,
exact mem_range.2 h },
exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) },
have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN,
have aN' : a ≤ N - 1 := by linarith only [aN, Npos],
have cNn : c (N - 1) ≤ n,
{ have : N - 1 < N := nat.pred_lt Npos.ne',
simpa only [not_lt] using nat.find_min exN this },
calc (n : ℝ) * l - u n ≤ c N * l - u (c (N - 1)) :
begin
refine add_le_add (mul_le_mul_of_nonneg_right (nat.cast_le.2 ncN.le) lnonneg) _,
exact neg_le_neg (hmono cNn),
end
... ≤ ((1 + ε) * c (N - 1)) * l - u (c (N - 1)) :
begin
refine add_le_add (mul_le_mul_of_nonneg_right _ lnonneg) le_rfl,
have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos,
have := (ha _ aN').1,
rwa B at this,
end
... = (c (N - 1) * l - u (c (N - 1))) + ε * c (N - 1) * l : by ring
... ≤ ε * c (N - 1) + ε * c (N - 1) * l :
add_le_add (ha _ aN').2 le_rfl
... = (ε * (1 + l)) * c (N - 1) : by ring
... ≤ (ε * (1 + l)) * n :
begin
refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _,
exact mul_nonneg (εpos.le) (add_nonneg zero_le_one lnonneg),
end },
refine tendsto_order.2 ⟨λ d hd, _, λ d hd, _⟩,
{ obtain ⟨ε, hε, εpos⟩ : ∃ (ε : ℝ), d + ε * (1 + l) < l ∧ 0 < ε,
{ have L : tendsto (λ ε, d + (ε * (1 + l))) (𝓝[>] 0) (𝓝 (d + 0 * (1 + l))),
{ apply tendsto.mono_left _ nhds_within_le_nhds,
exact tendsto_const_nhds.add (tendsto_id.mul tendsto_const_nhds) },
simp only [zero_mul, add_zero] at L,
exact (((tendsto_order.1 L).2 l hd).and (self_mem_nhds_within)).exists },
filter_upwards [B ε εpos, Ioi_mem_at_top 0] with n hn npos,
simp_rw [div_eq_inv_mul],
calc d < (n⁻¹ * n) * (l - ε * (1 + l)) :
begin
rw [inv_mul_cancel, one_mul],
{ linarith only [hε] },
{ exact nat.cast_ne_zero.2 (ne_of_gt npos) }
end
... = n⁻¹ * (n * l - ε * (1 + l) * n) : by ring
... ≤ n⁻¹ * u n :
begin
refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)),
linarith only [hn],
end },
{ obtain ⟨ε, hε, εpos⟩ : ∃ (ε : ℝ), l + ε * (1 + ε + l) < d ∧ 0 < ε,
{ have L : tendsto (λ ε, l + (ε * (1 + ε + l))) (𝓝[>] 0) (𝓝 (l + 0 * (1 + 0 + l))),
{ apply tendsto.mono_left _ nhds_within_le_nhds,
exact tendsto_const_nhds.add
(tendsto_id.mul ((tendsto_const_nhds.add tendsto_id).add tendsto_const_nhds)) },
simp only [zero_mul, add_zero] at L,
exact (((tendsto_order.1 L).2 d hd).and (self_mem_nhds_within)).exists },
filter_upwards [A ε εpos, Ioi_mem_at_top 0] with n hn npos,
simp_rw [div_eq_inv_mul],
calc (n : ℝ)⁻¹ * u n ≤ (n : ℝ)⁻¹ * (n * l + ε * (1 + ε + l) * n) :
begin
refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)),
linarith only [hn],
end
... = ((n : ℝ) ⁻¹ * n) * (l + ε * (1 + ε + l)) : by ring
... < d :
begin
rwa [inv_mul_cancel, one_mul],
exact nat.cast_ne_zero.2 (ne_of_gt npos),
end }
end
/-- If a monotone sequence `u` is such that `u ⌊c^n⌋₊ / ⌊c^n⌋₊` converges to a limit `l` for all
`c > 1`, then `u n / n` tends to `l`. It is even enough to have the assumption for a sequence of
`c`s converging to `1`. -/
lemma tendsto_div_of_monotone_of_tendsto_div_floor_pow
(u : ℕ → ℝ) (l : ℝ) (hmono : monotone u)
(c : ℕ → ℝ) (cone : ∀ k, 1 < c k) (clim : tendsto c at_top (𝓝 1))
(hc : ∀ k, tendsto (λ (n : ℕ), u (⌊(c k) ^ n⌋₊) / ⌊(c k)^n⌋₊) at_top (𝓝 l)) :
tendsto (λ n, u n / n) at_top (𝓝 l) :=
begin
apply tendsto_div_of_monotone_of_exists_subseq_tendsto_div u l hmono,
assume a ha,
obtain ⟨k, hk⟩ : ∃ k, c k < a := ((tendsto_order.1 clim).2 a ha).exists,
refine ⟨λ n, ⌊(c k)^n⌋₊, _,
tendsto_nat_floor_at_top.comp (tendsto_pow_at_top_at_top_of_one_lt (cone k)), hc k⟩,
have H : ∀ (n : ℕ), (0 : ℝ) < ⌊c k ^ n⌋₊,
{ assume n,
refine zero_lt_one.trans_le _,
simp only [nat.one_le_cast, nat.one_le_floor_iff, one_le_pow_of_one_le (cone k).le n] },
have A : tendsto (λ (n : ℕ), ((⌊c k ^ (n+1)⌋₊ : ℝ) / c k ^ (n+1)) * c k /
(⌊c k ^ n⌋₊ / c k ^ n)) at_top (𝓝 (1 * c k / 1)),
{ refine tendsto.div (tendsto.mul _ tendsto_const_nhds) _ one_ne_zero,
{ refine tendsto_nat_floor_div_at_top.comp _,
exact (tendsto_pow_at_top_at_top_of_one_lt (cone k)).comp (tendsto_add_at_top_nat 1) },
{ refine tendsto_nat_floor_div_at_top.comp _,
exact tendsto_pow_at_top_at_top_of_one_lt (cone k) } },
have B : tendsto (λ (n : ℕ), (⌊c k ^ (n+1)⌋₊ : ℝ) / ⌊c k ^ n⌋₊) at_top (𝓝 (c k)),
{ simp only [one_mul, div_one] at A,
convert A,
ext1 n,
simp only [(zero_lt_one.trans (cone k)).ne', ne.def, not_false_iff, (H n).ne']
with field_simps {discharger := tactic.field_simp.ne_zero},
ring_exp },
filter_upwards [(tendsto_order.1 B).2 a hk] with n hn,
exact (div_le_iff (H n)).1 hn.le
end
/-- The sum of `1/(c^i)^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative
constant. -/
lemma sum_div_pow_sq_le_div_sq (N : ℕ) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) :
∑ i in (range N).filter (λ i, j < c ^ i), 1 / (c ^ i) ^ 2 ≤ (c^3 * (c - 1) ⁻¹) / j ^ 2 :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
have A : 0 < (c⁻¹) ^ 2 := sq_pos_of_pos (inv_pos.2 cpos),
have B : c^2 * (1 - c⁻¹ ^ 2) ⁻¹ ≤ c^3 * (c - 1) ⁻¹,
{ rw [← div_eq_mul_inv, ← div_eq_mul_inv, div_le_div_iff _ (sub_pos.2 hc)], swap,
{ exact sub_pos.2 (pow_lt_one (inv_nonneg.2 cpos.le) (inv_lt_one hc) two_ne_zero) },
have : c ^ 3 = c^2 * c, by ring_exp,
simp only [mul_sub, this, mul_one, inv_pow, sub_le_sub_iff_left],
rw [mul_assoc, mul_comm c, ← mul_assoc, mul_inv_cancel (sq_pos_of_pos cpos).ne', one_mul],
simpa using pow_le_pow hc.le one_le_two },
calc
∑ i in (range N).filter (λ i, j < c ^ i), 1/ (c ^ i) ^ 2
≤ ∑ i in Ico (⌊real.log j / real.log c⌋₊) N, 1 / (c ^ i) ^ 2 :
begin
refine sum_le_sum_of_subset_of_nonneg _ (λ i hi hident, div_nonneg zero_le_one (sq_nonneg _)),
assume i hi,
simp only [mem_filter, mem_range] at hi,
simp only [hi.1, mem_Ico, and_true],
apply nat.floor_le_of_le,
apply le_of_lt,
rw [div_lt_iff (real.log_pos hc), ← real.log_pow],
exact real.log_lt_log hj hi.2
end
... = ∑ i in Ico (⌊real.log j / real.log c⌋₊) N, ((c⁻¹) ^ 2) ^ i :
begin
congr' 1 with i,
simp [← pow_mul, mul_comm],
end
... ≤ ((c⁻¹) ^ 2) ^ (⌊real.log j / real.log c⌋₊) / (1 - (c⁻¹) ^ 2) :
begin
apply geom_sum_Ico_le_of_lt_one (sq_nonneg _),
rw sq_lt_one_iff (inv_nonneg.2 (zero_le_one.trans hc.le)),
exact inv_lt_one hc
end
... ≤ ((c⁻¹) ^ 2) ^ (real.log j / real.log c - 1) / (1 - (c⁻¹) ^ 2) :
begin
apply div_le_div _ _ _ le_rfl,
{ apply real.rpow_nonneg_of_nonneg (sq_nonneg _) },
{ rw ← real.rpow_nat_cast,
apply real.rpow_le_rpow_of_exponent_ge A,
{ exact pow_le_one _ (inv_nonneg.2 (zero_le_one.trans hc.le)) (inv_le_one hc.le) },
{ exact (nat.sub_one_lt_floor _).le } },
{ simpa only [inv_pow, sub_pos] using inv_lt_one (one_lt_pow hc two_ne_zero) }
end
... = (c^2 * (1 - c⁻¹ ^ 2) ⁻¹) / j ^ 2 :
begin
have I : (c ⁻¹ ^ 2) ^ (real.log j / real.log c) = 1 / j ^ 2,
{ apply real.log_inj_on_pos (real.rpow_pos_of_pos A _),
{ rw [one_div], exact inv_pos.2 (sq_pos_of_pos hj) },
rw real.log_rpow A,
simp only [one_div, real.log_inv, real.log_pow, nat.cast_bit0, nat.cast_one, mul_neg,
neg_inj],
field_simp [(real.log_pos hc).ne'],
ring },
rw [real.rpow_sub A, I],
have : c^2 - 1 ≠ 0 := (sub_pos.2 (one_lt_pow hc two_ne_zero)).ne',
field_simp [hj.ne', (zero_lt_one.trans hc).ne'],
ring,
end
... ≤ (c^3 * (c - 1) ⁻¹) / j ^ 2 :
begin
apply div_le_div _ B (sq_pos_of_pos hj) le_rfl,
exact mul_nonneg (pow_nonneg cpos.le _) (inv_nonneg.2 (sub_pos.2 hc).le),
end
end
lemma mul_pow_le_nat_floor_pow {c : ℝ} (hc : 1 < c) (i : ℕ) :
(1 - c⁻¹) * c ^ i ≤ ⌊c ^ i⌋₊ :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
rcases nat.eq_zero_or_pos i with rfl|hi,
{ simp only [pow_zero, nat.floor_one, nat.cast_one, mul_one, sub_le_self_iff, inv_nonneg,
cpos.le] },
have hident : 1 ≤ i := hi,
calc (1 - c⁻¹) * c ^ i
= c ^ i - c ^ i * c ⁻¹ : by ring
... ≤ c ^ i - 1 :
by simpa only [←div_eq_mul_inv, sub_le_sub_iff_left, one_le_div cpos, pow_one]
using pow_le_pow hc.le hident
... ≤ ⌊c ^ i⌋₊ : (nat.sub_one_lt_floor _).le
end
/-- The sum of `1/⌊c^i⌋₊^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative
constant. -/
lemma sum_div_nat_floor_pow_sq_le_div_sq (N : ℕ) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) :
∑ i in (range N).filter (λ i, j < ⌊c ^ i⌋₊), (1 : ℝ) / ⌊c ^ i⌋₊ ^ 2
≤ (c ^ 5 * (c - 1) ⁻¹ ^ 3) / j ^ 2 :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
have A : 0 < 1 - c⁻¹ := sub_pos.2 (inv_lt_one hc),
calc
∑ i in (range N).filter (λ i, j < ⌊c ^ i⌋₊), (1 : ℝ) / ⌊c ^ i⌋₊ ^ 2
≤ ∑ i in (range N).filter (λ i, j < c ^ i), (1 : ℝ) / ⌊c ^ i⌋₊ ^ 2 :
begin
apply sum_le_sum_of_subset_of_nonneg,
{ assume i hi,
simp only [mem_filter, mem_range] at hi,
simpa only [hi.1, mem_filter, mem_range, true_and]
using hi.2.trans_le (nat.floor_le (pow_nonneg cpos.le _)) },
{ assume i hi hident,
exact div_nonneg zero_le_one (sq_nonneg _), }
end
... ≤ ∑ i in (range N).filter (λ i, j < c ^ i), ((1 - c⁻¹) ⁻¹) ^ 2 * (1 / (c ^ i) ^ 2) :
begin
apply sum_le_sum (λ i hi, _),
rw [mul_div_assoc', mul_one, div_le_div_iff], rotate,
{ apply sq_pos_of_pos,
refine zero_lt_one.trans_le _,
simp only [nat.le_floor, one_le_pow_of_one_le, hc.le, nat.one_le_cast, nat.cast_one] },
{ exact sq_pos_of_pos (pow_pos cpos _) },
rw [one_mul, ← mul_pow],
apply pow_le_pow_of_le_left (pow_nonneg cpos.le _),
rw [← div_eq_inv_mul, le_div_iff A, mul_comm],
exact mul_pow_le_nat_floor_pow hc i,
end
... ≤ ((1 - c⁻¹) ⁻¹) ^ 2 * (c^3 * (c - 1) ⁻¹) / j ^ 2 :
begin
rw [← mul_sum, ← mul_div_assoc'],
refine mul_le_mul_of_nonneg_left _ (sq_nonneg _),
exact sum_div_pow_sq_le_div_sq N hj hc,
end
... = (c ^ 5 * (c - 1) ⁻¹ ^ 3) / j ^ 2 :
begin
congr' 1,
field_simp [cpos.ne', (sub_pos.2 hc).ne'],
ring,
end
end
|
f1fd0f676f431b8b667b7ac16aa04ba7258c68d0 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/doc_string1.lean | f6f2ebc9778e1a371bee3a51ce727da02d024aca | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 724 | lean | /--
Documentation for x
```
eval x + x
```
Testing...
-/
def x := 10 + 20
def y := "alo"
open tactic
run_command do
d ← doc_string `x,
trace d
run_command add_doc_string `y "testing simple doc"
run_command do
d ← doc_string `y,
trace d
namespace foo
namespace bla
/--
Documentation for single
testing...
hello
world
-/
inductive single
| unit
end bla
end foo
run_command do
trace "--------",
doc_string `foo.bla.single >>= trace
/-- Documentation for constant A
foo -/
constant A : Type
run_command doc_string `A >>= trace
/--Documentation for point
test
-/
structure point :=
(x : nat) (y : nat)
run_command doc_string `point >>= trace
print "----------"
|
c2c4207c0a72c0ad260d85805db4d4f53b0bea3d | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/ring_theory/algebra.lean | 727179e3645bdc469f88a2917b4b96d634b72f85 | [
"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 | 20,615 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import data.complex.basic
import data.matrix.basic
import linear_algebra.tensor_product
import ring_theory.subring
import algebra.commute
/-!
# Algebra over Commutative Semiring (under category)
In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`,
and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras
(`map`, `comap`).
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
-/
noncomputable theory
universes u v w u₁ v₁
open_locale tensor_product
section prio
-- We set this priority to 0 later in this file
set_option default_priority 200 -- see Note [default priority]
/-- 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. -/
@[nolint has_inhabited_instance]
class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A]
extends has_scalar R A, R →+* A :=
(commutes' : ∀ r x, to_fun r * x = x * to_fun r)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
/-- Embedding `R →+* A` given by `algebra` structure. -/
def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A :=
algebra.to_ring_hom
/-- Creating an algebra from a morphism in CRing. -/
def ring_hom.to_algebra {R S} [comm_semiring R] [semiring S] (i : R →+* S)
(h : ∀ c x, i c * x = x * i c) :
algebra R S :=
{ smul := λ c x, i c * x,
commutes' := h,
smul_def' := λ c x, rfl,
.. i}
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A]
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
@[priority 200] -- see Note [lower instance priority]
instance to_semimodule : semimodule R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R 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]
end semiring
-- TODO (semimodule linear maps): once we have them, port next section to semirings
section ring
variables [comm_ring R] [ring A] [algebra R A]
@[priority 200] -- see Note [lower instance priority]
instance to_module : module R A := { .. algebra.to_semimodule }
/-- 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 :=
ring_hom.to_algebra ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ $ λ _, mul_comm _
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])
/-- The multiplication on the left in an algebra is a linear map. -/
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
/-- The multiplication on the right in an algebra is a linear map. -/
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 ring
end algebra
instance module.endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := λ r, r • linear_map.id,
map_one' := one_smul _ _,
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul _ _ _,
map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] },
commutes' := by { intros, ext, simp },
smul_def' := by { intros, ext, simp } }
instance matrix_algebra (n : Type u) (R : Type v)
[fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) :=
{ to_fun := λ r, r • 1,
map_one' := one_smul _ _,
map_mul' := λ r₁ r₂, by { ext, simp [mul_assoc] },
map_zero' := zero_smul _ _,
map_add' := λ _ _, add_smul _ _ _,
commutes' := by { intros, simp },
smul_def' := by { intros, simp } }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_inhabited_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
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₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
variables (φ : A →ₐ[R] B)
@[ext]
theorem ext ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
by cases φ₁; cases φ₂; congr' 1; ext; apply H
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
φ.to_ring_hom.map_add r s
@[simp] lemma map_zero : φ 0 = 0 :=
φ.to_ring_hom.map_zero
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
φ.to_ring_hom.map_mul x y
@[simp] lemma map_one : φ 1 = 1 :=
φ.to_ring_hom.map_one
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
end
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[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 semiring
variables [comm_ring R] [ring A] [ring B] [ring C]
variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B)
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
φ.to_ring_hom.map_neg x
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
φ.to_ring_hom.map_sub x y
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
add := φ.map_add,
smul := λ (c : R) 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
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
end alg_hom
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments]
def comap : Type w := A
instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h
instance comap.semiring [h : semiring A] : semiring (comap R S A) := h
instance comap.ring [h : ring A] : ring (comap R S A) := h
instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h
instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h
instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] :
algebra S (comap R S A) := h
/-- Identity homomorphism `A →ₐ[S] comap R S A`. -/
def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] :
A →ₐ[S] comap R S A := alg_hom.id S A
/-- Identity homomorphism `comap R S A →ₐ[S] A`. -/
def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] :
comap R S A →ₐ[S] A := alg_hom.id S A
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
/-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map R S r • x : A),
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _,
.. (algebra_map S A).comp (algebra_map R S) }
/-- Embedding of `S` into `comap R S A`. -/
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
.. algebra_map S A }
theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring 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 :=
{ commutes' := λ r, φ.commutes (algebra_map R S r)
..φ }
end alg_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra $
λ r x, (commute.cast_int_left x r.1).div_left (commute.cast_nat_left x r.2)
end rat
namespace complex
instance algebra_over_reals : algebra ℝ ℂ :=
(ring_hom.of coe).to_algebra $ λ _, mul_comm _
end complex
/-- A subalgebra is a subring that includes the range of `algebra_map`. -/
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 R A) ≤ carrier)
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⟩
lemma range_le (S : subalgebra R A) : set.range (algebra_map R A) ≤ S := S.range_le'
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ (S : set A)⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[ext] 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
theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T :=
⟨λ h x, by rw h, ext⟩
variables (S : subalgebra R A)
instance : is_subring (S : set A) := S.subring
instance : ring S := @@subtype.ring _ S.is_subring
instance : inhabited S := ⟨0⟩
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⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_restrict S $ λ x, S.range_le ⟨x, rfl⟩ }
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 _
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := subtype.val }; intros; refl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
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 R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) :=
⟨to_submodule⟩
instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2
instance : partial_order (subalgebra R A) :=
{ le := λ S T, (S : set A) ≤ (T : set A),
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
/-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/
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⟩ }
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
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 R 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)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
begin
haveI : is_subring (set.range φ) := show is_subring (set.range φ.to_ring_hom), by apply_instance,
exact ⟨set.range φ, λ y ⟨r, hr⟩, ⟨algebra_map R A r, hr ▸ φ.commutes r⟩⟩
end
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 := (ring_hom.id R).to_algebra mul_comm
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
variables (R) {A}
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ carrier := ring.closure (set.range (algebra_map R A) ∪ s),
range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure }
variables {R}
protected lemma 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⟩
/-- Galois insertion between `adjoin` and `coe`. -/
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
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map 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
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
end algebra
section int
variables (R : Type*) [ring R]
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- CRing ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ commutes' := λ x y, commute.cast_int_left _ _,
smul_def' := λ _ _, gsmul_eq_mul _ _,
.. int.cast_ring_hom R }
variables {R}
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier := S,
range_le' := by { rintros _ ⟨i, rfl⟩, rw [ring_hom.eq_int_cast, ← gsmul_one],
exact is_add_subgroup.gsmul_mem 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
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
↑(span ℤ s) = add_group.closure s :=
set.subset.antisymm (λ x hx, span_induction hx
(λ _, add_group.mem_closure)
is_add_submonoid.zero_mem
(λ a b ha hb, is_add_submonoid.add_mem ha hb)
(λ n a ha, by { exact is_add_subgroup.gsmul_mem ha }))
(add_group.closure_subset subset_span)
@[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] :
(↑(span ℤ s) : set R) = s :=
by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup]
end span_int
end int
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
(E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F]
/-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict S R E`.
Not registered as an instance as `S` can not be inferred. -/
def module.restrict_scalars : module R E :=
{ smul := λc x, (algebra_map R S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
variables {S E}
local attribute [instance] module.restrict_scalars
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) : E →ₗ[R] F :=
{ to_fun := f.to_fun,
add := λx y, f.map_add x y,
smul := λc x, f.map_smul (algebra_map R S c) x }
@[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
module.restrict_scalars ℝ ℂ E
attribute [instance, priority 900] module.complex_to_real
end restrict_scalars
|
220d218286352ccfbe997775121094ab122a9fd0 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /examples/lean/ex3.lean | 0f0825c071415964779b74b23fc63d453676d39a | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 745 | lean | import macros.
theorem my_and_comm (a b : Bool) : (a ∧ b) → (b ∧ a)
:= assume H_ab, and_intro (and_elimr H_ab) (and_eliml H_ab).
theorem my_or_comm (a b : Bool) : (a ∨ b) → (b ∨ a)
:= assume H_ab,
or_elim H_ab
(λ H_a, or_intror b H_a)
(λ H_b, or_introl H_b a).
-- (em a) is the excluded middle a ∨ ¬a
-- (mt H H_na) is Modus Tollens with
-- H : (a → b) → a)
-- H_na : ¬a
-- produces
-- ¬(a → b)
--
-- not_imp_eliml applied to
-- (MT H H_na) : ¬(a → b)
-- produces
-- a
theorem pierce (a b : Bool) : ((a → b) → a) → a
:= assume H, or_elim (em a)
(λ H_a, H_a)
(λ H_na, not_imp_eliml (mt H H_na)).
print environment 3. |
5494b9f34b2b53f3023afdb002febd99483809ac | 626e312b5c1cb2d88fca108f5933076012633192 | /src/data/mv_polynomial/basic.lean | c1864e2678a05bcd15b24cfa4a3ed8e827960138 | [
"Apache-2.0"
] | permissive | Bioye97/mathlib | 9db2f9ee54418d29dd06996279ba9dc874fd6beb | 782a20a27ee83b523f801ff34efb1a9557085019 | refs/heads/master | 1,690,305,956,488 | 1,631,067,774,000 | 1,631,067,774,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 37,400 | 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.polynomial.eval
import data.finsupp.antidiagonal
/-!
# Multivariate polynomials
This file defines polynomial rings over a base ring (or even semiring),
with variables from a general type `σ` (which could be infinite).
## Important definitions
Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary
type. This file creates the type `mv_polynomial σ R`, which mathematicians
might denote $R[X_i : i \in σ]$. It is the type of multivariate
(a.k.a. multivariable) polynomials, with variables
corresponding to the terms in `σ`, and coefficients in `R`.
### Notation
In the definitions below, we use the following notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (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 : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
### Definitions
* `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients
in the commutative semiring `R`
* `monomial s a` : the monomial which mathematically would be denoted `a * X^s`
* `C a` : the constant polynomial with value `a`
* `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`.
* `coeff s p` : the coefficient of `s` in `p`.
* `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another
semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`.
Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested
that sticking to `eval` and `map` might make the code less brittle.
* `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation,
returning a term of type `R`
* `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of
coefficient semiring corresponding to `f`
## Implementation notes
Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite
support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`.
The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `R` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable 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 {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`R` is the coefficient ring -/
def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
section instances
instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] :
decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq
instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring
instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] :
distrib_mul_action R (mv_polynomial σ S₁) :=
add_monoid_algebra.distrib_mul_action
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] [has_faithful_scalar R S₁] :
has_faithful_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.has_faithful_scalar
instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) :=
add_monoid_algebra.module
instance [monoid R] [monoid S₁] [comm_semiring S₂]
[has_scalar R S₁] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [is_scalar_tower R S₁ S₂] :
is_scalar_tower R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.is_scalar_tower
instance [monoid R] [monoid S₁][comm_semiring S₂]
[distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [smul_comm_class R S₁ S₂] :
smul_comm_class R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.smul_comm_class
instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) :=
add_monoid_algebra.algebra
end instances
variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R}
/-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/
def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a
lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl
lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl
/-- `C a` is the constant polynomial with value `a` -/
def C : R →+* mv_polynomial σ R :=
{ to_fun := monomial 0, ..single_zero_ring_hom }
variables (R σ)
theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl
variables {R σ}
/-- `X n` is the degree `1` monomial $X_n$. -/
def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1
lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial]
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C_apply, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n :=
by induction n; simp [pow_succ, *]
lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] :
function.injective (C : R → mv_polynomial σ R) :=
finsupp.single_injective _
lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) [is_empty σ] :
function.surjective (C : R → mv_polynomial σ R) :=
begin
refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩,
simpa [(finsupp.ext is_empty_elim : a = 0), C_apply, monomial],
end
@[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) :
(C r : mv_polynomial σ R) = C s ↔ r = s :=
(C_injective σ R).eq_iff
instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective C (C_injective _ _)
instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R]
[nontrivial R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $
function.injective.comp
(λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _)
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
theorem C_mul' : mv_polynomial.C a * p = a • p :=
(algebra.smul_def a p).symm
lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq_C_mul_X {s : σ} {a : R} {n : ℕ} :
monomial (single s n) a = C a * (X s)^n :=
by rw [← zero_add (single s n), monomial_add_single, C_apply]
@[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} :
monomial s a + monomial s b = monomial s (a + b) :=
single_add.symm
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} :
monomial s a * monomial s' b = monomial (s + s') (a * b) :=
add_monoid_algebra.single_mul_single
@[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 :=
single_zero
@[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) :
sum (monomial u r) b = b u r :=
sum_single_index w
@[simp] lemma sum_C {A : Type*} [add_comm_monoid A]
{b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) :
sum (C a) b = b 0 a :=
by simp [C_apply, w]
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
begin
apply @finsupp.induction σ ℕ _ _ s,
{ simp only [C_apply, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm],
{ simp only [pow_zero], },
{ intro a, simp only [pow_zero], },
{ intros, rw pow_add, }, }
end
@[recursor 5]
lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [add_comm, monomial_add_single, this] }
end,
finsupp.induction p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ (this s a) hp)
attribute [elab_as_eliminator]
theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p :=
finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this,
show P (monomial 0 0), from h1 0 0)
(λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf)
@[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
by { ext, exacts [hC _, hX _] }
lemma hom_eq_hom [semiring S₂]
(f g : mv_polynomial σ R →+* S₂)
(hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) :
f p = g p :=
ring_hom.congr_fun (ring_hom_ext hC hX) p
lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R)
(hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) :
f p = p :=
hom_eq_hom f (ring_hom.id _) hC hX p
@[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A]
{f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) :
f = g :=
by { ext, exact hf _ }
@[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) :
f (C r) = C r :=
f.commutes r
section support
/--
The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient.
-/
def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) :=
p.support
lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} :=
by convert rfl
lemma support_monomial_subset : (monomial s a).support ⊆ {s} :=
support_single_subset
lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add
lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} :=
by rw [X, support_monomial, if_neg]; exact one_ne_zero
end support
section coeff
/-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R :=
@coe_fn _ (monoid_algebra.has_coe_to_fun _ _) p m
@[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∈ p.support ↔ p.coeff m ≠ 0 :=
by simp [support, coeff]
lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∉ p.support ↔ p.coeff m = 0 :=
by simp
lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} :
p.sum b = ∑ m in p.support, b m (p.coeff m) :=
by simp [support, finsupp.sum, coeff]
lemma support_mul (p q : mv_polynomial σ R) :
(p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) :=
by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl
@[ext] lemma ext (p q : mv_polynomial σ R) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ R) :
p = q ↔ (∀ m, coeff m p = coeff m q) :=
⟨ λ h m, by rw h, ext p q⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) :
coeff m (p + q) = coeff m p + coeff m q := add_apply p q m
@[simp] lemma coeff_smul {S₁ : Type*} [monoid S₁] [distrib_mul_action S₁ R]
(m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) :
coeff m (c • p) = c • coeff m p := smul_apply c p m
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ R) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 :=
single_eq_of_ne (λ h, by cases single_eq_zero.1 h)
/-- `mv_polynomial.coeff m` but promoted to an `add_monoid_hom`. -/
@[simps] def coeff_add_monoid_hom (m : σ →₀ ℕ) : mv_polynomial σ R →+ R :=
{ to_fun := coeff m,
map_zero' := coeff_zero m,
map_add' := coeff_add m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) :
coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) :=
(coeff_add_monoid_hom _).map_sum _ s
lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) :
coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C [decidable_eq σ] (m) (a) :
coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 :=
single_apply
lemma coeff_one [decidable_eq σ] (m) :
coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 :=
coeff_C m 1
@[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a :=
single_eq_same
@[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 :=
coeff_zero_C 1
lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:R),
rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' [decidable_eq σ] (i : σ) (m) :
coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ R) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) :
coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, sum_C],
{ simp [sum_def, coeff_sum] {contextual := tt} },
simp
end
lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) :
coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q :=
begin
rw mul_def,
-- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`,
-- so we need to turn both sides into a sum over a product.
have := @finset.sum_product R (σ →₀ ℕ) _ _ p.support q.support
(λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0),
convert this.symm using 1; clear this,
{ rw [coeff],
iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only },
exact single_apply },
symmetry,
-- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`.
apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)),
{ intros x hx hx',
simp only [mem_antidiagonal, eq_self_iff_true, if_false, forall_true_iff],
contrapose! hx',
rw [if_neg hx'] },
{ rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl',
simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro },
{ rintros ⟨i, j⟩ hij hij',
refine ⟨⟨i, j⟩, _, _⟩,
{ simp only [mem_support_iff, finset.mem_product],
contrapose! hij',
exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' },
{ rw [mem_antidiagonal] at hij,
simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } },
{ intros x hx hx',
simp only [ne.def] at hx' ⊢,
split_ifs with H,
{ refl },
{ rw if_neg H at hx', contradiction } }
end
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) :
coeff (m + single s 1) (p * X s) = coeff m p :=
begin
have : (m, single s 1) ∈ (m + single s 1).antidiagonal := mem_antidiagonal.2 rfl,
rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.sum_eq_zero, add_zero, coeff_X, mul_one],
rintros ⟨i,j⟩ hij,
rw [finset.mem_erase, mem_antidiagonal] at hij,
by_cases H : single s 1 = j,
{ subst j, simpa using hij },
{ rw [coeff_X', if_neg H, mul_zero] },
end
lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
nontriviality R,
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_X _ s},
congr' with t,
by_cases hj : s = t,
{ subst t, simp only [nat_sub_apply, add_apply, single_eq_same],
refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa finsupp.mem_support_iff at h },
{ simp [single_eq_of_ne hj] } },
{ rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
rw [support_X, finset.mem_singleton] at hi', subst i',
rw finset.mem_singleton at H, subst m,
rw [finsupp.mem_support_iff, add_apply, single_apply, if_pos rfl],
intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 }
end
lemma eq_zero_iff {p : mv_polynomial σ R} :
p = 0 ↔ ∀ d, coeff d p = 0 :=
by { rw ext_iff, simp only [coeff_zero], }
lemma ne_zero_iff {p : mv_polynomial σ R} :
p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 :=
by { rw [ne.def, eq_zero_iff], push_neg, }
lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) :
∃ d, coeff d p ≠ 0 :=
ne_zero_iff.mp h
lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) :
C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i :=
begin
split,
{ rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0,
let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i),
use ψ,
apply mv_polynomial.ext, intro i,
simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'],
split_ifs with hi hi,
{ rw hc },
{ rw not_mem_support_iff at hi, rwa mul_zero } },
end
end coeff
section constant_coeff
/--
`constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`.
This is a ring homomorphism.
-/
def constant_coeff : mv_polynomial σ R →+* R :=
{ to_fun := coeff 0,
map_one' := by simp [coeff, add_monoid_algebra.one_def],
map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero],
map_zero' := coeff_zero _,
map_add' := coeff_add _ }
lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl
@[simp]
lemma constant_coeff_C (r : R) :
constant_coeff (C r : mv_polynomial σ R) = r :=
by simp [constant_coeff_eq]
@[simp]
lemma constant_coeff_X (i : σ) :
constant_coeff (X i : mv_polynomial σ R) = 0 :=
by simp [constant_coeff_eq]
lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) :
constant_coeff (monomial d r) = if d = 0 then r else 0 :=
by rw [constant_coeff_eq, coeff_monomial]
variables (σ R)
@[simp] lemma constant_coeff_comp_C :
constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R :=
by { ext, apply constant_coeff_C }
@[simp] lemma constant_coeff_comp_algebra_map :
constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R :=
constant_coeff_comp_C _ _
end constant_coeff
section as_sum
@[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) :
∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables (f : R →+* S₁) (g : σ → S₁)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ R) : S₁ :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i :=
by { simp only [eval₂_eq, ← finsupp.prod_pow], refl }
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [f.map_zero])
(by simp [add_mul, f.map_add])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [f.map_zero])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by simp [eval₂_monomial, C, prod_zero_index]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans f.map_one
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial, f.map_one, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, f.map_mul] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by rw [monomial_single_add, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
f.map_one, -add_comm] }
end
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ }
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
/-- `mv_polynomial.eval₂` as a `ring_hom`. -/
def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ :=
{ to_fun := eval₂ f g,
map_one' := eval₂_one _ _,
map_mul' := λ p q, eval₂_mul _ _,
map_zero' := eval₂_zero _ _,
map_add' := λ p q, eval₂_add _ _ }
@[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) :
⇑(eval₂_hom f g) = eval₂ f g := rfl
lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
by rintros rfl rfl rfl; refl
end
@[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) :
eval₂_hom f g (C r) = f r := eval₂_C f g r
@[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) :
eval₂_hom f g (X i) = g i := eval₂_X f g i
@[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) :
φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) :=
begin
apply mv_polynomial.ring_hom_ext,
{ intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] },
{ intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] }
end
lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) :=
by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod,
ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X']
section
lemma eval₂_comp_left {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, k.map_add,
eval₂_mul, k.map_mul] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → S₁)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_prod _ s
@[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_sum _ s
attribute [to_additive] eval₂_prod
lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
begin
show _ = eval₂_hom f g (eval₂ C q p),
rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp,
end
end eval₂
section eval
variables {f : σ → R}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f
lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id R) x f
lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _
@[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p :=
by rw [smul_eq_C_mul, (eval x).map_mul, eval_C]
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
(eval g).map_sum _ _
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
(eval g).map_prod _ _
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ R) (g : τ → R)
(p : mv_polynomial σ R) :
eval (eval g ∘ f) p = eval g (eval₂ C f p) :=
begin
rw eval₂_comp_left (eval g),
unfold eval, simp only [coe_eval₂_hom],
congr' with a, simp
end
end eval
section map
variables (f : R →+* S₁)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _
theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta
theorem map_map [comm_semiring S₂]
(g : S₁ →+* S₂)
(p : mv_polynomial σ R) :
map g (map f p) = map (g.comp f) p :=
(eval₂_comp_left (map g) (C.comp f) X p).trans $
begin
congr,
{ ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], },
{ ext1 n, simp only [map_X, comp_app], }
end
theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) :
p.eval₂ f g = eval g (map f p) :=
begin
unfold map eval, simp only [coe_eval₂_hom],
have h := eval₂_comp_left (eval₂_hom _ g),
dsimp at h,
rw h,
congr,
{ ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], },
{ ext1 n, simp only [comp_app, eval₂_X], },
end
lemma eval₂_comp_right {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero },
{ intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add },
{ intros p i hp m, simp only [hp, (map f).map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw f.map_zero }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
@[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) :
eval g (map f p) = eval₂ f g p :=
by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } }
@[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂ φ g (map f p) = eval₂ (φ.comp f) g p :=
by { rw [← eval_map, ← eval_map, map_map], }
@[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p :=
eval₂_map f g φ p
@[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) :
constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) :=
coeff_map f φ 0
lemma constant_coeff_comp_map (f : R →+* S₁) :
(constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff :=
by { ext; simp }
lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support :=
begin
intro x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f
end
lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) :
(map f p).support = p.support :=
begin
apply finset.subset.antisymm,
{ exact mv_polynomial.support_map_subset _ _ },
intros x hx,
rw mem_support_iff,
contrapose! hx,
simp only [not_not, mem_support_iff],
change (map f p).coeff x = 0 at hx,
rw [coeff_map, ← f.map_zero] at hx,
exact hf hx
end
lemma C_dvd_iff_map_hom_eq_zero
(q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r')
(φ : mv_polynomial σ R) :
C r ∣ φ ↔ map q φ = 0 :=
begin
rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff],
simp only [coeff_map, coeff_zero, hr],
end
lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) :
map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ :=
begin
rw mv_polynomial.ext_iff,
apply forall_congr, intro m,
rw [coeff_map],
apply eq_iff_eq_cancel_right.mpr,
refl
end
end map
section aeval
/-! ### The algebra of multivariate polynomials -/
variables (f : σ → S₁)
variables [algebra R S₁] [comm_semiring S₂]
/-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `S₁`. -/
def aeval : mv_polynomial σ R →ₐ[R] S₁ :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R S₁) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl
lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) :
aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl
@[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _
theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) :
φ = aeval (φ ∘ X) :=
by { ext i, simp }
lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B]
(φ : S₁ →ₐ[R] B) :
φ.comp (aeval f) = aeval (λ i, φ (f i)) :=
by { ext i, simp }
@[simp] lemma map_aeval {B : Type*} [comm_semiring B]
(g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) :
φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
@[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) :=
begin
suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff,
from ring_hom.congr_fun this p,
ext; simp
end
@[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero f p
@[simp] lemma aeval_zero (p : mv_polynomial σ R) :
aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_zero (algebra_map R S₁) p
@[simp] lemma aeval_zero' (p : mv_polynomial σ R) :
aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
aeval_zero p
lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) :=
eval₂_hom_monomial _ _ _ _
lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) :
eval₂_hom f g φ = 0 :=
begin
rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero],
intros d hd,
obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd),
rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hgi, zero_pow],
rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff]
end
lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) :
aeval f φ = 0 :=
eval₂_hom_eq_zero _ _ _ h
end aeval
end comm_semiring
end mv_polynomial
|
d4e54ee9fbe11be1c5dc40d9d2ed0c387eadc31a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/ring/inj_surj.lean | 881bd62bd6718a0d1655ba6ea92e7e35d92d7397 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 12,150 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro
-/
import algebra.order.ring.defs
import algebra.order.monoid.cancel.basic
import algebra.ring.inj_surj
/-!
# Pulling back ordered rings along injective maps.
-/
open function
universe u
variables {α : Type u} {β : Type*}
namespace function.injective
/-- Pullback an `ordered_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def ordered_semiring [ordered_semiring α] [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0)
(one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) :
ordered_semiring β :=
{ zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one],
mul_le_mul_of_nonneg_left := λ a b c h hc, show f (c * a) ≤ f (c * b),
by { rw [mul, mul], refine mul_le_mul_of_nonneg_left h _, rwa ←zero },
mul_le_mul_of_nonneg_right := λ a b c h hc, show f (a * c) ≤ f (b * c),
by { rw [mul, mul], refine mul_le_mul_of_nonneg_right h _, rwa ←zero },
..hf.ordered_add_comm_monoid f zero add nsmul,
..hf.semiring f zero one add mul nsmul npow nat_cast }
/-- Pullback an `ordered_comm_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def ordered_comm_semiring [ordered_comm_semiring α] [has_zero β] [has_one β] [has_add β]
[has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α) (hf : injective f)
(zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) :
ordered_comm_semiring β :=
{ ..hf.comm_semiring f zero one add mul nsmul npow nat_cast,
..hf.ordered_semiring f zero one add mul nsmul npow nat_cast }
/-- Pullback an `ordered_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def ordered_ring [ordered_ring α] [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β]
[has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
ordered_ring β :=
{ mul_nonneg := λ a b ha hb, show f 0 ≤ f (a * b),
by { rw [zero, mul], apply mul_nonneg; rwa ← zero },
..hf.ordered_semiring f zero one add mul nsmul npow nat_cast,
..hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
/-- Pullback an `ordered_comm_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def ordered_comm_ring [ordered_comm_ring α] [has_zero β] [has_one β] [has_add β]
[has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β]
[has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
ordered_comm_ring β :=
{ ..hf.ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast,
..hf.comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
/-- Pullback a `strict_ordered_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def strict_ordered_semiring [strict_ordered_semiring α] [has_zero β] [has_one β]
[has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) :
strict_ordered_semiring β :=
{ mul_lt_mul_of_pos_left := λ a b c h hc, show f (c * a) < f (c * b),
by simpa only [mul, zero] using mul_lt_mul_of_pos_left ‹f a < f b› (by rwa ←zero),
mul_lt_mul_of_pos_right := λ a b c h hc, show f (a * c) < f (b * c),
by simpa only [mul, zero] using mul_lt_mul_of_pos_right ‹f a < f b› (by rwa ←zero),
..hf.ordered_cancel_add_comm_monoid f zero add nsmul,
..hf.ordered_semiring f zero one add mul nsmul npow nat_cast,
..pullback_nonzero f zero one }
/-- Pullback a `strict_ordered_comm_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def strict_ordered_comm_semiring [strict_ordered_comm_semiring α] [has_zero β] [has_one β]
[has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) :
strict_ordered_comm_semiring β :=
{ ..hf.comm_semiring f zero one add mul nsmul npow nat_cast,
..hf.strict_ordered_semiring f zero one add mul nsmul npow nat_cast }
/-- Pullback a `strict_ordered_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def strict_ordered_ring [strict_ordered_ring α] [has_zero β] [has_one β] [has_add β]
[has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β]
[has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
strict_ordered_ring β :=
{ mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero },
..hf.strict_ordered_semiring f zero one add mul nsmul npow nat_cast,
..hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
/-- Pullback a `strict_ordered_comm_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def strict_ordered_comm_ring [strict_ordered_comm_ring α] [has_zero β]
[has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β]
[has_smul ℤ β] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0)
(one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
strict_ordered_comm_ring β :=
{ ..hf.strict_ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast,
..hf.comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
/-- Pullback a `linear_ordered_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def linear_ordered_semiring [linear_ordered_semiring α] [has_zero β] [has_one β]
[has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] [has_sup β] [has_inf β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y))
(hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) :
linear_ordered_semiring β :=
{ .. linear_order.lift f hf hsup hinf,
.. hf.strict_ordered_semiring f zero one add mul nsmul npow nat_cast }
/-- Pullback a `linear_ordered_semiring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def linear_ordered_comm_semiring [linear_ordered_comm_semiring α]
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β]
[has_sup β] [has_inf β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y))
(hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) :
linear_ordered_comm_semiring β :=
{ ..hf.linear_ordered_semiring f zero one add mul nsmul npow nat_cast hsup hinf,
..hf.strict_ordered_comm_semiring f zero one add mul nsmul npow nat_cast }
/-- Pullback a `linear_ordered_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
def linear_ordered_ring [linear_ordered_ring α] [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β]
[has_int_cast β] [has_sup β] [has_inf β] (f : β → α) (hf : injective f) (zero : f 0 = 0)
(one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n)
(hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) :
linear_ordered_ring β :=
{ .. linear_order.lift f hf hsup hinf,
.. hf.strict_ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
/-- Pullback a `linear_ordered_comm_ring` under an injective map. -/
@[reducible] -- See note [reducible non-instances]
protected def linear_ordered_comm_ring [linear_ordered_comm_ring α] [has_zero β]
[has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β]
[has_smul ℤ β] [has_nat_cast β] [has_int_cast β] [has_sup β] [has_inf β] (f : β → α)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x)
(sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n)
(hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) :
linear_ordered_comm_ring β :=
{ .. linear_order.lift f hf hsup hinf,
.. hf.strict_ordered_comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast }
end function.injective
|
8d30d033e7815ff44d2617d15dfac50f42ccec87 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Meta/InferType.lean | 75b98fa75142c766ddce2a3a65ee9bd384d0d247 | [
"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 | 17,269 | 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.Data.LBool
import Lean.Meta.Basic
namespace Lean
/-
Auxiliary function for instantiating the loose bound variables in `e` with `args[start:stop]`.
This function is similar to `instantiateRevRange`, but it applies beta-reduction when
we instantiate a bound variable with a lambda expression.
Example: Given the term `#0 a`, and `start := 0, stop := 1, args := #[fun x => x]` the result is
`a` instead of `(fun x => x) a`.
This reduction is useful when we are inferring the type of eliminator-like applications.
For example, given `(n m : Nat) (f : Nat → Nat) (h : m = n)`,
the type of `Eq.subst (motive := fun x => f m = f x) h rfl`
is `motive n` which is `(fun (x : Nat) => f m = f x) n`
This function reduces the new application to `f m = f n`
We use it to implement `inferAppType`
-/
partial def Expr.instantiateBetaRevRange (e : Expr) (start : Nat) (stop : Nat) (args : Array Expr) : Expr :=
if e.hasLooseBVars && stop > start then
assert! stop ≤ args.size
visit e 0 |>.run
else
e
where
visit (e : Expr) (offset : Nat) : MonadStateCacheT (ExprStructEq × Nat) Expr Id Expr :=
if offset >= e.looseBVarRange then
-- `e` doesn't have free variables
return e
else checkCache ({ val := e : ExprStructEq }, offset) fun _ => do
match e with
| Expr.forallE _ d b _ => return e.updateForallE! (← visit d offset) (← visit b (offset+1))
| Expr.lam _ d b _ => return e.updateLambdaE! (← visit d offset) (← visit b (offset+1))
| Expr.letE _ t v b _ => return e.updateLet! (← visit t offset) (← visit v offset) (← visit b (offset+1))
| Expr.mdata _ b _ => return e.updateMData! (← visit b offset)
| Expr.proj _ _ b _ => return e.updateProj! (← visit b offset)
| Expr.app f a _ =>
e.withAppRev fun f revArgs => do
let fNew ← visit f offset
let revArgs ← revArgs.mapM (visit · offset)
if f.isBVar then
-- try to beta reduce if `f` was a bound variable
return fNew.betaRev revArgs
else
return mkAppRev fNew revArgs
| Expr.bvar vidx _ =>
-- Recall that looseBVarRange for `Expr.bvar` is `vidx+1`.
-- So, we must have offset ≤ vidx, since we are in the "else" branch of `if offset >= e.looseBVarRange`
let n := stop - start
if vidx < offset + n then
return args[stop - (vidx - offset) - 1].liftLooseBVars 0 offset
else
return mkBVar (vidx - n)
-- The following cases are unreachable because they never contain loose bound variables
| Expr.const .. => unreachable!
| Expr.fvar .. => unreachable!
| Expr.mvar .. => unreachable!
| Expr.sort .. => unreachable!
| Expr.lit .. => unreachable!
namespace Meta
def throwFunctionExpected {α} (f : Expr) : MetaM α :=
throwError "function expected{indentExpr f}"
private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do
let mut fType ← inferType f
let mut j := 0
/- TODO: check whether `instantiateBetaRevRange` is too expensive, and
use it only when `args` contains a lambda expression. -/
for i in [:args.size] do
match fType with
| Expr.forallE _ _ b _ => fType := b
| _ =>
match (← whnf <| fType.instantiateBetaRevRange j i args) with
| Expr.forallE _ _ b _ => j := i; fType := b
| _ => throwFunctionExpected <| mkAppRange f 0 (i+1) args
return fType.instantiateBetaRevRange j args.size args
def throwIncorrectNumberOfLevels {α} (constName : Name) (us : List Level) : MetaM α :=
throwError "incorrect number of universe levels {mkConst constName us}"
private def inferConstType (c : Name) (us : List Level) : MetaM Expr := do
let cinfo ← getConstInfo c
if cinfo.levelParams.length == us.length then
return cinfo.instantiateTypeLevelParams us
else
throwIncorrectNumberOfLevels c us
private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do
let failed {α} : Unit → MetaM α := fun _ =>
throwError "invalid projection{indentExpr (mkProj structName idx e)}"
let structType ← inferType e
let structType ← whnf structType
matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal =>
let n := structVal.numParams
let structParams := structType.getAppArgs
if n != structParams.size then failed ()
else do
let mut ctorType ← inferAppType (mkConst ctorVal.name structLvls) structParams
for i in [:idx] do
ctorType ← whnf ctorType
match ctorType with
| Expr.forallE _ _ body _ =>
if body.hasLooseBVars then
ctorType := body.instantiate1 $ mkProj structName i e
else
ctorType := body
| _ => failed ()
ctorType ← whnf ctorType
match ctorType with
| Expr.forallE _ d _ _ => pure d
| _ => failed ()
def throwTypeExcepted {α} (type : Expr) : MetaM α :=
throwError "type expected{indentExpr type}"
def getLevel (type : Expr) : MetaM Level := do
let typeType ← inferType type
let typeType ← whnfD typeType
match typeType with
| Expr.sort lvl _ => pure lvl
| Expr.mvar mvarId _ =>
if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
throwTypeExcepted type
else
let lvl ← mkFreshLevelMVar
assignExprMVar mvarId (mkSort lvl)
pure lvl
| _ => throwTypeExcepted type
private def inferForallType (e : Expr) : MetaM Expr :=
forallTelescope e fun xs e => do
let lvl ← getLevel e
let lvl ← xs.foldrM (init := lvl) fun x lvl => do
let xType ← inferType x
let xTypeLvl ← getLevel xType
pure $ mkLevelIMax' xTypeLvl lvl
pure $ mkSort lvl.normalize
/- Infer type of lambda and let expressions -/
private def inferLambdaType (e : Expr) : MetaM Expr :=
lambdaLetTelescope e fun xs e => do
let type ← inferType e
mkForallFVars xs type
@[inline] private def withLocalDecl' {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α :=
savingCache do
let fvarId ← mkFreshFVarId
withReader (fun ctx => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) do
x (mkFVar fvarId)
def throwUnknownMVar {α} (mvarId : MVarId) : MetaM α :=
throwError "unknown metavariable '?{mvarId.name}'"
private def inferMVarType (mvarId : MVarId) : MetaM Expr := do
match (← getMCtx).findDecl? mvarId with
| some d => pure d.type
| none => throwUnknownMVar mvarId
private def inferFVarType (fvarId : FVarId) : MetaM Expr := do
match (← getLCtx).find? fvarId with
| some d => pure d.type
| none => throwUnknownFVar fvarId
@[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do
match (← get).cache.inferType.find? e with
| some type => pure type
| none =>
let type ← inferType
unless e.hasMVar || type.hasMVar do
modifyInferTypeCache fun c => c.insert e type
pure type
@[export lean_infer_type]
def inferTypeImp (e : Expr) : MetaM Expr :=
let rec infer : Expr → MetaM Expr
| Expr.const c [] _ => inferConstType c []
| Expr.const c us _ => checkInferTypeCache e (inferConstType c us)
| e@(Expr.proj n i s _) => checkInferTypeCache e (inferProjType n i s)
| e@(Expr.app f _ _) => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs)
| Expr.mvar mvarId _ => inferMVarType mvarId
| Expr.fvar fvarId _ => inferFVarType fvarId
| Expr.bvar bidx _ => throwError "unexpected bound variable {mkBVar bidx}"
| Expr.mdata _ e _ => infer e
| Expr.lit v _ => pure v.type
| Expr.sort lvl _ => pure $ mkSort (mkLevelSucc lvl)
| e@(Expr.forallE _ _ _ _) => checkInferTypeCache e (inferForallType e)
| e@(Expr.lam _ _ _ _) => checkInferTypeCache e (inferLambdaType e)
| e@(Expr.letE _ _ _ _ _) => checkInferTypeCache e (inferLambdaType e)
withIncRecDepth <| withTransparency TransparencyMode.default (infer e)
/--
Return `LBool.true` if given level is always equivalent to universe level zero.
It is used to implement `isProp`. -/
private def isAlwaysZero : Level → Bool
| Level.zero _ => true
| Level.mvar _ _ => false
| Level.param _ _ => false
| Level.succ _ _ => false
| Level.max u v _ => isAlwaysZero u && isAlwaysZero v
| Level.imax _ u _ => isAlwaysZero u
/--
`isArrowProp type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> Prop`.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowProp : Expr → Nat → MetaM LBool
| Expr.sort u _, 0 => return isAlwaysZero (← instantiateLevelMVars u) |>.toLBool
| Expr.forallE _ _ _ _, 0 => pure LBool.false
| Expr.forallE _ _ b _, n+1 => isArrowProp b n
| Expr.letE _ _ _ b _, n => isArrowProp b n
| Expr.mdata _ e _, n => isArrowProp e n
| _, _ => pure LBool.undef
/--
`isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a proposition. -/
private partial def isPropQuickApp : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProp constType arity
| Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType arity
| Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType arity
| Expr.app f _ _, arity => isPropQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isPropQuickApp e arity
| Expr.letE _ _ _ b _, arity => isPropQuickApp b arity
| Expr.lam _ _ _ _, 0 => pure LBool.false
| Expr.lam _ _ b _, arity+1 => isPropQuickApp b arity
| _, _ => pure LBool.undef
/--
`isPropQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a proposition. -/
partial def isPropQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.false
| Expr.lam _ _ _ _ => pure LBool.false
| Expr.letE _ _ _ b _ => isPropQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => isPropQuick b
| Expr.mdata _ e _ => isPropQuick e
| Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProp constType 0
| Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType 0
| Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType 0
| Expr.app f _ _ => isPropQuickApp f 1
/-- `isProp whnf e` return `true` if `e` is a proposition.
If `e` contains metavariables, it may not be possible
to decide whether is a proposition or not. We return `false` in this
case. We considered using `LBool` and retuning `LBool.undef`, but
we have no applications for it. -/
def isProp (e : Expr) : MetaM Bool := do
let r ← isPropQuick e
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef =>
let type ← inferType e
let type ← whnfD type
match type with
| Expr.sort u _ => return isAlwaysZero (← instantiateLevelMVars u)
| _ => pure false
/--
`isArrowProposition type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowProposition : Expr → Nat → MetaM LBool
| Expr.forallE _ _ b _, n+1 => isArrowProposition b n
| Expr.letE _ _ _ b _, n => isArrowProposition b n
| Expr.mdata _ e _, n => isArrowProposition e n
| type, 0 => isPropQuick type
| _, _ => pure LBool.undef
mutual
/--
`isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a proof. -/
private partial def isProofQuickApp : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProposition constType arity
| Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity
| Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity
| Expr.app f _ _, arity => isProofQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isProofQuickApp e arity
| Expr.letE _ _ _ b _, arity => isProofQuickApp b arity
| Expr.lam _ _ b _, 0 => isProofQuick b
| Expr.lam _ _ b _, arity+1 => isProofQuickApp b arity
| _, _ => pure LBool.undef
/--
`isProofQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a proof. -/
partial def isProofQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.false
| Expr.lam _ _ b _ => isProofQuick b
| Expr.letE _ _ _ b _ => isProofQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => pure LBool.false
| Expr.mdata _ e _ => isProofQuick e
| Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProposition constType 0
| Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0
| Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0
| Expr.app f _ _ => isProofQuickApp f 1
end
def isProof (e : Expr) : MetaM Bool := do
let r ← isProofQuick e
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => do
let type ← inferType e
Meta.isProp type
/--
`isArrowType type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> Sort _`.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowType : Expr → Nat → MetaM LBool
| Expr.sort u _, 0 => pure LBool.true
| Expr.forallE _ _ _ _, 0 => pure LBool.false
| Expr.forallE _ _ b _, n+1 => isArrowType b n
| Expr.letE _ _ _ b _, n => isArrowType b n
| Expr.mdata _ e _, n => isArrowType e n
| _, _ => pure LBool.undef
/--
`isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a type. -/
private partial def isTypeQuickApp : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowType constType arity
| Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowType fvarType arity
| Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowType mvarType arity
| Expr.app f _ _, arity => isTypeQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isTypeQuickApp e arity
| Expr.letE _ _ _ b _, arity => isTypeQuickApp b arity
| Expr.lam _ _ _ _, 0 => pure LBool.false
| Expr.lam _ _ b _, arity+1 => isTypeQuickApp b arity
| _, _ => pure LBool.undef
/--
`isTypeQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a type. -/
partial def isTypeQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.true
| Expr.lam _ _ _ _ => pure LBool.false
| Expr.letE _ _ _ b _ => isTypeQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => pure LBool.true
| Expr.mdata _ e _ => isTypeQuick e
| Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowType constType 0
| Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowType fvarType 0
| Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowType mvarType 0
| Expr.app f _ _ => isTypeQuickApp f 1
def isType (e : Expr) : MetaM Bool := do
let r ← isTypeQuick e
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef =>
let type ← inferType e
let type ← whnfD type
match type with
| Expr.sort _ _ => pure true
| _ => pure false
partial def isTypeFormerType (type : Expr) : MetaM Bool := do
let type ← whnfD type
match type with
| Expr.sort _ _ => pure true
| Expr.forallE n d b c =>
withLocalDecl' n c.binderInfo d fun fvar =>
isTypeFormerType (b.instantiate1 fvar)
| _ => pure false
/--
Return true iff `e : Sort _` or `e : (forall As, Sort _)`.
Remark: it subsumes `isType` -/
def isTypeFormer (e : Expr) : MetaM Bool := do
let type ← inferType e
isTypeFormerType type
end Lean.Meta
|
42ebfa23295502f748914d4661e9479f60a8be2f | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/exercises/src_18_inequalities_and_upper_bounds.lean | 8f388f6d9791f131f3ba112a06fc70d5cf9ba02f | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,192 | lean | import tactic.linarith
namespace mth1001
section inequalities_and_upper_bounds
/-
At the start of this module, we looked at simple inequalities. We'll extend our study to
consider bounds and greatest bounds.
These considerations will later form the basis of our study of suprema of sets of real numbers.
-/
-- Given, `x ≤ 2`, we can prove `3 * x + 8 ≥ 5 * x`.
-- Below, `∀ x ≤ 2, 3 * x + 8 ≥ 5 * x` is an abbreviation of `∀ x, x ≤ 2 → 3 * x + 8 ≥ 5 * x`.
example : ∀ x ≤ 2, 3 * x + 8 ≥ 5 * x :=
begin
intros x hx,
linarith,
end
-- Exercise 100:
example : ∀ x ≤ 0, 3 * x + 8 ≥ 5 * x :=
begin
sorry
end
/-
We can generalise the above, writing `x ≤ y` instead of `x ≤ 2` or `x ≤ 0`. However, it simply
isn't true *for every `y`* that if `x ≤ y`, then `3 * x + 8 ≥ 5 * x`. We ask you to prove this
below.
-/
-- Exercise 101:
example : ¬(∀ y, ∀ x, x ≤ y → 3 * x + 8 ≥ 5 * x) :=
begin
sorry
end
/-
However, if we impose constraints on `y`, for instance, given `y ≤ 3`, given `x ≤ y`, you can
prove `3 * x + 8 ≥ 5 * x`.
-/
-- Exercise 102:
example : ∀ y ≤ 1, ∀ x ≤ y, 3 * x + 8 ≥ 5 * x :=
begin
sorry
end
/-
Now `1` isn't the only bound for `y`.
-/
-- Exercise 103:
example : ∀ y ≤ 0, ∀ x ≤ y, 3 * x + 8 ≥ 5 * x :=
begin
sorry
end
-- Exercise 104:
/-
We can generalise further, writing `y ≤ z` instead of `1` or `0` above. Once more, however, it
isn't true that *for every* `z`, given `y ≤ z`, given `x ≤ y`, one has `3 * x + 8 ≥ 5 * x`.
-/
example : ¬(∀ z, ∀ y ≤ z, ∀ x ≤ y, 3 * x + 8 ≥ 5 * x) :=
begin
sorry
end
/-
We'll write a new definition `is_bnd_ineq` so that `is_bnd_ineq z` holds if, given `y ≤ z`,
given `x ≤ y`, one has `3 * x + 8 ≥ 5 * x`.
-/
def is_bnd_ineq (z : ℤ) := ∀ y ≤ z, ∀ x ≤ y, 3 * x + 8 ≥ 5 * x
/-
With this definition, we can rephrase some of the results above. The proofs are no different.
-/
-- Exercise 105:
example : is_bnd_ineq 1 :=
begin
unfold is_bnd_ineq, -- This line isn't necessary for Lean, but helps the human proof writer!
sorry
end
-- Exercise 106:
example : is_bnd_ineq 0 :=
begin
sorry
end
/-
We come now to the main definition of this section. What does it mean to be a *greatest* bound?
`z` is a greatest bound if:
* `z` is a bound (i.e. we have `is_bnd_ineq z`) and
* For every `w`, if `w` is a bound, then `w ≤ z`.
-/
def greatest_bnd_ineq (z : ℤ) :=
is_bnd_ineq z ∧ (∀ w, is_bnd_ineq w → w ≤ z)
/-
The main task of this section is to prove `greatest_bnd_ineq 4`, i.e that `4` is a greatest bound.
-/
-- Exercise 107:
example : greatest_bnd_ineq 4 :=
begin
sorry
end
/-
We'd like to conclude that `4` is *the* greatest bound, but we haven't proved that there is only
one greatest bound. This, we proceed to do.
-/
-- Exercise 108:
example (z₁ z₂ : ℤ) : greatest_bnd_ineq z₁ ∧ greatest_bnd_ineq z₂ → z₁ = z₂ :=
begin
intro h,
rcases h with ⟨⟨bnd₁, gt₁⟩, bnd₂, gt₂⟩,
have : z₁ ≤ z₂,
{ sorry, },
have : z₂ ≤ z₁,
{ sorry, },
linarith,
end
end inequalities_and_upper_bounds
end mth1001
|
d19354e693ed23875642250826b1486e5c55d6c0 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/typeclass_diamond.lean | a48898e86240c579733c66318a7d2a7802515281 | [
"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,750 | lean | new_frontend
class Top₁ (n : Nat) : Type := (u : Unit := ())
class Bot₁ (n : Nat) : Type := (u : Unit := ())
class Left₁ (n : Nat) : Type := (u : Unit := ())
class Right₁ (n : Nat) : Type := (u : Unit := ())
instance Bot₁Inst : Bot₁ Nat.zero := {}
instance Left₁ToBot₁ (n : Nat) [Left₁ n] : Bot₁ n := {}
instance Right₁ToBot₁ (n : Nat) [Right₁ n] : Bot₁ n := {}
instance Top₁ToLeft₁ (n : Nat) [Top₁ n] : Left₁ n := {}
instance Top₁ToRight₁ (n : Nat) [Top₁ n] : Right₁ n := {}
instance Bot₁ToTopSucc (n : Nat) [Bot₁ n] : Top₁ n.succ := {}
class Top₂ (n : Nat) : Type := (u : Unit := ())
class Bot₂ (n : Nat) : Type := (u : Unit := ())
class Left₂ (n : Nat) : Type := (u : Unit := ())
class Right₂ (n : Nat) : Type := (u : Unit := ())
instance Left₂ToBot₂ (n : Nat) [Left₂ n] : Bot₂ n := {}
instance Right₂ToBot₂ (n : Nat) [Right₂ n] : Bot₂ n := {}
instance Top₂ToLeft₂ (n : Nat) [Top₂ n] : Left₂ n := {}
instance Top₂ToRight₂ (n : Nat) [Top₂ n] : Right₂ n := {}
instance Bot₂ToTopSucc (n : Nat) [Bot₂ n] : Top₂ n.succ := {}
class Top (n : Nat) : Type := (u : Unit := ())
instance Top₁ToTop (n : Nat) [Top₁ n] : Top n := {}
instance Top₂ToTop (n : Nat) [Top₂ n] : Top n := {}
#synth Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ
def tst : Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ :=
inferInstance
|
dc913da3bc385859591ca19b533923b91e407ef2 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/topology/homeomorph.lean | fa404d27cd7408d4211543621ad5b815b8450e25 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,229 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import topology.dense_embedding
/-!
# Homeomorphisms
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β :=
{ compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.compact_image],
apply compact_space.compact_univ } }
lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β :=
{ t2 :=
begin
intros x y hxy,
obtain ⟨u, v, hu, hv, hxu, hyv, huv⟩ := t2_separation (h.symm.injective.ne hxy),
refine ⟨h.symm ⁻¹' u, h.symm ⁻¹' v,
h.symm.continuous.is_open_preimage _ hu,
h.symm.continuous.is_open_preimage _ hv,
hxu, hyv, _⟩,
rw [← preimage_inter, huv, preimage_empty],
end }
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
by rw [h.embedding.closure_eq_preimage_closure_image, h.image_preimage]
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.continuous)
(continuous_inr.comp h₂.continuous),
ext x, cases x; refl,
end,
continuous_inv_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous)
(continuous_inr.comp h₂.symm.continuous),
ext x, cases x; refl
end,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
begin
refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm,
{ convert continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd),
ext1 x, cases x; refl, },
{ exact (is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map) }
end
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
..e.to_equiv.image s, }
end homeomorph
|
4a2674cceaa4350ffd897df284a03bd0e92a87e9 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/tactic/lean_core_docs.lean | 0e85f0cfadbf7d4eb3c4c477bce5932b22f35c2c | [
"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 | 22,843 | lean | /-
Copyright (c) 2020 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Bryan Gin-ge Chen, Robert Y. Lewis, Scott Morrison
-/
import tactic.doc_commands
/-!
# Core tactic documentation
This file adds the majority of the interactive tactics from core Lean (i.e. pre-mathlib) to the API documentation.
## TODO
* Make a PR to core changing core docstrings to the docstrings below,
and also changing the docstrings of `cc`, `simp` and `conv` to the ones
already in the API docs.
* SMT tactics are currently not documented.
* `rsimp` and `constructor_matching` are currently not documented.
* `dsimp` deserves better documentation.
-/
add_tactic_doc
{ name := "abstract",
category := doc_category.tactic,
decl_names := [`tactic.interactive.abstract],
tags := ["core", "proof extraction"] }
/-- Proves a goal of the form `s = t` when `s` and `t` are expressions built up out of a binary operation,
and equality can be proved using associativity and commutativity of that operation. -/
add_tactic_doc
{ name := "ac_refl",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ac_refl, `tactic.interactive.ac_reflexivity],
tags := ["core", "lemma application", "finishing"] }
add_tactic_doc
{ name := "all_goals",
category := doc_category.tactic,
decl_names := [`tactic.interactive.all_goals],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "any_goals",
category := doc_category.tactic,
decl_names := [`tactic.interactive.any_goals],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "apply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply],
tags := ["core", "basic", "lemma application"] }
add_tactic_doc
{ name := "apply_auto_param",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_auto_param],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "apply_instance",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_instance],
tags := ["core", "type class"] }
add_tactic_doc
{ name := "apply_opt_param",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_opt_param],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "apply_with",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_with],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "assume",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assume],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "assumption",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assumption],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "assumption'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assumption'],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "async",
category := doc_category.tactic,
decl_names := [`tactic.interactive.async],
tags := ["core", "goal management", "combinator", "proof extraction"] }
/--
`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use
`open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib).
-/
add_tactic_doc
{ name := "by_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.by_cases],
tags := ["core", "basic", "logic", "case bashing"] }
/--
If the target of the main goal is a proposition `p`, `by_contra h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use
`open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib).
-/
add_tactic_doc
{ name := "by_contra / by_contradiction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.by_contra, `tactic.interactive.by_contradiction],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "case",
category := doc_category.tactic,
decl_names := [`tactic.interactive.case],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases],
tags := ["core", "basic", "induction"] }
/--
`cases_matching p` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches the pattern `p`.
`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches one of the given patterns.
`cases_matching* p` is a more efficient and compact version of `focus1 { repeat { cases_matching p } }`.
It is more efficient because the pattern is compiled once.
`casesm` is shorthand for `cases_matching`.
Example: The following tactic destructs all conjunctions and disjunctions in the current context.
```
cases_matching* [_ ∨ _, _ ∧ _]
```
-/
add_tactic_doc
{ name := "cases_matching / casesm",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases_matching, `tactic.interactive.casesm],
tags := ["core", "induction", "context management"] }
/--
`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`
`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`
`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current context.
```
cases_type* or and
```
-/
add_tactic_doc
{ name := "cases_type",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases_type],
tags := ["core", "induction", "context management"] }
add_tactic_doc
{ name := "change",
category := doc_category.tactic,
decl_names := [`tactic.interactive.change],
tags := ["core", "basic", "renaming"] }
add_tactic_doc
{ name := "clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear],
tags := ["core", "context management"] }
/--
Close goals of the form `n ≠ m` when `n` and `m` have type `nat`, `char`, `string`, `int` or `fin sz`,
and they are literals. It also closes goals of the form `n < m`, `n > m`, `n ≤ m` and `n ≥ m` for `nat`.
If the goal is of the form `n = m`, then it tries to close it using reflexivity.
In mathlib, consider using `norm_num` instead for numeric types.
-/
add_tactic_doc
{ name := "comp_val",
category := doc_category.tactic,
decl_names := [`tactic.interactive.comp_val],
tags := ["core", "arithmetic"] }
/--
The `congr` tactic attempts to identify both sides of an equality goal `A = B`,
leaving as new goals the subterms of `A` and `B` which are not definitionally equal.
Example: suppose the goal is `x * f y = g w * f z`. Then `congr` will produce two goals:
`x = g w` and `y = z`.
Note that `congr` can be over-aggressive at times; the `congr'` tactic in mathlib
provides a more refined approach, by taking a parameter that limits the recursion depth.
-/
add_tactic_doc
{ name := "congr",
category := doc_category.tactic,
decl_names := [`tactic.interactive.congr],
tags := ["core", "congruence"] }
add_tactic_doc
{ name := "constructor",
category := doc_category.tactic,
decl_names := [`tactic.interactive.constructor],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "contradiction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.contradiction],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "delta",
category := doc_category.tactic,
decl_names := [`tactic.interactive.delta],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "destruct",
category := doc_category.tactic,
decl_names := [`tactic.interactive.destruct],
tags := ["core", "induction"] }
add_tactic_doc
{ name := "done",
category := doc_category.tactic,
decl_names := [`tactic.interactive.done],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "dsimp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.dsimp],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "dunfold",
category := doc_category.tactic,
decl_names := [`tactic.interactive.dunfold],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "eapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.eapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "econstructor",
category := doc_category.tactic,
decl_names := [`tactic.interactive.econstructor],
tags := ["core", "logic"] }
/--
A variant of `rw` that uses the unifier more aggressively, unfolding semireducible definitions.
-/
add_tactic_doc
{ name := "erewrite / erw",
category := doc_category.tactic,
decl_names := [`tactic.interactive.erewrite, `tactic.interactive.erw],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "exact",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exact],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "exacts",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exacts],
tags := ["core", "finishing"] }
add_tactic_doc
{ name := "exfalso",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exfalso],
tags := ["core", "basic", "logic"] }
/--
`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.
`existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list.
Note: in mathlib, the `use` tactic is an equivalent tactic which sometimes is smarter with
unification.
-/
add_tactic_doc
{ name := "existsi",
category := doc_category.tactic,
decl_names := [`tactic.interactive.existsi],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "fail_if_success",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fail_if_success],
tags := ["core", "testing", "combinator"] }
add_tactic_doc
{ name := "fapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "focus",
category := doc_category.tactic,
decl_names := [`tactic.interactive.focus],
tags := ["core", "goal management", "combinator"] }
add_tactic_doc
{ name := "from",
category := doc_category.tactic,
decl_names := [`tactic.interactive.from],
tags := ["core", "finishing"] }
/--
Apply function extensionality and introduce new hypotheses.
The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to
```
|- ((fun x, ...) = (fun x, ...))
```
The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.
Note also the mathlib tactic `ext`, which applies as many extensionality lemmas as possible.
-/
add_tactic_doc
{ name := "funext",
category := doc_category.tactic,
decl_names := [`tactic.interactive.funext],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "generalize",
category := doc_category.tactic,
decl_names := [`tactic.interactive.generalize],
tags := ["core", "context management"] }
add_tactic_doc
{ name := "guard_hyp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.guard_hyp],
tags := ["core", "testing", "context management"] }
add_tactic_doc
{ name := "guard_target",
category := doc_category.tactic,
decl_names := [`tactic.interactive.guard_target],
tags := ["core", "testing", "goal management"] }
add_tactic_doc
{ name := "have",
category := doc_category.tactic,
decl_names := [`tactic.interactive.have],
tags := ["core", "basic", "context management"] }
add_tactic_doc
{ name := "induction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.induction],
tags := ["core", "basic", "induction"] }
add_tactic_doc
{ name := "injection",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injection],
tags := ["core", "structures", "induction"] }
add_tactic_doc
{ name := "injections",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections],
tags := ["core", "structures", "induction"] }
/--
If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.
If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`.
If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.
The variant `intro z` uses the identifier `z` to name the new hypothesis.
The variant `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.
The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them.
-/
add_tactic_doc
{ name := "intro / intros",
category := doc_category.tactic,
decl_names := [`tactic.interactive.intro, `tactic.interactive.intros],
tags := ["core", "basic", "logic"] }
add_tactic_doc
{ name := "introv",
category := doc_category.tactic,
decl_names := [`tactic.interactive.introv],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "iterate",
category := doc_category.tactic,
decl_names := [`tactic.interactive.iterate],
tags := ["core", "combinator"] }
/--
`left` applies the first constructor when the type of the target is an inductive data type with two constructors.
Similarly, `right` applies the second constructor.
-/
add_tactic_doc
{ name := "left / right",
category := doc_category.tactic,
decl_names := [`tactic.interactive.left, `tactic.interactive.right],
tags := ["core", "basic", "logic"] }
/--
`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
Note the related mathlib tactic `set a := t with h`, which adds the hypothesis `h : a = t` to
the local context and replaces `t` with `a` everywhere it can.
-/
add_tactic_doc
{ name := "let",
category := doc_category.tactic,
decl_names := [`tactic.interactive.let],
tags := ["core", "basic", "logic", "context management"] }
add_tactic_doc
{ name := "mapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.mapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "match_target",
category := doc_category.tactic,
decl_names := [`tactic.interactive.match_target],
tags := ["core", "testing", "goal management"] }
add_tactic_doc
{ name := "refine",
category := doc_category.tactic,
decl_names := [`tactic.interactive.refine],
tags := ["core", "basic", "lemma application"] }
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation,
that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`.
The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.
-/
add_tactic_doc
{ name := "refl / reflexivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.refl, `tactic.interactive.reflexivity],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "rename",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rename],
tags := ["core", "renaming"] }
add_tactic_doc
{ name := "repeat",
category := doc_category.tactic,
decl_names := [`tactic.interactive.repeat],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "revert",
category := doc_category.tactic,
decl_names := [`tactic.interactive.revert],
tags := ["core", "context management", "goal management"] }
/--
`rw e` applies an equation or iff `e` as a rewrite rule to the main goal. If `e` is preceded by
left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined
constant, then the equational lemmas associated with `e` are used. This provides a convenient
way to unfold `e`.
`rw [e₁, ..., eₙ]` applies the given rules sequentially.
`rw e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses
in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify
the target of the goal.
`rewrite` is synonymous with `rw`.
-/
add_tactic_doc
{ name := "rw / rewrite",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rw, `tactic.interactive.rewrite],
tags := ["core", "basic", "rewriting"] }
add_tactic_doc
{ name := "rwa",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rwa],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "show",
category := doc_category.tactic,
decl_names := [`tactic.interactive.show],
tags := ["core", "goal management", "renaming"] }
add_tactic_doc
{ name := "simp_intros",
category := doc_category.tactic,
decl_names := [`tactic.interactive.simp_intros],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "skip",
category := doc_category.tactic,
decl_names := [`tactic.interactive.skip],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "solve1",
category := doc_category.tactic,
decl_names := [`tactic.interactive.solve1],
tags := ["core", "combinator", "goal management"] }
add_tactic_doc
{ name := "sorry / admit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.sorry, `tactic.interactive.admit],
inherit_description_from := `tactic.interactive.sorry,
tags := ["core", "testing", "debugging"] }
add_tactic_doc
{ name := "specialize",
category := doc_category.tactic,
decl_names := [`tactic.interactive.specialize],
tags := ["core", "hypothesis management", "lemma application"] }
add_tactic_doc
{ name := "split",
category := doc_category.tactic,
decl_names := [`tactic.interactive.split],
tags := ["core", "basic", "logic"] }
add_tactic_doc
{ name := "subst",
category := doc_category.tactic,
decl_names := [`tactic.interactive.subst],
tags := ["core", "rewrite"] }
add_tactic_doc
{ name := "subst_vars",
category := doc_category.tactic,
decl_names := [`tactic.interactive.subst_vars],
tags := ["core", "rewrite"] }
add_tactic_doc
{ name := "success_if_fail",
category := doc_category.tactic,
decl_names := [`tactic.interactive.success_if_fail],
tags := ["core", "testing", "combinator"] }
add_tactic_doc
{ name := "suffices",
category := doc_category.tactic,
decl_names := [`tactic.interactive.suffices],
tags := ["core", "basic", "goal management"] }
add_tactic_doc
{ name := "symmetry",
category := doc_category.tactic,
decl_names := [`tactic.interactive.symmetry],
tags := ["core", "basic", "lemma application"] }
add_tactic_doc
{ name := "trace",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "trace_simp_set",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace_simp_set],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "trace_state",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace_state],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "transitivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.transitivity],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "trivial",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trivial],
tags := ["core", "finishing"] }
add_tactic_doc
{ name := "try",
category := doc_category.tactic,
decl_names := [`tactic.interactive.try],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "type_check",
category := doc_category.tactic,
decl_names := [`tactic.interactive.type_check],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "unfold",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold],
tags := ["core", "basic", "rewriting"] }
add_tactic_doc
{ name := "unfold1",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold1],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "unfold_projs",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold_projs],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "with_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.with_cases],
tags := ["core", "combinator"] }
|
9f1371648edf4db4e5b8a7ad4c14d2ac6dd276d2 | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /order/bounds.lean | 0ffe1f6a133c02cf7a8d7ccc6e50b8384a8cc650 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,453 | 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
(Least / Greatest) upper / lower bounds
-/
import order.complete_lattice data.set
open set lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β} {s t : set α}
section preorder
variables [preorder α] [preorder β] {f : α → β}
definition upper_bounds (s : set α) : set α := { x | ∀a ∈ s, a ≤ x }
definition lower_bounds (s : set α) : set α := { x | ∀a ∈ s, x ≤ a }
definition is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
definition is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
definition is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
definition is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
lemma mem_upper_bounds_image (Hf : monotone f) (Ha : a ∈ upper_bounds s) :
f a ∈ upper_bounds (f '' s) :=
bounded_forall_image_of_bounded_forall (assume x H, Hf (Ha _ ‹x ∈ s›))
lemma mem_lower_bounds_image (Hf : monotone f) (Ha : a ∈ lower_bounds s) :
f a ∈ lower_bounds (f '' s) :=
bounded_forall_image_of_bounded_forall (assume x H, Hf (Ha _ ‹x ∈ s›))
lemma is_lub_singleton {a : α} : is_lub {a} a :=
begin
simp [is_lub, is_least, upper_bounds, lower_bounds] {contextual := tt},
exact ⟨assume a' _, le_refl _, assume a' ha', ha' _ rfl⟩
end
lemma is_glb_singleton {a : α} : is_glb {a} a :=
begin
simp [is_glb, is_greatest, upper_bounds, lower_bounds] {contextual := tt},
exact ⟨assume a' _, le_refl _, assume a' ha', ha' _ rfl⟩
end
end preorder
section partial_order
variables [partial_order α]
lemma eq_of_is_least_of_is_least (Ha : is_least s a₁) (Hb : is_least s a₂) : a₁ = a₂ :=
le_antisymm (Ha.right _ Hb.left) (Hb.right _ Ha.left)
lemma is_least_iff_eq_of_is_least (Ha : is_least s a₁) : is_least s a₂ ↔ a₁ = a₂ :=
iff.intro (eq_of_is_least_of_is_least Ha) (assume h, h ▸ Ha)
lemma eq_of_is_greatest_of_is_greatest (Ha : is_greatest s a₁) (Hb : is_greatest s a₂) : a₁ = a₂ :=
le_antisymm (Hb.right _ Ha.left) (Ha.right _ Hb.left)
lemma is_greatest_iff_eq_of_is_greatest (Ha : is_greatest s a₁) : is_greatest s a₂ ↔ a₁ = a₂ :=
iff.intro (eq_of_is_greatest_of_is_greatest Ha) (assume h, h ▸ Ha)
lemma eq_of_is_lub_of_is_lub : is_lub s a₁ → is_lub s a₂ → a₁ = a₂ :=
eq_of_is_least_of_is_least
lemma is_lub_iff_eq_of_is_lub : is_lub s a₁ → (is_lub s a₂ ↔ a₁ = a₂) :=
is_least_iff_eq_of_is_least
lemma eq_of_is_glb_of_is_glb : is_glb s a₁ → is_glb s a₂ → a₁ = a₂ :=
eq_of_is_greatest_of_is_greatest
lemma is_glb_iff_eq_of_is_glb : is_glb s a₁ → (is_glb s a₂ ↔ a₁ = a₂) :=
is_greatest_iff_eq_of_is_greatest
end partial_order
section lattice
lemma is_glb_empty [order_top α] : is_glb ∅ (⊤:α) :=
by simp [is_glb, is_greatest, lower_bounds, upper_bounds]
lemma is_lub_empty [order_bot α] : is_lub ∅ (⊥:α) :=
by simp [is_lub, is_least, lower_bounds, upper_bounds]
lemma is_lub_union_sup [semilattice_sup α] (hs : is_lub s a₁) (ht : is_lub t a₂) :
is_lub (s ∪ t) (a₁ ⊔ a₂) :=
⟨assume c h, h.cases_on (le_sup_left_of_le ∘ hs.left c) (le_sup_right_of_le ∘ ht.left c),
assume c hc, sup_le
(hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩
lemma is_glb_union_inf [semilattice_inf α] (hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
⟨assume c h, h.cases_on (inf_le_left_of_le ∘ hs.left c) (inf_le_right_of_le ∘ ht.left c),
assume c hc, le_inf
(hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩
lemma is_lub_insert_sup [semilattice_sup α] (h : is_lub s a₁) : is_lub (insert a₂ s) (a₂ ⊔ a₁) :=
by rw [insert_eq]; exact is_lub_union_sup is_lub_singleton h
lemma is_lub_iff_sup_eq [semilattice_sup α] : is_lub {a₁, a₂} a ↔ a₂ ⊔ a₁ = a :=
is_lub_iff_eq_of_is_lub $ is_lub_insert_sup $ is_lub_singleton
lemma is_glb_insert_inf [semilattice_inf α] (h : is_glb s a₁) : is_glb (insert a₂ s) (a₂ ⊓ a₁) :=
by rw [insert_eq]; exact is_glb_union_inf is_glb_singleton h
lemma is_glb_iff_inf_eq [semilattice_inf α] : is_glb {a₁, a₂} a ↔ a₂ ⊓ a₁ = a :=
is_glb_iff_eq_of_is_glb $ is_glb_insert_inf $ is_glb_singleton
end lattice
section complete_lattice
variables [complete_lattice α] {f : ι → α}
lemma is_lub_Sup : is_lub s (Sup s) := and.intro (assume x, le_Sup) (assume x, Sup_le)
lemma is_lub_supr : is_lub (range f) (⨆j, f j) :=
have is_lub (range f) (Sup (range f)), from is_lub_Sup,
by rwa [Sup_range] at this
lemma is_lub_iff_supr_eq : is_lub (range f) a ↔ (⨆j, f j) = a := is_lub_iff_eq_of_is_lub is_lub_supr
lemma is_lub_iff_Sup_eq : is_lub s a ↔ Sup s = a := is_lub_iff_eq_of_is_lub is_lub_Sup
lemma is_glb_Inf : is_glb s (Inf s) := and.intro (assume a, Inf_le) (assume a, le_Inf)
lemma is_glb_infi : is_glb (range f) (⨅j, f j) :=
have is_glb (range f) (Inf (range f)), from is_glb_Inf,
by rwa [Inf_range] at this
lemma is_glb_iff_infi_eq : is_glb (range f) a ↔ (⨅j, f j) = a := is_glb_iff_eq_of_is_glb is_glb_infi
lemma is_glb_iff_Inf_eq : is_glb s a ↔ Inf s = a := is_glb_iff_eq_of_is_glb is_glb_Inf
end complete_lattice
|
504823fb2bea5f9064701410ad53ff6d66422ade | bf35a3ed54de6fced25e870a19cf82da937bdc9e | /src/greet_then_find_hyperplane.lean | 4a514dd4c71af59c975dbee9c370e959d747ee3e | [] | no_license | khoek/klean-demo | cd01e703e1333fd6095ea5349986a614b53383f5 | d572f3ee90589854beb66cb7499a99722c454689 | refs/heads/master | 1,585,083,090,000 | 1,533,310,995,000 | 1,533,310,995,000 | 143,000,189 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 414 | lean | import system.extras
import .lib
def dim : ℕ := 2
def a_vects : list (array dim ℕ) := [to_array [1, 2], to_array [4, 5]]
def b_vects : list (array dim ℕ) := [to_array [5, 5], to_array [2, 8]]
meta def main : io unit := do
io.print_ln "a",
extras.greet,
n ← pure (extras.find_separating_hyperplane a_vects b_vects),
io.print_ln "b",
io.print_ln (array.to_list n.1),
io.print_ln n.2 |
bab3dc50b9f09f9e3bc3fd2d29d3718ca3b5e08a | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/634d.lean | 2ce05ff37bee9da37ab82a83cc75b90568224ad4 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 418 | lean | section
universe l
definition A {n : ℕ} (t : Sort l) := t
check A
check _root_.A.{1}
set_option pp.universes true
check A
check _root_.A.{1}
end
section
universe l
parameters {B : Sort l}
definition P {n : ℕ} (b : B) := b
check P
check @_root_.P.{1} nat
set_option pp.universes true
check P
check _root_.P.{1}
set_option pp.implicit true
check @P 2
check @_root_.P.{1} nat
end
|
8c1a6041ff4fdf9a6512f66f1699586f5fb5769f | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/vector/simplify_eq.lean | 086b9f32c85b3ae2d56b6f3411602c37788628e7 | [
"Apache-2.0"
] | permissive | digama0/lean-protocol-support | eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59 | cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda | refs/heads/master | 1,625,421,450,627 | 1,506,035,462,000 | 1,506,035,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,422 | lean | /- Defines basic lemmas for equality -/
import data.vector
import ..list.simplify_eq
import ..list.take_drop_lemmas
import ..subtype
universe variables u
namespace vector
variable {α : Type u}
variable {n : ℕ}
local infix `++`:65 := vector.append
theorem cons_eq_cons {n : ℕ} (a b : α) (x y : vector α n)
: a :: x = b :: y ↔ a = b ∧ x = y :=
begin
apply iff.intro,
{
-- Reduce to list primitives
cases x with xv xp,
cases y with yv yp,
simp [ vector.cons ],
-- Simplify equalities
simp [ @subtype.mk_eq_mk (list α) (λ (l : list α), @list.length α l = nat.succ n)
],
cc,
},
{
intro h,
rw [and.left h, and.right h],
},
end
@[simp]
theorem append_eq_append {m n : ℕ} (a b : vector α m) (x y : vector α n)
: a ++ x = b ++ y ↔ a = b ∧ x = y :=
begin
apply iff.intro,
{ -- Reduce intro list functions
cases a with av ap,
cases b with bv bp,
cases x with xv xp,
cases y with yv yp,
unfold vector.append,
have h : av^.length = bv^.length, { simp [ap, bp] },
-- Simplify hypothesis into conjunction av = bv ∧ xv = yv
intro p,
have q := congr_arg subtype.val p,
simp [list.append_eq_take_drop, h, nat.sub_self] at q,
-- Prove equalities
simp [and.left q, and.right q],
},
{ -- Prove a = b & x = y -> a +++ x = b +++ y
intro h,
rw [and.left h, and.right h],
},
end
end vector
|
6a45251b54a49fd9c300ce928970f66c8e241e80 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/geometry/manifold/charted_space.lean | 9d562746d52521c70a3c5df5de3c3aee484e470b | [
"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 | 51,400 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.local_homeomorph
/-!
# Charted spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A smooth manifold is a topological space `M` locally modelled on a euclidean space (or a euclidean
half-space for manifolds with boundaries, or an infinite dimensional vector space for more general
notions of manifolds), i.e., the manifold is covered by open subsets on which there are local
homeomorphisms (the charts) going to a model space `H`, and the changes of charts should be smooth
maps.
In this file, we introduce a general framework describing these notions, where the model space is an
arbitrary topological space. We avoid the word *manifold*, which should be reserved for the
situation where the model space is a (subset of a) vector space, and use the terminology
*charted space* instead.
If the changes of charts satisfy some additional property (for instance if they are smooth), then
`M` inherits additional structure (it makes sense to talk about smooth manifolds). There are
therefore two different ingredients in a charted space:
* the set of charts, which is data
* the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop.
We separate these two parts in the definition: the charted space structure is just the set of
charts, and then the different smoothness requirements (smooth manifold, orientable manifold,
contact manifold, and so on) are additional properties of these charts. These properties are
formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable
under composition and inverse, to which the change of coordinates should belong.
## Main definitions
* `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition,
inverse and restriction (ex: local diffeos).
* `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H`
* `charted_space H M` : charted space structure on `M` modelled on `H`, given by an atlas of
local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class.
* `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a charted space
modelled on `H`, require that all coordinate changes belong to `G`. This is a type class.
* `atlas H M` : when `M` is a charted space modelled on `H`, the atlas of this charted
space structure, i.e., the set of charts.
* `G.maximal_atlas M` : when `M` is a charted space modelled on `H` and admitting `G` as a
structure groupoid, one can consider all the local homeomorphisms from `M` to `H` such that
changing coordinate from any chart to them belongs to `G`. This is a larger atlas, called the
maximal atlas (for the groupoid `G`).
* `structomorph G M M'` : the type of diffeomorphisms between the charted spaces `M` and `M'` for
the groupoid `G`. We avoid the word diffeomorphism, keeping it for the smooth category.
As a basic example, we give the instance
`instance charted_space_model_space (H : Type*) [topological_space H] : charted_space H H`
saying that a topological space is a charted space over itself, with the identity as unique chart.
This charted space structure is compatible with any groupoid.
Additional useful definitions:
* `pregroupoid H` : a subset of local mas of `H` stable under composition and
restriction, but not inverse (ex: smooth maps)
* `groupoid_of_pregroupoid` : construct a groupoid from a pregroupoid, by requiring that a map and
its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps)
* `chart_at H x` is a preferred chart at `x : M` when `M` has a charted space structure modelled on
`H`.
* `G.compatible he he'` states that, for any two charts `e` and `e'` in the atlas, the composition
of `e.symm` and `e'` belongs to the groupoid `G` when `M` admits `G` as a structure groupoid.
* `G.compatible_of_mem_maximal_atlas he he'` states that, for any two charts `e` and `e'` in the
maximal atlas associated to the groupoid `G`, the composition of `e.symm` and `e'` belongs to the
`G` if `M` admits `G` as a structure groupoid.
* `charted_space_core.to_charted_space`: consider a space without a topology, but endowed with a set
of charts (which are local equivs) for which the change of coordinates are local homeos. Then
one can construct a topology on the space for which the charts become local homeos, defining
a genuine charted space structure.
## Implementation notes
The atlas in a charted space is *not* a maximal atlas in general: the notion of maximality depends
on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current
formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas
defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms
between `M` and `M'` do *not* induce a bijection between the atlases of `M` and `M'`: the
definition is only that, read in charts, the structomorphism locally belongs to the groupoid under
consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas).
A consequence is that the invariance under structomorphisms of properties defined in terms of the
atlas is not obvious in general, and could require some work in theory (amounting to the fact
that these properties only depend on the maximal atlas, for instance). In practice, this does not
create any real difficulty.
We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the
model space is a half space.
Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and
sometimes as spaces with an atlas from which a topology is deduced. We use the former approach:
otherwise, there would be an instance from manifolds to topological spaces, which means that any
instance search for topological spaces would try to find manifold structures involving a yet
unknown model space, leading to problems. However, we also introduce the latter approach,
through a structure `charted_space_core` making it possible to construct a topology out of a set of
local equivs with compatibility conditions (but we do not register it as an instance).
In the definition of a charted space, the model space is written as an explicit parameter as there
can be several model spaces for a given topological space. For instance, a complex manifold
(modelled over `ℂ^n`) will also be seen sometimes as a real manifold modelled over `ℝ^(2n)`.
## Notations
In the locale `manifold`, we denote the composition of local homeomorphisms with `≫ₕ`, and the
composition of local equivs with `≫`.
-/
noncomputable theory
open_locale classical topology
open filter
universes u
variables {H : Type u} {H' : Type*} {M : Type*} {M' : Type*} {M'' : Type*}
/- Notational shortcut for the composition of local homeomorphisms and local equivs, i.e.,
`local_homeomorph.trans` and `local_equiv.trans`.
Note that, as is usual for equivs, the composition is from left to right, hence the direction of
the arrow. -/
localized "infixr (name := local_homeomorph.trans)
` ≫ₕ `:100 := local_homeomorph.trans" in manifold
localized "infixr (name := local_equiv.trans)
` ≫ `:100 := local_equiv.trans" in manifold
open set local_homeomorph
/-! ### Structure groupoids-/
section groupoid
/-! One could add to the definition of a structure groupoid the fact that the restriction of an
element of the groupoid to any open set still belongs to the groupoid.
(This is in Kobayashi-Nomizu.)
I am not sure I want this, for instance on `H × E` where `E` is a vector space, and the groupoid is
made of functions respecting the fibers and linear in the fibers (so that a charted space over this
groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always
defined on sets of the form `s × E`. There is a typeclass `closed_under_restriction` for groupoids
which have the restriction property.
The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid
around each point in its domain of definition, then it belongs to the groupoid. Without this
requirement, the composition of structomorphisms does not have to be a structomorphism. Note that
this implies that a local homeomorphism with empty source belongs to any structure groupoid, as
it trivially satisfies this condition.
There is also a technical point, related to the fact that a local homeomorphism is by definition a
global map which is a homeomorphism when restricted to its source subset (and its values outside
of the source are not relevant). Therefore, we also require that being a member of the groupoid only
depends on the values on the source.
We use primes in the structure names as we will reformulate them below (without primes) using a
`has_mem` instance, writing `e ∈ G` instead of `e ∈ G.members`.
-/
/-- A structure groupoid is a set of local homeomorphisms of a topological space stable under
composition and inverse. They appear in the definition of the smoothness class of a manifold. -/
structure structure_groupoid (H : Type u) [topological_space H] :=
(members : set (local_homeomorph H H))
(trans' : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members)
(symm' : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members)
(id_mem' : local_homeomorph.refl H ∈ members)
(locality' : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧
x ∈ s ∧ e.restr s ∈ members) → e ∈ members)
(eq_on_source' : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members)
variable [topological_space H]
instance : has_mem (local_homeomorph H H) (structure_groupoid H) :=
⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩
lemma structure_groupoid.trans (G : structure_groupoid H) {e e' : local_homeomorph H H}
(he : e ∈ G) (he' : e' ∈ G) : e ≫ₕ e' ∈ G :=
G.trans' e e' he he'
lemma structure_groupoid.symm (G : structure_groupoid H) {e : local_homeomorph H H} (he : e ∈ G) :
e.symm ∈ G :=
G.symm' e he
lemma structure_groupoid.id_mem (G : structure_groupoid H) :
local_homeomorph.refl H ∈ G :=
G.id_mem'
lemma structure_groupoid.locality (G : structure_groupoid H) {e : local_homeomorph H H}
(h : ∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ G) :
e ∈ G :=
G.locality' e h
lemma structure_groupoid.eq_on_source (G : structure_groupoid H) {e e' : local_homeomorph H H}
(he : e ∈ G) (h : e' ≈ e) : e' ∈ G :=
G.eq_on_source' e e' he h
/-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/
instance structure_groupoid.partial_order : partial_order (structure_groupoid H) :=
partial_order.lift structure_groupoid.members
(λa b h, by { cases a, cases b, dsimp at h, induction h, refl })
lemma structure_groupoid.le_iff {G₁ G₂ : structure_groupoid H} :
G₁ ≤ G₂ ↔ ∀ e, e ∈ G₁ → e ∈ G₂ :=
iff.rfl
/-- The trivial groupoid, containing only the identity (and maps with empty source, as this is
necessary from the definition) -/
def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H :=
{ members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅},
trans' := λe e' he he', begin
cases he; simp at he he',
{ simpa only [he, refl_trans]},
{ have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _,
rw he at this,
have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := eq_bot_iff.2 this,
exact (mem_union _ _ _).2 (or.inr this) },
end,
symm' := λe he, begin
cases (mem_union _ _ _).1 he with E E,
{ simp [mem_singleton_iff.mp E] },
{ right,
simpa only [e.to_local_equiv.image_source_eq_target.symm] with mfld_simps using E},
end,
id_mem' := mem_union_left _ rfl,
locality' := λe he, begin
cases e.source.eq_empty_or_nonempty with h h,
{ right, exact h },
{ left,
rcases h with ⟨x, hx⟩,
rcases he x hx with ⟨s, open_s, xs, hs⟩,
have x's : x ∈ (e.restr s).source,
{ rw [restr_source, open_s.interior_eq],
exact ⟨hx, xs⟩ },
cases hs,
{ replace hs : local_homeomorph.restr e s = local_homeomorph.refl H,
by simpa only using hs,
have : (e.restr s).source = univ, by { rw hs, simp },
change (e.to_local_equiv).source ∩ interior s = univ at this,
have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ },
have : s = univ, by rwa [open_s.interior_eq, univ_subset_iff] at this,
simpa only [this, restr_univ] using hs },
{ exfalso,
rw mem_set_of_eq at hs,
rwa hs at x's } },
end,
eq_on_source' := λe e' he he'e, begin
cases he,
{ left,
have : e = e',
{ refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _;
rw set.mem_singleton_iff.1 he ; refl },
rwa ← this },
{ right,
change (e.to_local_equiv).source = ∅ at he,
rwa [set.mem_set_of_eq, he'e.source_eq] }
end }
/-- Every structure groupoid contains the identity groupoid -/
instance : order_bot (structure_groupoid H) :=
{ bot := id_groupoid H,
bot_le := begin
assume u f hf,
change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf,
simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf,
cases hf,
{ rw hf,
apply u.id_mem },
{ apply u.locality,
assume x hx,
rw [hf, mem_empty_iff_false] at hx,
exact hx.elim }
end }
instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) :=
⟨id_groupoid H⟩
/-- To construct a groupoid, one may consider classes of local homeos such that both the function
and its inverse have some property. If this property is stable under composition,
one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the
groupoid of smooth functions with smooth inverses as an application. -/
structure pregroupoid (H : Type*) [topological_space H] :=
(property : (H → H) → (set H) → Prop)
(comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v)
→ property (g ∘ f) (u ∩ f ⁻¹' v))
(id_mem : property id univ)
(locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u)
(congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u)
/-- Construct a groupoid of local homeos for which the map and its inverse have some property,
from a pregroupoid asserting that this property is stable under composition. -/
def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H :=
{ members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target},
trans' := λe e' he he', begin
split,
{ apply PG.comp he.1 he'.1 e.open_source e'.open_source,
apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source },
{ apply PG.comp he'.2 he.2 e'.open_target e.open_target,
apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target }
end,
symm' := λe he, ⟨he.2, he.1⟩,
id_mem' := ⟨PG.id_mem, PG.id_mem⟩,
locality' := λe he, begin
split,
{ apply PG.locality e.open_source (λx xu, _),
rcases he x xu with ⟨s, s_open, xs, hs⟩,
refine ⟨s, s_open, xs, _⟩,
convert hs.1 using 1,
dsimp [local_homeomorph.restr], rw s_open.interior_eq },
{ apply PG.locality e.open_target (λx xu, _),
rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩,
refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩,
{ exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open },
{ rw [← inter_assoc, inter_self],
convert hs.2 using 1,
dsimp [local_homeomorph.restr], rw s_open.interior_eq } },
end,
eq_on_source' := λe e' he ee', begin
split,
{ apply PG.congr e'.open_source ee'.2,
simp only [ee'.1, he.1] },
{ have A := ee'.symm',
apply PG.congr e'.symm.open_source A.2,
convert he.2,
rw A.1,
refl }
end }
lemma mem_groupoid_of_pregroupoid {PG : pregroupoid H} {e : local_homeomorph H H} :
e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target :=
iff.rfl
lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H)
(h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid :=
begin
refine structure_groupoid.le_iff.2 (λ e he, _),
rw mem_groupoid_of_pregroupoid at he ⊢,
exact ⟨h _ _ he.1, h _ _ he.2⟩
end
lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H}
(he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source :=
begin
rw ← he'.1,
exact PG.congr e.open_source he'.eq_on.symm he,
end
/-- The pregroupoid of all local maps on a topological space `H` -/
@[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H :=
{ property := λf s, true,
comp := λf g u v hf hg hu hv huv, trivial,
id_mem := trivial,
locality := λf u u_open h, trivial,
congr := λf g u u_open hcongr hf, trivial }
instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) :=
⟨continuous_pregroupoid H⟩
/-- The groupoid of all local homeomorphisms on a topological space `H` -/
def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H :=
pregroupoid.groupoid (continuous_pregroupoid H)
/-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/
instance : order_top (structure_groupoid H) :=
{ top := continuous_groupoid H,
le_top := λ u f hf, by { split; exact dec_trivial } }
/-- A groupoid is closed under restriction if it contains all restrictions of its element local
homeomorphisms to open subsets of the source. -/
class closed_under_restriction (G : structure_groupoid H) : Prop :=
(closed_under_restriction : ∀ {e : local_homeomorph H H}, e ∈ G → ∀ (s : set H), is_open s →
e.restr s ∈ G)
lemma closed_under_restriction' {G : structure_groupoid H} [closed_under_restriction G]
{e : local_homeomorph H H} (he : e ∈ G) {s : set H} (hs : is_open s) :
e.restr s ∈ G :=
closed_under_restriction.closed_under_restriction he s hs
/-- The trivial restriction-closed groupoid, containing only local homeomorphisms equivalent to the
restriction of the identity to the various open subsets. -/
def id_restr_groupoid : structure_groupoid H :=
{ members := {e | ∃ {s : set H} (h : is_open s), e ≈ local_homeomorph.of_set s h},
trans' := begin
rintros e e' ⟨s, hs, hse⟩ ⟨s', hs', hse'⟩,
refine ⟨s ∩ s', is_open.inter hs hs', _⟩,
have := local_homeomorph.eq_on_source.trans' hse hse',
rwa local_homeomorph.of_set_trans_of_set at this,
end,
symm' := begin
rintros e ⟨s, hs, hse⟩,
refine ⟨s, hs, _⟩,
rw [← of_set_symm],
exact local_homeomorph.eq_on_source.symm' hse,
end,
id_mem' := ⟨univ, is_open_univ, by simp only with mfld_simps⟩,
locality' := begin
intros e h,
refine ⟨e.source, e.open_source, by simp only with mfld_simps, _⟩,
intros x hx,
rcases h x hx with ⟨s, hs, hxs, s', hs', hes'⟩,
have hes : x ∈ (e.restr s).source,
{ rw e.restr_source, refine ⟨hx, _⟩,
rw hs.interior_eq, exact hxs },
simpa only with mfld_simps using local_homeomorph.eq_on_source.eq_on hes' hes,
end,
eq_on_source' := begin
rintros e e' ⟨s, hs, hse⟩ hee',
exact ⟨s, hs, setoid.trans hee' hse⟩,
end }
lemma id_restr_groupoid_mem {s : set H} (hs : is_open s) :
of_set s hs ∈ @id_restr_groupoid H _ := ⟨s, hs, by refl⟩
/-- The trivial restriction-closed groupoid is indeed `closed_under_restriction`. -/
instance closed_under_restriction_id_restr_groupoid :
closed_under_restriction (@id_restr_groupoid H _) :=
⟨ begin
rintros e ⟨s', hs', he⟩ s hs,
use [s' ∩ s, is_open.inter hs' hs],
refine setoid.trans (local_homeomorph.eq_on_source.restr he s) _,
exact ⟨by simp only [hs.interior_eq] with mfld_simps, by simp only with mfld_simps⟩,
end ⟩
/-- A groupoid is closed under restriction if and only if it contains the trivial restriction-closed
groupoid. -/
lemma closed_under_restriction_iff_id_le (G : structure_groupoid H) :
closed_under_restriction G ↔ id_restr_groupoid ≤ G :=
begin
split,
{ introsI _i,
apply structure_groupoid.le_iff.mpr,
rintros e ⟨s, hs, hes⟩,
refine G.eq_on_source _ hes,
convert closed_under_restriction' G.id_mem hs,
change s = _ ∩ _,
rw hs.interior_eq,
simp only with mfld_simps },
{ intros h,
split,
intros e he s hs,
rw ← of_set_trans (e : local_homeomorph H H) hs,
refine G.trans _ he,
apply structure_groupoid.le_iff.mp h,
exact id_restr_groupoid_mem hs },
end
/-- The groupoid of all local homeomorphisms on a topological space `H` is closed under restriction.
-/
instance : closed_under_restriction (continuous_groupoid H) :=
(closed_under_restriction_iff_id_le _).mpr (by convert le_top)
end groupoid
/-! ### Charted spaces -/
/-- A charted space is a topological space endowed with an atlas, i.e., a set of local
homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts
cover the whole space. We express the covering property by chosing for each `x` a member
`chart_at H x` of the atlas containing `x` in its source: in the smooth case, this is convenient to
construct the tangent bundle in an efficient way.
The model space is written as an explicit parameter as there can be several model spaces for a
given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen
sometimes as a real manifold over `ℝ^(2n)`.
-/
@[ext]
class charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] :=
(atlas [] : set (local_homeomorph M H))
(chart_at [] : M → local_homeomorph M H)
(mem_chart_source [] : ∀x, x ∈ (chart_at x).source)
(chart_mem_atlas [] : ∀x, chart_at x ∈ atlas)
export charted_space
attribute [simp, mfld_simps] mem_chart_source chart_mem_atlas
section charted_space
/-- Any space is a charted_space modelled over itself, by just using the identity chart -/
instance charted_space_self (H : Type*) [topological_space H] : charted_space H H :=
{ atlas := {local_homeomorph.refl H},
chart_at := λx, local_homeomorph.refl H,
mem_chart_source := λx, mem_univ x,
chart_mem_atlas := λx, mem_singleton _ }
/-- In the trivial charted_space structure of a space modelled over itself through the identity, the
atlas members are just the identity -/
@[simp, mfld_simps] lemma charted_space_self_atlas
{H : Type*} [topological_space H] {e : local_homeomorph H H} :
e ∈ atlas H H ↔ e = local_homeomorph.refl H :=
by simp [atlas, charted_space.atlas]
/-- In the model space, chart_at is always the identity -/
lemma chart_at_self_eq {H : Type*} [topological_space H] {x : H} :
chart_at H x = local_homeomorph.refl H :=
by simpa using chart_mem_atlas H x
section
variables (H) [topological_space H] [topological_space M] [charted_space H M]
lemma mem_chart_target (x : M) : chart_at H x x ∈ (chart_at H x).target :=
(chart_at H x).map_source (mem_chart_source _ _)
lemma chart_source_mem_nhds (x : M) : (chart_at H x).source ∈ 𝓝 x :=
(chart_at H x).open_source.mem_nhds $ mem_chart_source H x
lemma chart_target_mem_nhds (x : M) : (chart_at H x).target ∈ 𝓝 (chart_at H x x) :=
(chart_at H x).open_target.mem_nhds $ mem_chart_target H x
/-- `achart H x` is the chart at `x`, considered as an element of the atlas.
Especially useful for working with `basic_smooth_vector_bundle_core` -/
def achart (x : M) : atlas H M := ⟨chart_at H x, chart_mem_atlas H x⟩
lemma achart_def (x : M) : achart H x = ⟨chart_at H x, chart_mem_atlas H x⟩ := rfl
@[simp, mfld_simps]
lemma coe_achart (x : M) : (achart H x : local_homeomorph M H) = chart_at H x := rfl
@[simp, mfld_simps]
lemma achart_val (x : M) : (achart H x).1 = chart_at H x := rfl
lemma mem_achart_source (x : M) : x ∈ (achart H x).1.source :=
mem_chart_source H x
open topological_space
lemma charted_space.second_countable_of_countable_cover [second_countable_topology H]
{s : set M} (hs : (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ)
(hsc : s.countable) :
second_countable_topology M :=
begin
haveI : ∀ x : M, second_countable_topology (chart_at H x).source :=
λ x, (chart_at H x).second_countable_topology_source,
haveI := hsc.to_encodable,
rw bUnion_eq_Union at hs,
exact second_countable_topology_of_countable_cover (λ x : s, (chart_at H (x : M)).open_source) hs
end
variable (M)
lemma charted_space.second_countable_of_sigma_compact [second_countable_topology H]
[sigma_compact_space M] :
second_countable_topology M :=
begin
obtain ⟨s, hsc, hsU⟩ : ∃ s, set.countable s ∧ (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ :=
countable_cover_nhds_of_sigma_compact (λ x : M, chart_source_mem_nhds H x),
exact charted_space.second_countable_of_countable_cover H hsU hsc
end
/-- If a topological space admits an atlas with locally compact charts, then the space itself
is locally compact. -/
lemma charted_space.locally_compact [locally_compact_space H] : locally_compact_space M :=
begin
have : ∀ (x : M), (𝓝 x).has_basis
(λ s, s ∈ 𝓝 (chart_at H x x) ∧ is_compact s ∧ s ⊆ (chart_at H x).target)
(λ s, (chart_at H x).symm '' s),
{ intro x,
rw [← (chart_at H x).symm_map_nhds_eq (mem_chart_source H x)],
exact ((compact_basis_nhds (chart_at H x x)).has_basis_self_subset
(chart_target_mem_nhds H x)).map _ },
refine locally_compact_space_of_has_basis this _,
rintro x s ⟨h₁, h₂, h₃⟩,
exact h₂.image_of_continuous_on ((chart_at H x).continuous_on_symm.mono h₃)
end
/-- If a topological space admits an atlas with locally connected charts, then the space itself is
locally connected. -/
lemma charted_space.locally_connected_space [locally_connected_space H] :
locally_connected_space M :=
begin
let E : M → local_homeomorph M H := chart_at H,
refine locally_connected_space_of_connected_bases
(λ x s, (E x).symm '' s)
(λ x s, (is_open s ∧ E x x ∈ s ∧ is_connected s) ∧ s ⊆ (E x).target) _ _,
{ intros x,
simpa only [local_homeomorph.symm_map_nhds_eq, mem_chart_source] using
((locally_connected_space.open_connected_basis (E x x)).restrict_subset
((E x).open_target.mem_nhds (mem_chart_target H x))).map (E x).symm },
{ rintros x s ⟨⟨-, -, hsconn⟩, hssubset⟩,
exact hsconn.is_preconnected.image _ ((E x).continuous_on_symm.mono hssubset) },
end
/-- If `M` is modelled on `H'` and `H'` is itself modelled on `H`, then we can consider `M` as being
modelled on `H`. -/
def charted_space.comp (H : Type*) [topological_space H] (H' : Type*) [topological_space H']
(M : Type*) [topological_space M] [charted_space H H'] [charted_space H' M] :
charted_space H M :=
{ atlas := image2 local_homeomorph.trans (atlas H' M) (atlas H H'),
chart_at := λ p : M, (chart_at H' p).trans (chart_at H (chart_at H' p p)),
mem_chart_source := λ p, by simp only with mfld_simps,
chart_mem_atlas :=
λ p, ⟨chart_at H' p, chart_at H _, chart_mem_atlas H' p, chart_mem_atlas H _, rfl⟩ }
end
/-- For technical reasons we introduce two type tags:
* `model_prod H H'` is the same as `H × H'`;
* `model_pi H` is the same as `Π i, H i`, where `H : ι → Type*` and `ι` is a finite type.
In both cases the reason is the same, so we explain it only in the case of the product. A charted
space `M` with model `H` is a set of local charts from `M` to `H` covering the space. Every space is
registered as a charted space over itself, using the only chart `id`, in `manifold_model_space`. You
can also define a product of charted space `M` and `M'` (with model space `H × H'`) by taking the
products of the charts. Now, on `H × H'`, there are two charted space structures with model space
`H × H'` itself, the one coming from `manifold_model_space`, and the one coming from the product of
the two `manifold_model_space` on each component. They are equal, but not defeq (because the product
of `id` and `id` is not defeq to `id`), which is bad as we know. This expedient of renaming `H × H'`
solves this problem. -/
library_note "Manifold type tags"
/-- Same thing as `H × H'` We introduce it for technical reasons,
see note [Manifold type tags]. -/
def model_prod (H : Type*) (H' : Type*) := H × H'
/-- Same thing as `Π i, H i` We introduce it for technical reasons,
see note [Manifold type tags]. -/
def model_pi {ι : Type*} (H : ι → Type*) := Π i, H i
section
local attribute [reducible] model_prod
instance model_prod_inhabited [inhabited H] [inhabited H'] :
inhabited (model_prod H H') :=
prod.inhabited
instance (H : Type*) [topological_space H] (H' : Type*) [topological_space H'] :
topological_space (model_prod H H') :=
prod.topological_space
/- Next lemma shows up often when dealing with derivatives, register it as simp. -/
@[simp, mfld_simps] lemma model_prod_range_prod_id
{H : Type*} {H' : Type*} {α : Type*} (f : H → α) :
range (λ (p : model_prod H H'), (f p.1, p.2)) = range f ×ˢ (univ : set H') :=
by rw prod_range_univ_eq
end
section
variables {ι : Type*} {Hi : ι → Type*}
instance model_pi_inhabited [Π i, inhabited (Hi i)] :
inhabited (model_pi Hi) :=
pi.inhabited _
instance [Π i, topological_space (Hi i)] :
topological_space (model_pi Hi) :=
Pi.topological_space
end
/-- The product of two charted spaces is naturally a charted space, with the canonical
construction of the atlas of product maps. -/
instance prod_charted_space (H : Type*) [topological_space H]
(M : Type*) [topological_space M] [charted_space H M]
(H' : Type*) [topological_space H']
(M' : Type*) [topological_space M'] [charted_space H' M'] :
charted_space (model_prod H H') (M × M') :=
{ atlas := image2 local_homeomorph.prod (atlas H M) (atlas H' M'),
chart_at := λ x : M × M', (chart_at H x.1).prod (chart_at H' x.2),
mem_chart_source := λ x, ⟨mem_chart_source _ _, mem_chart_source _ _⟩,
chart_mem_atlas := λ x, mem_image2_of_mem (chart_mem_atlas _ _) (chart_mem_atlas _ _) }
section prod_charted_space
variables [topological_space H] [topological_space M] [charted_space H M]
[topological_space H'] [topological_space M'] [charted_space H' M'] {x : M×M'}
@[simp, mfld_simps] lemma prod_charted_space_chart_at :
(chart_at (model_prod H H') x) = (chart_at H x.fst).prod (chart_at H' x.snd) := rfl
lemma charted_space_self_prod : prod_charted_space H H H' H' = charted_space_self (H × H') :=
by { ext1, { simp [prod_charted_space, atlas] }, { ext1, simp [chart_at_self_eq], refl } }
end prod_charted_space
/-- The product of a finite family of charted spaces is naturally a charted space, with the
canonical construction of the atlas of finite product maps. -/
instance pi_charted_space {ι : Type*} [fintype ι] (H : ι → Type*) [Π i, topological_space (H i)]
(M : ι → Type*) [Π i, topological_space (M i)] [Π i, charted_space (H i) (M i)] :
charted_space (model_pi H) (Π i, M i) :=
{ atlas := local_homeomorph.pi '' (set.pi univ $ λ i, atlas (H i) (M i)),
chart_at := λ f, local_homeomorph.pi $ λ i, chart_at (H i) (f i),
mem_chart_source := λ f i hi, mem_chart_source (H i) (f i),
chart_mem_atlas := λ f, mem_image_of_mem _ $ λ i hi, chart_mem_atlas (H i) (f i) }
@[simp, mfld_simps] lemma pi_charted_space_chart_at {ι : Type*} [fintype ι] (H : ι → Type*)
[Π i, topological_space (H i)] (M : ι → Type*) [Π i, topological_space (M i)]
[Π i, charted_space (H i) (M i)] (f : Π i, M i) :
chart_at (model_pi H) f = local_homeomorph.pi (λ i, chart_at (H i) (f i)) := rfl
end charted_space
/-! ### Constructing a topology from an atlas -/
/-- Sometimes, one may want to construct a charted space structure on a space which does not yet
have a topological structure, where the topology would come from the charts. For this, one needs
charts that are only local equivs, and continuity properties for their composition.
This is formalised in `charted_space_core`. -/
@[nolint has_nonempty_instance]
structure charted_space_core (H : Type*) [topological_space H] (M : Type*) :=
(atlas : set (local_equiv M H))
(chart_at : M → local_equiv M H)
(mem_chart_source : ∀x, x ∈ (chart_at x).source)
(chart_mem_atlas : ∀x, chart_at x ∈ atlas)
(open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source)
(continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas →
continuous_on (e.symm.trans e') (e.symm.trans e').source)
namespace charted_space_core
variables [topological_space H] (c : charted_space_core H M) {e : local_equiv M H}
/-- Topology generated by a set of charts on a Type. -/
protected def to_topological_space : topological_space M :=
topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas)
(s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source}
lemma open_source' (he : e ∈ c.atlas) : is_open[c.to_topological_space] e.source :=
begin
apply topological_space.generate_open.basic,
simp only [exists_prop, mem_Union, mem_singleton_iff],
refine ⟨e, he, univ, is_open_univ, _⟩,
simp only [set.univ_inter, set.preimage_univ]
end
lemma open_target (he : e ∈ c.atlas) : is_open e.target :=
begin
have E : e.target ∩ e.symm ⁻¹' e.source = e.target :=
subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx,
local_equiv.target_subset_preimage_source _ hx⟩),
simpa [local_equiv.trans_source, E] using c.open_source e e he he
end
/-- An element of the atlas in a charted space without topology becomes a local homeomorphism
for the topology constructed from this atlas. The `local_homeomorph` version is given in this
definition. -/
protected def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) :
@local_homeomorph M H c.to_topological_space _ :=
{ open_source := by convert c.open_source' he,
open_target := by convert c.open_target he,
continuous_to_fun := begin
letI : topological_space M := c.to_topological_space,
rw continuous_on_open_iff (c.open_source' he),
assume s s_open,
rw inter_comm,
apply topological_space.generate_open.basic,
simp only [exists_prop, mem_Union, mem_singleton_iff],
exact ⟨e, he, ⟨s, s_open, rfl⟩⟩
end,
continuous_inv_fun := begin
letI : topological_space M := c.to_topological_space,
apply continuous_on_open_of_generate_from (c.open_target he),
assume t ht,
simp only [exists_prop, mem_Union, mem_singleton_iff] at ht,
rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩,
rw ts,
let f := e.symm.trans e',
have : is_open (f ⁻¹' s ∩ f.source),
by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1
(c.continuous_to_fun e e' he e'_atlas) s s_open,
have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) =
e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source),
by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ },
simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this
end,
..e }
/-- Given a charted space without topology, endow it with a genuine charted space structure with
respect to the topology constructed from the atlas. -/
def to_charted_space : @charted_space H _ M c.to_topological_space :=
{ atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he},
chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x),
mem_chart_source := λx, c.mem_chart_source x,
chart_mem_atlas := λx, begin
simp only [mem_Union, mem_singleton_iff],
exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩,
end }
end charted_space_core
/-! ### Charted space with a given structure groupoid -/
section has_groupoid
variables [topological_space H] [topological_space M] [charted_space H M]
/-- A charted space has an atlas in a groupoid `G` if the change of coordinates belong to the
groupoid -/
class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M]
[charted_space H M] (G : structure_groupoid H) : Prop :=
(compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G)
/-- Reformulate in the `structure_groupoid` namespace the compatibility condition of charts in a
charted space admitting a structure groupoid, to make it more easily accessible with dot
notation. -/
lemma structure_groupoid.compatible {H : Type*} [topological_space H] (G : structure_groupoid H)
{M : Type*} [topological_space M] [charted_space H M] [has_groupoid M G]
{e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) :
e.symm ≫ₕ e' ∈ G :=
has_groupoid.compatible G he he'
lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) :
has_groupoid M G₂ :=
⟨λ e e' he he', hle (h.compatible he he')⟩
lemma has_groupoid_of_pregroupoid (PG : pregroupoid H)
(h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M
→ PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) :
has_groupoid M (PG.groupoid) :=
⟨assume e e' he he', mem_groupoid_of_pregroupoid.mpr ⟨h he he', h he' he⟩⟩
/-- The trivial charted space structure on the model space is compatible with any groupoid -/
instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) :
has_groupoid H G :=
{ compatible := λe e' he he', begin
replace he : e ∈ atlas H H := he,
replace he' : e' ∈ atlas H H := he',
rw charted_space_self_atlas at he he',
simp [he, he', structure_groupoid.id_mem]
end }
/-- Any charted space structure is compatible with the groupoid of all local homeomorphisms -/
instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) :=
⟨begin
assume e e' he he',
rw [continuous_groupoid, mem_groupoid_of_pregroupoid],
simp only [and_self]
end⟩
section maximal_atlas
variables (M) (G : structure_groupoid H)
/-- Given a charted space admitting a structure groupoid, the maximal atlas associated to this
structure groupoid is the set of all local charts that are compatible with the atlas, i.e., such
that changing coordinates with an atlas member gives an element of the groupoid. -/
def structure_groupoid.maximal_atlas : set (local_homeomorph M H) :=
{e | ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G}
variable {M}
/-- The elements of the atlas belong to the maximal atlas for any structure groupoid -/
lemma structure_groupoid.subset_maximal_atlas [has_groupoid M G] :
atlas H M ⊆ G.maximal_atlas M :=
λ e he e' he', ⟨G.compatible he he', G.compatible he' he⟩
lemma structure_groupoid.chart_mem_maximal_atlas [has_groupoid M G]
(x : M) : chart_at H x ∈ G.maximal_atlas M :=
G.subset_maximal_atlas (chart_mem_atlas H x)
variable {G}
lemma mem_maximal_atlas_iff {e : local_homeomorph M H} :
e ∈ G.maximal_atlas M ↔ ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G :=
iff.rfl
/-- Changing coordinates between two elements of the maximal atlas gives rise to an element
of the structure groupoid. -/
lemma structure_groupoid.compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H}
(he : e ∈ G.maximal_atlas M) (he' : e' ∈ G.maximal_atlas M) : e.symm ≫ₕ e' ∈ G :=
begin
apply G.locality (λ x hx, _),
set f := chart_at H (e.symm x) with hf,
let s := e.target ∩ (e.symm ⁻¹' f.source),
have hs : is_open s,
{ apply e.symm.continuous_to_fun.preimage_open_of_open; apply open_source },
have xs : x ∈ s, by { dsimp at hx, simp [s, hx] },
refine ⟨s, hs, xs, _⟩,
have A : e.symm ≫ₕ f ∈ G := (mem_maximal_atlas_iff.1 he f (chart_mem_atlas _ _)).1,
have B : f.symm ≫ₕ e' ∈ G := (mem_maximal_atlas_iff.1 he' f (chart_mem_atlas _ _)).2,
have C : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ∈ G := G.trans A B,
have D : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ≈ (e.symm ≫ₕ e').restr s := calc
(e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') = e.symm ≫ₕ (f ≫ₕ f.symm) ≫ₕ e' : by simp [trans_assoc]
... ≈ e.symm ≫ₕ (of_set f.source f.open_source) ≫ₕ e' :
by simp [eq_on_source.trans', trans_self_symm]
... ≈ (e.symm ≫ₕ (of_set f.source f.open_source)) ≫ₕ e' : by simp [trans_assoc]
... ≈ (e.symm.restr s) ≫ₕ e' : by simp [s, trans_of_set']
... ≈ (e.symm ≫ₕ e').restr s : by simp [restr_trans],
exact G.eq_on_source C (setoid.symm D),
end
variable (G)
/-- In the model space, the identity is in any maximal atlas. -/
lemma structure_groupoid.id_mem_maximal_atlas : local_homeomorph.refl H ∈ G.maximal_atlas H :=
G.subset_maximal_atlas $ by simp
/-- In the model space, any element of the groupoid is in the maximal atlas. -/
lemma structure_groupoid.mem_maximal_atlas_of_mem_groupoid {f : local_homeomorph H H} (hf : f ∈ G) :
f ∈ G.maximal_atlas H :=
begin
rintros e (rfl : e = local_homeomorph.refl H),
exact ⟨G.trans (G.symm hf) G.id_mem, G.trans (G.symm G.id_mem) hf⟩,
end
end maximal_atlas
section singleton
variables {α : Type*} [topological_space α]
namespace local_homeomorph
variable (e : local_homeomorph α H)
/-- If a single local homeomorphism `e` from a space `α` into `H` has source covering the whole
space `α`, then that local homeomorphism induces an `H`-charted space structure on `α`.
(This condition is equivalent to `e` being an open embedding of `α` into `H`; see
`open_embedding.singleton_charted_space`.) -/
def singleton_charted_space (h : e.source = set.univ) : charted_space H α :=
{ atlas := {e},
chart_at := λ _, e,
mem_chart_source := λ _, by simp only [h] with mfld_simps,
chart_mem_atlas := λ _, by tauto }
@[simp, mfld_simps] lemma singleton_charted_space_chart_at_eq (h : e.source = set.univ) {x : α} :
@chart_at H _ α _ (e.singleton_charted_space h) x = e := rfl
lemma singleton_charted_space_chart_at_source
(h : e.source = set.univ) {x : α} :
(@chart_at H _ α _ (e.singleton_charted_space h) x).source = set.univ := h
lemma singleton_charted_space_mem_atlas_eq (h : e.source = set.univ)
(e' : local_homeomorph α H) (h' : e' ∈ (e.singleton_charted_space h).atlas) : e' = e := h'
/-- Given a local homeomorphism `e` from a space `α` into `H`, if its source covers the whole
space `α`, then the induced charted space structure on `α` is `has_groupoid G` for any structure
groupoid `G` which is closed under restrictions. -/
lemma singleton_has_groupoid (h : e.source = set.univ) (G : structure_groupoid H)
[closed_under_restriction G] : @has_groupoid _ _ _ _ (e.singleton_charted_space h) G :=
{ compatible := begin
intros e' e'' he' he'',
rw e.singleton_charted_space_mem_atlas_eq h e' he',
rw e.singleton_charted_space_mem_atlas_eq h e'' he'',
refine G.eq_on_source _ e.trans_symm_self,
have hle : id_restr_groupoid ≤ G := (closed_under_restriction_iff_id_le G).mp (by assumption),
exact structure_groupoid.le_iff.mp hle _ (id_restr_groupoid_mem _),
end }
end local_homeomorph
namespace open_embedding
variable [nonempty α]
/-- An open embedding of `α` into `H` induces an `H`-charted space structure on `α`.
See `local_homeomorph.singleton_charted_space` -/
def singleton_charted_space {f : α → H} (h : open_embedding f) :
charted_space H α := (h.to_local_homeomorph f).singleton_charted_space (by simp)
lemma singleton_charted_space_chart_at_eq {f : α → H} (h : open_embedding f) {x : α} :
⇑(@chart_at H _ α _ (h.singleton_charted_space) x) = f := rfl
lemma singleton_has_groupoid {f : α → H} (h : open_embedding f)
(G : structure_groupoid H) [closed_under_restriction G] :
@has_groupoid _ _ _ _ h.singleton_charted_space G :=
(h.to_local_homeomorph f).singleton_has_groupoid (by simp) G
end open_embedding
end singleton
namespace topological_space.opens
open topological_space
variables (G : structure_groupoid H) [has_groupoid M G]
variables (s : opens M)
/-- An open subset of a charted space is naturally a charted space. -/
instance : charted_space H s :=
{ atlas := ⋃ (x : s), {@local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩},
chart_at := λ x, @local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩,
mem_chart_source := λ x, by { simp only with mfld_simps, exact (mem_chart_source H x.1) },
chart_mem_atlas := λ x, by { simp only [mem_Union, mem_singleton_iff], use x } }
/-- If a groupoid `G` is `closed_under_restriction`, then an open subset of a space which is
`has_groupoid G` is naturally `has_groupoid G`. -/
instance [closed_under_restriction G] : has_groupoid s G :=
{ compatible := begin
rintros e e' ⟨_, ⟨x, hc⟩, he⟩ ⟨_, ⟨x', hc'⟩, he'⟩,
haveI : nonempty s := ⟨x⟩,
simp only [hc.symm, mem_singleton_iff, subtype.val_eq_coe] at he,
simp only [hc'.symm, mem_singleton_iff, subtype.val_eq_coe] at he',
rw [he, he'],
convert G.eq_on_source _
(subtype_restr_symm_trans_subtype_restr s (chart_at H x) (chart_at H x')),
apply closed_under_restriction',
{ exact G.compatible (chart_mem_atlas H x) (chart_mem_atlas H x') },
{ exact preimage_open_of_open_symm (chart_at H x) s.2 },
end }
lemma chart_at_inclusion_symm_eventually_eq {U V : opens M} (hUV : U ≤ V) {x : U} :
(chart_at H (set.inclusion hUV x)).symm
=ᶠ[𝓝 (chart_at H (set.inclusion hUV x) (set.inclusion hUV x))] set.inclusion hUV
∘ (chart_at H x).symm :=
begin
set i := set.inclusion hUV,
set e := chart_at H (x:M),
haveI : nonempty U := ⟨x⟩,
haveI : nonempty V := ⟨i x⟩,
have heUx_nhds : (e.subtype_restr U).target ∈ 𝓝 (e x),
{ apply (e.subtype_restr U).open_target.mem_nhds,
exact e.map_subtype_source (mem_chart_source _ _) },
exact filter.eventually_eq_of_mem heUx_nhds (e.subtype_restr_symm_eq_on_of_le hUV),
end
end topological_space.opens
/-! ### Structomorphisms -/
/-- A `G`-diffeomorphism between two charted spaces is a homeomorphism which, when read in the
charts, belongs to `G`. We avoid the word diffeomorph as it is too related to the smooth category,
and use structomorph instead. -/
@[nolint has_nonempty_instance]
structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*)
[topological_space M] [topological_space M'] [charted_space H M] [charted_space H M']
extends homeomorph M M' :=
(mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H,
c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G)
variables [topological_space M'] [topological_space M'']
{G : structure_groupoid H} [charted_space H M'] [charted_space H M'']
/-- The identity is a diffeomorphism of any charted space, for any groupoid. -/
def structomorph.refl (M : Type*) [topological_space M] [charted_space H M]
[has_groupoid M G] : structomorph G M M :=
{ mem_groupoid := λc c' hc hc', begin
change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G,
rw local_homeomorph.refl_trans,
exact has_groupoid.compatible G hc hc'
end,
..homeomorph.refl M }
/-- The inverse of a structomorphism is a structomorphism -/
def structomorph.symm (e : structomorph G M M') : structomorph G M' M :=
{ mem_groupoid := begin
assume c c' hc hc',
have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G :=
G.symm (e.mem_groupoid c' c hc' hc),
rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc]
at this,
end,
..e.to_homeomorph.symm}
/-- The composition of structomorphisms is a structomorphism -/
def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') :
structomorph G M M'' :=
{ mem_groupoid := begin
/- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these
charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y.
Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so
their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/
assume c c' hc hc',
refine G.locality (λx hx, _),
let f₁ := e.to_homeomorph.to_local_homeomorph,
let f₂ := e'.to_homeomorph.to_local_homeomorph,
let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph,
have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _,
-- define the atlas g around y
let y := (c.symm ≫ₕ f₁) x,
let g := chart_at H y,
have hg₁ := chart_mem_atlas H y,
have hg₂ := mem_chart_source H y,
let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source,
have open_s : is_open s,
by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source,
have : x ∈ s,
{ split,
{ simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source],
rw trans_source at hx,
exact hx.1 },
{ exact hg₂ } },
refine ⟨s, open_s, this, _⟩,
let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'),
have A : F₁ ∈ G := G.trans (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'),
let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s,
have : F₁ ≈ F₂ := calc
F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc]
... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' :
by simp [eq_on_source.trans', trans_self_symm g]
... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') :
by simp [trans_assoc]
... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set']
... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans]
... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc]
... ≈ F₂ : by simp [F₂, feq],
have : F₂ ∈ G := G.eq_on_source A (setoid.symm this),
exact this
end,
..homeomorph.trans e.to_homeomorph e'.to_homeomorph }
end has_groupoid
|
ab86119fc42312eba775fd271f0681eebbfd7bed | 618003631150032a5676f229d13a079ac875ff77 | /src/ring_theory/adjoin_root.lean | 6029348823e2a4e41390124370590e3963942a8f | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 4,120 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
Adjoining roots of polynomials
-/
import data.polynomial
import ring_theory.principal_ideal_domain
/-!
# Adjoining roots of polynomials
This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a
commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is
irreducible, the field structure on `adjoin_root f` is constructed.
## Main definitions and results
The main definitions are in the `adjoin_root` namespace.
* `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism.
* `of f : R →+* adjoin_root f`, the natural ring homomorphism.
* `root f : adjoin_root f`, the image of X in R[X]/(f).
* `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring
homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`.
-/
noncomputable theory
universes u v w
variables {R : Type u} {S : Type v} {K : Type w}
open polynomial ideal
/-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring
as the quotient of `R` by the principal ideal of `f`. -/
def adjoin_root [comm_ring R] (f : polynomial R) : Type u :=
ideal.quotient (span {f} : ideal (polynomial R))
namespace adjoin_root
section comm_ring
variables [comm_ring R] (f : polynomial R)
instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _
instance : inhabited (adjoin_root f) := ⟨0⟩
instance : decidable_eq (adjoin_root f) := classical.dec_eq _
/-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/
def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk_hom _
/-- Embedding of the original ring `R` into `adjoin_root f`. -/
def of : R →+* adjoin_root f := (mk f).comp (ring_hom.of C)
/-- The adjoined root. -/
def root : adjoin_root f := mk f X
variables {f}
instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩
@[simp] lemma mk_self : mk f f = 0 :=
quotient.sound' (mem_span_singleton.2 $ by simp)
@[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl
@[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 :=
quotient.induction_on' (root f)
(λ (g : polynomial R) (hg : mk f g = mk f X),
show finsupp.sum f (λ (e : ℕ) (a : R), mk f (C a) * mk f g ^ e) = 0,
by simp only [hg, ((mk f).map_pow _ _).symm, ((mk f).map_mul _ _).symm];
rw [finsupp.sum, ← (mk f).map_sum,
show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self])
(show (root f) = mk f X, from rfl)
lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) :=
by rw [is_root, eval_map, eval₂_root]
variables [comm_ring S]
/-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/
def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S :=
begin
apply ideal.quotient.lift _ (eval₂_ring_hom i x),
intros g H,
rcases mem_span_singleton.1 H with ⟨y, hy⟩,
rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul]
end
variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0}
@[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a :=
ideal.quotient.lift_mk _ _ _
@[simp] lemma lift_root : lift i a h (root f) = a := by simp [root, h]
@[simp] lemma lift_of {x : R} : lift i a h x = i x :=
by rw [← mk_C x, lift_mk, eval₂_C]
end comm_ring
variables [field K] {f : polynomial K} [irreducible f]
instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) :=
principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f›
noncomputable instance field : field (adjoin_root f) :=
ideal.quotient.field (span {f} : ideal (polynomial K))
lemma coe_injective : function.injective (coe : K → adjoin_root f) :=
(of f).injective
variable (f)
lemma mul_div_root_cancel :
(X - C (root f)) * (f.map (of f) / (X - C (root f))) = f.map (of f) :=
mul_div_eq_iff_is_root.2 $ is_root_root _
end adjoin_root
|
37a157a0418f9fd3166f8603f6f306a9809fa3a9 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/playground/termParserAttr.lean | 4219d7823c4363791bd105b3b88e649bebc22182 | [
"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 | 1,034 | lean | import Lean
open Lean
open Lean.Elab
def run (input : String) (failIff : Bool := true) : MetaIO Unit :=
do env ← MetaIO.getEnv;
opts ← MetaIO.getOptions;
let (env, messages) := process input env opts;
messages.toList.forM $ fun msg => IO.println msg;
when (failIff && messages.hasErrors) $ throw (IO.userError "errors have been found");
when (!failIff && !messages.hasErrors) $ throw (IO.userError "there are no errors");
pure ()
open Lean.Parser
@[termParser] def tst := parser! "(|" >> termParser >> "|)"
@[termParser] def boo : ParserDescr :=
ParserDescr.node `boo
(ParserDescr.andthen
(ParserDescr.symbol "[|" 0)
(ParserDescr.andthen
(ParserDescr.parser `term 0)
(ParserDescr.symbol "|]" 0)))
open Lean.Elab.Term
@[termElab tst] def elabTst : TermElab :=
fun stx expected? =>
elabTerm (stx.getArg 1) expected?
@[termElab boo] def elabBoo : TermElab :=
fun stx expected? =>
elabTerm (stx.getArg 1) expected?
#eval run "#check [| @id.{1} Nat |]"
#eval run "#check (| id 1 |)"
|
5e39b1d102fcf7891dfc8f62a9d3123a238a2257 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/nat/totient.lean | ded01f637e46c7a8eaba5c059690382a85ebfc6d | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 14,681 | 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 algebra.char_p.two
import data.nat.factorization.basic
import data.nat.periodic
import data.zmod.basic
/-!
# Euler's totient function
This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function)
`nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`.
We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See
`sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and
`totient_prime_pow`.
-/
open finset
open_locale big_operators
namespace nat
/-- Euler's totient function. This counts the number of naturals strictly less than `n` which are
coprime with `n`. -/
def totient (n : ℕ) : ℕ := ((range n).filter n.coprime).card
localized "notation `φ` := nat.totient" in nat
@[simp] theorem totient_zero : φ 0 = 0 := rfl
@[simp] theorem totient_one : φ 1 = 1 :=
by simp [totient]
lemma totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter n.coprime).card := rfl
lemma totient_le (n : ℕ) : φ n ≤ n :=
((range n).card_filter_le _).trans_eq (card_range n)
lemma totient_lt (n : ℕ) (hn : 1 < n) : φ n < n :=
(card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n)
lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n
| 0 := dec_trivial
| 1 := by simp [totient]
| (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩
lemma filter_coprime_Ico_eq_totient (a n : ℕ) :
((Ico n (n+a)).filter (coprime a)).card = totient a :=
begin
rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range],
exact periodic_coprime a,
end
lemma Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) :
((Ico k (k + n)).filter (coprime a)).card ≤ totient a * (n / a + 1) :=
begin
conv_lhs { rw ←nat.mod_add_div n a },
induction n / a with i ih,
{ rw ←filter_coprime_Ico_eq_totient a k,
simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos)],
mono,
refine monotone_filter_left a.coprime _,
simp only [finset.le_eq_subset],
exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k), },
simp only [mul_succ],
simp_rw ←add_assoc at ih ⊢,
calc (filter a.coprime (Ico k (k + n % a + a * i + a))).card
= (filter a.coprime (Ico k (k + n % a + a * i)
∪ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card :
begin
congr,
rw Ico_union_Ico_eq_Ico,
rw add_assoc,
exact le_self_add,
exact le_self_add,
end
... ≤ (filter a.coprime (Ico k (k + n % a + a * i))).card + a.totient :
begin
rw [filter_union, ←filter_coprime_Ico_eq_totient a (k + n % a + a * i)],
apply card_union_le,
end
... ≤ a.totient * i + a.totient + a.totient : add_le_add_right ih (totient a),
end
open zmod
/-- Note this takes an explicit `fintype ((zmod n)ˣ)` argument to avoid trouble with instance
diamonds. -/
@[simp] lemma _root_.zmod.card_units_eq_totient (n : ℕ) [h : fact (0 < n)] [fintype ((zmod n)ˣ)] :
fintype.card ((zmod n)ˣ) = φ n :=
calc fintype.card ((zmod n)ˣ) = fintype.card {x : zmod n // x.val.coprime n} :
fintype.card_congr zmod.units_equiv_coprime
... = φ n :
begin
unfreezingI { obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := exists_eq_succ_of_ne_zero h.out.ne' },
simp only [totient, finset.card_eq_sum_ones, fintype.card_subtype, finset.sum_filter,
← fin.sum_univ_eq_sum_range, @nat.coprime_comm (m + 1)],
refl
end
lemma totient_even {n : ℕ} (hn : 2 < n) : even n.totient :=
begin
haveI : fact (1 < n) := ⟨one_lt_two.trans hn⟩,
suffices : 2 = order_of (-1 : (zmod n)ˣ),
{ rw [← zmod.card_units_eq_totient, even_iff_two_dvd, this], exact order_of_dvd_card_univ },
rw [←order_of_units, units.coe_neg_one, order_of_neg_one, ring_char.eq (zmod n) n, if_neg hn.ne'],
end
lemma totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n :=
if hmn0 : m * n = 0
then by cases nat.mul_eq_zero.1 hmn0 with h h;
simp only [totient_zero, mul_zero, zero_mul, h]
else
begin
haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩,
haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩,
haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩,
simp only [← zmod.card_units_eq_totient],
rw [fintype.card_congr (units.map_equiv (zmod.chinese_remainder h).to_mul_equiv).to_equiv,
fintype.card_congr (@mul_equiv.prod_units (zmod m) (zmod n) _ _).to_equiv,
fintype.card_prod]
end
/-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/
lemma totient_div_of_dvd {n d : ℕ} (hnd : d ∣ n) :
φ (n/d) = (filter (λ (k : ℕ), n.gcd k = d) (range n)).card :=
begin
rcases d.eq_zero_or_pos with rfl | hd0, { simp [eq_zero_of_zero_dvd hnd] },
rcases hnd with ⟨x, rfl⟩,
rw nat.mul_div_cancel_left x hd0,
apply finset.card_congr (λ k _, d * k),
{ simp only [mem_filter, mem_range, and_imp, coprime],
refine λ a ha1 ha2, ⟨(mul_lt_mul_left hd0).2 ha1, _⟩,
rw [gcd_mul_left, ha2, mul_one] },
{ simp [hd0.ne'] },
{ simp only [mem_filter, mem_range, exists_prop, and_imp],
refine λ b hb1 hb2, _,
have : d ∣ b, { rw ←hb2, apply gcd_dvd_right },
rcases this with ⟨q, rfl⟩,
refine ⟨q, ⟨⟨(mul_lt_mul_left hd0).1 hb1, _⟩, rfl⟩⟩,
rwa [gcd_mul_left, mul_right_eq_self_iff hd0] at hb2 },
end
lemma sum_totient (n : ℕ) : n.divisors.sum φ = n :=
begin
rcases n.eq_zero_or_pos with rfl | hn, { simp },
rw ←sum_div_divisors n φ,
have : n = ∑ (d : ℕ) in n.divisors, (filter (λ (k : ℕ), n.gcd k = d) (range n)).card,
{ nth_rewrite_lhs 0 ←card_range n,
refine card_eq_sum_card_fiberwise (λ x hx, mem_divisors.2 ⟨_, hn.ne'⟩),
apply gcd_dvd_left },
nth_rewrite_rhs 0 this,
exact sum_congr rfl (λ x hx, totient_div_of_dvd (dvd_of_mem_divisors hx)),
end
lemma sum_totient' (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n :=
begin
convert sum_totient _ using 1,
simp only [nat.divisors, sum_filter, range_eq_Ico],
rw sum_eq_sum_Ico_succ_bot; simp
end
/-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/
lemma totient_prime_pow_succ {p : ℕ} (hp : p.prime) (n : ℕ) :
φ (p ^ (n + 1)) = p ^ n * (p - 1) :=
calc φ (p ^ (n + 1))
= ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card :
totient_eq_card_coprime _
... = (range (p ^ (n + 1)) \ ((range (p ^ n)).image (* p))).card :
congr_arg card begin
rw [sdiff_eq_filter],
apply filter_congr,
simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos,
mem_image, not_exists, hp.coprime_iff_not_dvd],
intros a ha,
split,
{ rintros hap b _ rfl,
exact hap (dvd_mul_left _ _) },
{ rintros h ⟨b, rfl⟩,
rw [pow_succ] at ha,
exact h b (lt_of_mul_lt_mul_left ha (zero_le _)) (mul_comm _ _) }
end
... = _ :
have h1 : set.inj_on (* p) (range (p ^ n)),
from λ x _ y _, (nat.mul_left_inj hp.pos).1,
have h2 : (range (p ^ n)).image (* p) ⊆ range (p ^ (n + 1)),
from λ a, begin
simp only [mem_image, mem_range, exists_imp_distrib],
rintros b h rfl,
rw [pow_succ'],
exact (mul_lt_mul_right hp.pos).2 h
end,
begin
rw [card_sdiff h2, card_image_of_inj_on h1, card_range,
card_range, ← one_mul (p ^ n), pow_succ, ← tsub_mul,
one_mul, mul_comm]
end
/-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/
lemma totient_prime_pow {p : ℕ} (hp : p.prime) {n : ℕ} (hn : 0 < n) :
φ (p ^ n) = p ^ (n - 1) * (p - 1) :=
by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩;
exact totient_prime_pow_succ hp _
lemma totient_prime {p : ℕ} (hp : p.prime) : φ p = p - 1 :=
by rw [← pow_one p, totient_prime_pow hp]; simp
lemma totient_eq_iff_prime {p : ℕ} (hp : 0 < p) : p.totient = p - 1 ↔ p.prime :=
begin
refine ⟨λ h, _, totient_prime⟩,
replace hp : 1 < p,
{ apply lt_of_le_of_ne,
{ rwa succ_le_iff },
{ rintro rfl,
rw [totient_one, tsub_self] at h,
exact one_ne_zero h } },
rw [totient_eq_card_coprime, range_eq_Ico, ←Ico_insert_succ_left hp.le, finset.filter_insert,
if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ←nat.card_Ico 1 p] at h,
refine p.prime_of_coprime hp (λ n hn hnz, finset.filter_card_eq h n $ finset.mem_Ico.mpr ⟨_, hn⟩),
rwa [succ_le_iff, pos_iff_ne_zero],
end
lemma card_units_zmod_lt_sub_one {p : ℕ} (hp : 1 < p) [fintype ((zmod p)ˣ)] :
fintype.card ((zmod p)ˣ) ≤ p - 1 :=
begin
haveI : fact (0 < p) := ⟨zero_lt_one.trans hp⟩,
rw zmod.card_units_eq_totient p,
exact nat.le_pred_of_lt (nat.totient_lt p hp),
end
lemma prime_iff_card_units (p : ℕ) [fintype ((zmod p)ˣ)] :
p.prime ↔ fintype.card ((zmod p)ˣ) = p - 1 :=
begin
by_cases hp : p = 0,
{ substI hp,
simp only [zmod, not_prime_zero, false_iff, zero_tsub],
-- the substI created an non-defeq but subsingleton instance diamond; resolve it
suffices : fintype.card ℤˣ ≠ 0, { convert this },
simp },
haveI : fact (0 < p) := ⟨nat.pos_of_ne_zero hp⟩,
rw [zmod.card_units_eq_totient, nat.totient_eq_iff_prime (fact.out (0 < p))],
end
@[simp] lemma totient_two : φ 2 = 1 :=
(totient_prime prime_two).trans rfl
lemma totient_eq_one_iff : ∀ {n : ℕ}, n.totient = 1 ↔ n = 1 ∨ n = 2
| 0 := by simp
| 1 := by simp
| 2 := by simp
| (n+3) :=
begin
have : 3 ≤ n + 3 := le_add_self,
simp only [succ_succ_ne_one, false_or],
exact ⟨λ h, not_even_one.elim $ h ▸ totient_even this, by rintro ⟨⟩⟩,
end
/-! ### Euler's product formula for the totient function
We prove several different statements of this formula. -/
/-- Euler's product formula for the totient function. -/
theorem totient_eq_prod_factorization {n : ℕ} (hn : n ≠ 0) :
φ n = n.factorization.prod (λ p k, p ^ (k - 1) * (p - 1)) :=
begin
rw multiplicative_factorization φ @totient_mul totient_one hn,
apply finsupp.prod_congr (λ p hp, _),
have h := zero_lt_iff.mpr (finsupp.mem_support_iff.mp hp),
rw [totient_prime_pow (prime_of_mem_factorization hp) h],
end
/-- Euler's product formula for the totient function. -/
theorem totient_mul_prod_factors (n : ℕ) :
φ n * ∏ p in n.factors.to_finset, p = n * ∏ p in n.factors.to_finset, (p - 1) :=
begin
by_cases hn : n = 0, { simp [hn] },
rw totient_eq_prod_factorization hn,
nth_rewrite 2 ←factorization_prod_pow_eq_self hn,
simp only [←prod_factorization_eq_prod_factors, ←finsupp.prod_mul],
refine finsupp.prod_congr (λ p hp, _),
rw [finsupp.mem_support_iff, ← zero_lt_iff] at hp,
rw [mul_comm, ←mul_assoc, ←pow_succ, nat.sub_add_cancel hp],
end
/-- Euler's product formula for the totient function. -/
theorem totient_eq_div_factors_mul (n : ℕ) :
φ n = n / (∏ p in n.factors.to_finset, p) * (∏ p in n.factors.to_finset, (p - 1)) :=
begin
rw [← mul_div_left n.totient, totient_mul_prod_factors, mul_comm,
nat.mul_div_assoc _ (prod_prime_factors_dvd n), mul_comm],
simpa [prod_factorization_eq_prod_factors] using prod_pos (λ p, pos_of_mem_factorization),
end
/-- Euler's product formula for the totient function. -/
theorem totient_eq_mul_prod_factors (n : ℕ) :
(φ n : ℚ) = n * ∏ p in n.factors.to_finset, (1 - p⁻¹) :=
begin
by_cases hn : n = 0, { simp [hn] },
have hn' : (n : ℚ) ≠ 0, { simp [hn] },
have hpQ : ∏ p in n.factors.to_finset, (p : ℚ) ≠ 0,
{ rw [←cast_prod, cast_ne_zero, ←zero_lt_iff, ←prod_factorization_eq_prod_factors],
exact prod_pos (λ p hp, pos_of_mem_factorization hp) },
simp only [totient_eq_div_factors_mul n, prod_prime_factors_dvd n, cast_mul, cast_prod,
cast_div_char_zero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ←prod_mul_distrib],
refine prod_congr rfl (λ p hp, _),
have hp := pos_of_mem_factors (list.mem_to_finset.mp hp),
have hp' : (p : ℚ) ≠ 0 := cast_ne_zero.mpr hp.ne.symm,
rw [sub_mul, one_mul, mul_comm, mul_inv_cancel hp', cast_pred hp],
end
lemma totient_gcd_mul_totient_mul (a b : ℕ) : φ (a.gcd b) * φ (a * b) = φ a * φ b * (a.gcd b) :=
begin
have shuffle : ∀ a1 a2 b1 b2 c1 c2 : ℕ, b1 ∣ a1 → b2 ∣ a2 →
(a1/b1 * c1) * (a2/b2 * c2) = (a1*a2)/(b1*b2) * (c1*c2),
{ intros a1 a2 b1 b2 c1 c2 h1 h2,
calc
(a1/b1 * c1) * (a2/b2 * c2) = ((a1/b1) * (a2/b2)) * (c1*c2) : by apply mul_mul_mul_comm
... = (a1*a2)/(b1*b2) * (c1*c2) : by { congr' 1, exact div_mul_div_comm h1 h2 } },
simp only [totient_eq_div_factors_mul],
rw [shuffle, shuffle],
rotate, repeat { apply prod_prime_factors_dvd },
{ simp only [prod_factors_gcd_mul_prod_factors_mul],
rw [eq_comm, mul_comm, ←mul_assoc, ←nat.mul_div_assoc],
exact mul_dvd_mul (prod_prime_factors_dvd a) (prod_prime_factors_dvd b) }
end
lemma totient_super_multiplicative (a b : ℕ) : φ a * φ b ≤ φ (a * b) :=
begin
let d := a.gcd b,
rcases (zero_le a).eq_or_lt with rfl | ha0, { simp },
have hd0 : 0 < d, from nat.gcd_pos_of_pos_left _ ha0,
rw [←mul_le_mul_right hd0, ←totient_gcd_mul_totient_mul a b, mul_comm],
apply mul_le_mul_left' (nat.totient_le d),
end
lemma totient_dvd_of_dvd {a b : ℕ} (h : a ∣ b) : φ a ∣ φ b :=
begin
rcases eq_or_ne a 0 with rfl | ha0, { simp [zero_dvd_iff.1 h] },
rcases eq_or_ne b 0 with rfl | hb0, { simp },
have hab' : a.factorization.support ⊆ b.factorization.support,
{ intro p,
simp only [support_factorization, list.mem_to_finset],
apply factors_subset_of_dvd h hb0 },
rw [totient_eq_prod_factorization ha0, totient_eq_prod_factorization hb0],
refine finsupp.prod_dvd_prod_of_subset_of_dvd hab' (λ p hp, mul_dvd_mul _ dvd_rfl),
exact pow_dvd_pow p (tsub_le_tsub_right ((factorization_le_iff_dvd ha0 hb0).2 h p) 1),
end
lemma totient_mul_of_prime_of_dvd {p n : ℕ} (hp : p.prime) (h : p ∣ n) :
(p * n).totient = p * n.totient :=
begin
have h1 := totient_gcd_mul_totient_mul p n,
rw [(gcd_eq_left h), mul_assoc] at h1,
simpa [(totient_pos hp.pos).ne', mul_comm] using h1,
end
lemma totient_mul_of_prime_of_not_dvd {p n : ℕ} (hp : p.prime) (h : ¬ p ∣ n) :
(p * n).totient = (p - 1) * n.totient :=
begin
rw [totient_mul _, totient_prime hp],
simpa [h] using coprime_or_dvd_of_prime hp n,
end
end nat
|
acef879c942ae65dce42f0e4786a6eb662e88935 | 367134ba5a65885e863bdc4507601606690974c1 | /src/measure_theory/set_integral.lean | 4ce848c994bafdae8251851b802b996548288fc2 | [
"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 | 44,941 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.bochner_integration
import analysis.normed_space.indicator_function
/-!
# Set integral
In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation
is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable
function `f` and a measurable set `s` this definition coincides with another natural definition:
`∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s`
and is zero otherwise.
Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ`
directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g.
`integral_union`, `integral_empty`, `integral_univ`.
We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like
`integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`.
Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)`
saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable
at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite
at `l`.
Finally, we prove a version of the
[Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus)
for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries.
Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and
a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)`
as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that
`∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this
theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`.
## Notation
We provide the following notations for expressing the integral of a function on a set :
* `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f`
* `∫ a in s, f a` is `∫ a in s, f a ∂volume`
Note that the set notations are defined in the file `measure_theory/bochner_integration`,
but we reference them here because all theorems about set integrals are in this file.
## TODO
The file ends with over a hundred lines of commented out code. This is the old contents of this file
using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be
migrated to the new definition.
-/
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topological_space interval big_operators filter ennreal
variables {α β E F : Type*} [measurable_space α]
section piecewise
variables {μ : measure α} {s : set α} {f g : α → β}
lemma piecewise_ae_eq_restrict (hs : measurable_set s) : piecewise s f g =ᵐ[μ.restrict s] f :=
begin
rw [ae_restrict_eq hs],
exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_restrict_compl (hs : measurable_set s) :
piecewise s f g =ᵐ[μ.restrict sᶜ] g :=
begin
rw [ae_restrict_eq hs.compl],
exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right
end
end piecewise
section indicator_function
variables [has_zero β] {μ : measure α} {s : set α} {f : α → β}
lemma indicator_ae_eq_restrict (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict s] f :=
piecewise_ae_eq_restrict hs
lemma indicator_ae_eq_restrict_compl (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 :=
piecewise_ae_eq_restrict_compl hs
end indicator_function
section
variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α}
/-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable
w.r.t. `μ.restrict s` for some `s ∈ l`. -/
def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, ae_measurable f (μ.restrict s)
@[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ :=
⟨∅, mem_bot_sets, by simp⟩
protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) :
∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) :=
(eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h
protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) :
measurable_at_filter f l' μ :=
let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩
protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) :
measurable_at_filter f l μ :=
⟨univ, univ_mem_sets, by rwa measure.restrict_univ⟩
lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s))
(hl : s ∈ l):
measurable_at_filter f l μ :=
⟨s, hl, h⟩
protected lemma measurable.measurable_at_filter (h : measurable f) :
measurable_at_filter f l μ :=
h.ae_measurable.measurable_at_filter
end
namespace measure_theory
section normed_group
lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α}
{μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) :
has_finite_integral f (μ.restrict s) :=
by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩;
exact has_finite_integral_of_bounded hf
variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α}
/-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of
its pointwise norm over `s` is less than infinity. -/
def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop :=
integrable f (μ.restrict s)
lemma integrable_on.integrable (h : integrable_on f s μ) :
integrable f (μ.restrict s) :=
h
@[simp] lemma integrable_on_empty : integrable_on f ∅ μ :=
by simp [integrable_on, integrable_zero_measure]
@[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ :=
by rw [integrable_on, measure.restrict_univ]
lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _
lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ :=
integrable_const_iff.trans $ by rw [measure.restrict_apply_univ]
lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono_measure $ measure.restrict_mono hs hμ
lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) :
integrable_on f s μ :=
h.mono hst (le_refl _)
lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono (subset.refl _) hμ
lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) :
integrable_on f s μ :=
h.integrable.mono_measure $ restrict_mono_ae hst
lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ :=
h.mono_measure $ measure.restrict_le_self
lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ :=
h
lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ :=
h.mono_set $ subset_union_left _ _
lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ :=
h.mono_set $ subset_union_right _ _
lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) :
integrable_on f (s ∪ t) μ :=
(hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _
@[simp] lemma integrable_on_union :
integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ :=
⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩
@[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s)
{t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
begin
apply hs.induction_on,
{ simp },
{ intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] }
end
@[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} :
integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
integrable_on_finite_union s.finite_to_set
lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) :
integrable_on f s (μ + ν) :=
by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν }
@[simp] lemma integrable_on_add_measure :
integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)),
h.mono_measure (measure.le_add_left (le_refl _))⟩,
λ h, h.1.add_measure h.2⟩
lemma ae_measurable_indicator_iff (hs : measurable_set s) :
ae_measurable f (μ.restrict s) ↔ ae_measurable (indicator s f) μ :=
begin
split,
{ assume h,
refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩,
have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm),
have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm,
have : s.indicator f =ᵐ[μ.restrict s + μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
ae_add_measure_iff.2 ⟨A, B⟩,
simpa only [hs, measure.restrict_add_restrict_compl] using this },
{ assume h,
exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }
end
lemma integrable_indicator_iff (hs : measurable_set s) :
integrable (indicator s f) μ ↔ integrable_on f s μ :=
by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm,
ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs]
lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) :
integrable (indicator s f) μ :=
(integrable_indicator_iff hs).2 h
/-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some
set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/
def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, integrable_on f s μ
variables {l l' : filter α}
protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) :
∀ᶠ s in l.lift' powerset, integrable_on f s μ :=
by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst }
lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) :
integrable_at_filter f l μ :=
let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩
lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l ⊓ l') μ :=
hl.filter_mono inf_le_left
lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l' ⊓ l) μ :=
hl.filter_mono inf_le_right
@[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} :
integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩,
refine ⟨t, ht, _⟩,
refine hf.integrable.mono_measure (λ v hv, _),
simp only [measure.restrict_apply hv],
refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _),
exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩
end
alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _
/-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded
above at `l`, then `f` is integrable at `l`. -/
lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l]
(hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
(hf : l.is_bounded_under (≤) (norm ∘ f)) :
integrable_at_filter f l μ :=
begin
obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C,
from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩),
rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift'
with ⟨s, hsl, hsm, hfm, hμ, hC⟩,
refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩,
exact C,
rw [ae_restrict_eq hsm, eventually_inf_principal],
exact eventually_of_forall hC
end
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae
{l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ)
(hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) :
integrable_at_filter f l μ :=
(hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left)
hf.norm.is_bounded_under_le).of_inf_ae
alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ←
filter.tendsto.integrable_at_filter_ae
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α}
[is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
{b} (hf : tendsto f l (𝓝 b)) :
integrable_at_filter f l μ :=
hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le
alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter
variables [borel_space E] [second_countable_topology E]
lemma integrable_add [opens_measurable_space E] {f g : α → E}
(h : univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0}) (hf : measurable f) (hg : measurable g) :
integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ :=
begin
refine ⟨λ hfg, _, λ h, h.1.add h.2⟩,
rw [← indicator_add_eq_left h],
conv { congr, skip, rw [← indicator_add_eq_right h] },
rw [integrable_indicator_iff (hf (measurable_set_singleton 0)).compl],
rw [integrable_indicator_iff (hg (measurable_set_singleton 0)).compl],
exact ⟨hfg.integrable_on, hfg.integrable_on⟩
end
/-- To prove something for an arbitrary integrable function in a second countable
Borel normed group, it suffices to show that
* the property holds for (multiples of) characteristic functions;
* is closed under addition;
* the set of functions in the `L¹` space for which the property holds is closed.
* the property is closed under the almost-everywhere equal relation.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`).
-/
@[elab_as_eliminator]
lemma integrable.induction (P : (α → E) → Prop)
(h_ind : ∀ (c : E) ⦃s⦄, measurable_set s → μ s < ∞ → P (s.indicator (λ _, c)))
(h_sum : ∀ ⦃f g : α → E⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → integrable f μ → integrable g μ →
P f → P g → P (f + g))
(h_closed : is_closed {f : α →₁[μ] E | P f} )
(h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → integrable f μ → P f → P g) :
∀ ⦃f : α → E⦄ (hf : integrable f μ), P f :=
begin
have : ∀ (f : simple_func α E), integrable f μ → P f,
{ refine simple_func.induction _ _,
{ intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero,
piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢,
by_cases hc : c = 0,
{ subst hc, convert h_ind 0 measurable_set.empty (by simp) using 1, simp [const] },
apply h_ind c hs,
have : (nnnorm c : ℝ≥0∞) * μ s < ∞,
{ have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ℝ≥0∞)) (const α c) s,
dsimp only at this,
have h' := h.has_finite_integral,
simpa [has_finite_integral, this, lintegral_indicator, hs] using h' },
exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) },
{ intros f g hfg hf hg int_fg,
rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg,
refine h_sum hfg int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } },
have : ∀ (f : α →₁ₛ[μ] E), P f,
{ intro f,
exact h_ae (L1.simple_func.to_simple_func_eq_to_fun f) (L1.simple_func.integrable f)
(this (L1.simple_func.to_simple_func f) (L1.simple_func.integrable f)) },
have : ∀ (f : α →₁[μ] E), P f :=
λ f, L1.simple_func.dense_range.induction_on f h_closed this,
exact λ f hf, h_ae hf.coe_fn_to_L1 (L1.integrable_coe_fn _) (this (hf.to_L1 f)),
end
variables [complete_space E] [normed_space ℝ E]
lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
integral_congr_ae ((ae_restrict_iff' hs).2 h)
lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
set_integral_congr_ae hs $ eventually_of_forall h
lemma integral_union (hst : disjoint s t) (hs : measurable_set s) (ht : measurable_set t)
(hfs : integrable_on f s μ) (hft : integrable_on f t μ) :
∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ :=
by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft]
lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure]
lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ]
lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) :
∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ :=
by rw [← integral_union disjoint_compl_right hs hs.compl hfi.integrable_on hfi.integrable_on,
union_compl_self, integral_univ]
/-- For a function `f` and a measurable set `s`, the integral of `indicator s f`
over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/
lemma integral_indicator (hs : measurable_set s) :
∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ :=
begin
by_cases hf : ae_measurable f (μ.restrict s), swap,
{ rw integral_non_ae_measurable hf,
rw [ae_measurable_indicator_iff hs] at hf,
exact integral_non_ae_measurable hf },
by_cases hfi : integrable_on f s μ, swap,
{ rwa [integral_undef, integral_undef],
rwa integrable_indicator_iff hs },
calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ :
(integral_add_compl hs (hfi.indicator hs)).symm
... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ :
congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs))
(integral_congr_ae (indicator_ae_eq_restrict_compl hs))
... = ∫ x in s, f x ∂μ : by simp
end
lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c :=
by rw [integral_const, measure.restrict_apply_univ]
@[simp]
lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) :
∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e :=
by rw [integral_indicator s_meas, ← set_integral_const]
lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β}
(hs : measurable_set s) (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
begin
rw [measure.restrict_map hg hs, integral_map hg (hf.mono_measure _)],
exact measure.map_mono hg measure.restrict_le_self
end
lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
rw ← measure.restrict_apply_univ at *,
haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩,
exact norm_integral_le_of_norm_le_const hC
end
lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
apply norm_set_integral_le_of_norm_le_const_ae hs,
have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_measurable.mk f hfm x∥ ≤ C,
{ filter_upwards [hC, hfm.ae_mem_imp_eq_mk],
assume a h1 h2 h3,
rw [← h2 h3],
exact h1 h3 },
have B : measurable_set {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.measurable_mk.norm measurable_set_Iic,
filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A],
assume a h1 h2,
rwa h1
end
lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal]
lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm
lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC
lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 :=
integral_eq_zero_iff_of_nonneg_ae hf hfi
lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) :=
begin
rw [integral_pos_iff_support_of_nonneg_ae hf hfi, restrict_apply_of_null_measurable_set],
exact hfi.ae_measurable.null_measurable_set (measurable_set_singleton 0).compl
end
end normed_group
section mono
variables {μ : measure α} {f g : α → ℝ} {s : set α}
(hf : integrable_on f s μ) (hg : integrable_on g s μ)
lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono_ae hf hg h
lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h)
lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg
(by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h])
lemma set_integral_mono (h : f ≤ g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono hf hg h
end mono
section nonneg
variables {μ : measure α} {f : α → ℝ} {s : set α}
lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) :
(0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
integral_nonneg_of_ae hf
lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : (0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf)
lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) :
(0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf))
end nonneg
end measure_theory
open measure_theory asymptotics metric
variables {ι : Type*} [measurable_space E] [normed_group E]
/-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a
filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in
s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.lift'
powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the
actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma filter.tendsto.integral_sub_linear_is_o_ae
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} {l : filter α} [l.is_measurably_generated]
{f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b))
(hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
{s : ι → set α} {li : filter ι} (hs : tendsto s li (l.lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • b) m li :=
begin
suffices : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real)
(l.lift' powerset),
from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ,
refine is_o_iff.2 (λ ε ε₀, _),
have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε :=
eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀),
filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually,
hfm.eventually, this],
simp only [mem_closed_ball, dist_eq_norm],
intros s hμs h_integrable hfm h_norm,
rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs),
real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg],
exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_measurable_const)
end
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`
within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li`
provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞`
number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_within_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t)
(hfm : measurable_at_filter f (𝓝[t] a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _;
exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae
hfm (μ.finite_at_nhds_within a t) hs m hsμ
/-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite
measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then
`∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).lift'
powerset` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the
actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α}
{f : α → E} (ha : continuous_at f a) (hfm : measurable_at_filter f (𝓝 a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝 a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
(ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ
/-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is
integrable on `s`. -/
lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α}
(hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) :
integrable_on f s μ :=
is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst)
(λ s t hs ht, hs.union ht) hf
/-- A function which is continuous on a set `s` is almost everywhere measurable with respect to
`μ.restrict s`. -/
lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E]
{f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) :
ae_measurable f (μ.restrict s) :=
begin
refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩,
apply measurable_of_is_open,
assume t ht,
obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
_root_.continuous_on_iff'.1 hf t ht,
rw [indicator_preimage, inter_comm, hu],
exact (u_open.measurable_set.inter hs).union (hs.compl.inter (measurable_const ht.measurable_set))
end
lemma continuous_on.integrable_at_nhds_within
[topological_space α] [opens_measurable_space α] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E}
(hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) :
integrable_at_filter f (𝓝[t] a) μ :=
by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _;
exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩
(μ.finite_at_nhds_within _ _)
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ =
μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along
`li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_on.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
(hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_measurable ht⟩ hs m hsμ
/-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any
locally finite measure. -/
lemma continuous_on.integrable_on_compact
[topological_space α] [opens_measurable_space α] [borel_space E]
[t2_space α] {μ : measure α} [locally_finite_measure μ]
{s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) :
integrable_on f s μ :=
hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx
/-- A continuous function `f` is integrable on any compact set with respect to any locally finite
measure. -/
lemma continuous.integrable_on_compact
[topological_space α] [opens_measurable_space α] [t2_space α]
[borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α}
(hs : is_compact s) {f : α → E} (hf : continuous f) :
integrable_on f s μ :=
hf.continuous_on.integrable_on_compact hs
/-- A continuous function with compact closure of the support is integrable on the whole space. -/
lemma continuous.integrable_of_compact_closure_support
[topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f)
(hfc : is_compact (closure $ support f)) :
integrable f μ :=
begin
rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)),
integrable_indicator_iff is_closed_closure.measurable_set],
{ exact hf.integrable_on_compact hfc },
{ apply_instance }
end
section
/-! ### Continuous linear maps composed with integration
The goal of this section is to prove that integration commutes with continuous linear maps.
This holds for simple functions. The general result follows from the continuity of all involved
operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just
the composition, as we are dealing with classes of functions, but it has already been defined
as `continuous_linear_map.comp_Lp`. We take advantage of this construction here.
-/
variables {μ : measure α} [normed_space ℝ E]
variables [normed_group F] [normed_space ℝ F]
variables {p : ennreal}
local attribute [instance] fact_one_le_one_ennreal
namespace continuous_linear_map
variables [measurable_space F] [borel_space F]
lemma integrable_comp [opens_measurable_space E] {φ : α → E} (L : E →L[ℝ] F)
(φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ :=
((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp_ae_measurable φ_int.ae_measurable)
(eventually_of_forall $ λ a, L.le_op_norm (φ a))
variables [second_countable_topology F] [complete_space F]
[borel_space E] [second_countable_topology E]
lemma integral_comp_Lp (L : E →L[ℝ] F) (φ : Lp E p μ) :
∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ :=
integral_congr_ae $ coe_fn_comp_Lp _ _
lemma continuous_integral_comp_L1 (L : E →L[ℝ] F) :
continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) :=
begin
rw ← funext L.integral_comp_Lp,
exact continuous_integral.comp (L.comp_LpL 1 μ).continuous
end
variables [complete_space E]
lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_int : integrable φ μ) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)),
{ intros e s s_meas s_finite,
rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul,
← integral_indicator_const (L e) s_meas],
congr' 1 with a,
rw set.indicator_comp_of_zero L.map_zero },
{ intros f g H f_int g_int hf hg,
simp [L.map_add, integral_add f_int g_int,
integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] },
{ exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) },
{ intros f g hfg f_int hf,
convert hf using 1 ; clear hf,
{ exact integral_congr_ae (hfg.fun_comp L).symm },
{ rw integral_congr_ae hfg.symm } },
all_goals { assumption }
end
lemma integral_comp_L1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.integral_comp_comm (L1.integrable_coe_fn φ)
end continuous_linear_map
variables [borel_space E] [second_countable_topology E] [complete_space E]
[measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F]
lemma fst_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ :=
((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm
lemma snd_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ :=
((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm
lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) :
∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) :=
have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this)
lemma integral_smul_const (f : α → ℝ) (c : E) :
∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c :=
begin
by_cases hf : integrable f μ,
{ exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf },
{ by_cases hc : c = 0,
{ simp only [hc, integral_zero, smul_zero] },
rw [integral_undef hf, integral_undef, zero_smul],
simp_rw [integrable_smul_const hc, hf, not_false_iff] }
end
end
/-
namespace integrable
variables [measurable_space α] [measurable_space β] [normed_group E]
protected lemma measure_mono
end integrable
end measure_theory
section integral_on
variables [measurable_space α]
[normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β]
[measurable_space β] [borel_space β]
{s t : set α} {f g : α → β} {μ : measure α}
open set
lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : measurable_set s)
(h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ :=
integral_congr_ae hf hg $ _
lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f)
(h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) :=
integral_congr_ae hsm htm $ indicator_congr_of_set h
lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) :
(∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) :=
by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi }
lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g)
(hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) :=
by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi }
lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f)
(hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g)
(h : ∀ᵐ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
begin
apply integral_le_integral_ae hfm hfi hgm hgi,
apply indicator_le_indicator_ae,
exact h
end
lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h
lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f)
(htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] }
lemma integral_on_union_ae (hs : measurable_set s) (ht : measurable_set t) (hsm : measurable_on s f)
(hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f)
(h : ∀ᵐ a, a ∉ s ∩ t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
begin
have := integral_congr_ae _ _ (indicator_union_ae h f),
rw [this, integral_add hsm hsi htm hti],
{ exact hsm.union hs ht htm },
{ exact measurable.add hsm htm }
end
lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h }
lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_on_nonneg_of_ae $ univ_mem_sets' hf
lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h }
lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_on_nonpos_of_ae $ univ_mem_sets' hf
lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, measurable_set (s i))
(h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) :=
let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, exact hfm.subset (hsm i) (subset_Union _ _) },
{ assumption },
{ show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) }
end
lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, measurable_set (s i))
(h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) :=
let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) },
{ exact hfm.subset (measurable_set.Inter hsm) (Inter_subset _ _) },
{ show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) }
end
-- TODO : prove this for an encodable type
-- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat `
lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, measurable_set (s i))
(hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f)
(hfi : integrable_on (Union s) f) :
(∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a :=
suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)),
by { rwa has_sum.tsum_eq },
begin
have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a,
{ funext,
rw [← integral_finset_sum, indicator_finset_bUnion],
{ assume i hi j hj hij, exact hd i j hij },
{ assume i, refine hfm.subset (hm _) (subset_Union _ _) },
{ assume i, refine hfi.subset (subset_Union _ _) } },
rw this,
refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _,
{ exact indicator (Union s) (λ a, ∥f a∥) },
{ exact is_countably_generated_at_top_finset_nat },
{ refine univ_mem_sets' (λ n, _),
simp only [mem_set_of_eq],
refine hfm.subset (measurable_set.Union (λ i, measurable_set.Union_Prop (λh, hm _)))
(bUnion_subset_Union _ _), },
{ assumption },
{ refine univ_mem_sets' (λ n, univ_mem_sets' $ _),
simp only [mem_set_of_eq],
assume a,
rw ← norm_indicator_eq_indicator_norm,
refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ },
{ rw [← integrable_on, integrable_on_norm_iff], assumption },
{ filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) }
end
end integral_on
-/
|
f89a49ddff1d9228941d3564fef780cc700c4ad1 | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/vrel/inv.lean | c3c3b5b37e3b43dd7f5a7bf737f0f23018dfceb9 | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 1,135 | lean | /-
This file contains declarations related to `vrel` inversion or symmetry.
-/
import .id
namespace acie -----------------------------------------------------------------
namespace vrel -----------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {vs : Type → Type} [vset vs V] -- Type of variable name sets
variables {X Y : vs V} -- Variable name sets
variables {R : X ×ν Y} -- Variable name set relations
variables {x : ν∈ X} {y : ν∈ Y} -- Variable name set members
-- `inv R` inverts the order of the relation `R`.
@[reducible]
def inv : X ×ν Y → Y ×ν X :=
-- An alternative def for this is `function.swap`; however, that does
-- not unfold as easily as the explicit lambda.
λ R y x, ⟪x, y⟫ ∈ν R
-- Notation for `inv`.
postfix `°`:std.prec.max_plus := inv
@[reducible]
protected
theorem symm : ⟪x, y⟫ ∈ν R → ⟪y, x⟫ ∈ν R° :=
λ m, m
end /- namespace -/ vrel -------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
e6d0088aa3b9d54ab3505f088dc6d6957e6fda76 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/computability/language.lean | 7ca703ebd66f6c0c7926d398ca40daa26384f9f1 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,075 | 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 data.finset.basic
/-!
# Languages
This file contains the definition and operations on formal languages over an alphabet. Note strings
are implemented as lists over the alphabet.
The operations in this file define a [Kleene algebra](https://en.wikipedia.org/wiki/Kleene_algebra)
over the languages.
-/
universes u v
variables {α : Type u} [dec : decidable_eq α]
/-- A language is a set of strings over an alphabet. -/
@[derive [has_mem (list α), has_singleton (list α), has_insert (list α), complete_lattice]]
def language (α) := set (list α)
namespace language
local attribute [reducible] language
instance : has_zero (language α) := ⟨(∅ : set _)⟩
instance : has_one (language α) := ⟨{[]}⟩
instance : inhabited (language α) := ⟨0⟩
instance : has_add (language α) := ⟨set.union⟩
instance : has_mul (language α) := ⟨λ l m, (l.prod m).image (λ p, p.1 ++ p.2)⟩
lemma zero_def : (0 : language α) = (∅ : set _) := rfl
lemma one_def : (1 : language α) = {[]} := rfl
lemma add_def (l m : language α) : l + m = l ∪ m := rfl
lemma mul_def (l m : language α) : l * m = (l.prod m).image (λ p, p.1 ++ p.2) := rfl
/-- The star of a language `L` is the set of all strings which can be written by concatenating
strings from `L`. -/
def star (l : language α) : language α :=
{ x | ∃ S : list (list α), x = S.join ∧ ∀ y ∈ S, y ∈ l}
lemma star_def (l : language α) :
l.star = { x | ∃ S : list (list α), x = S.join ∧ ∀ y ∈ S, y ∈ l} := rfl
@[simp] lemma mem_one (x : list α) : x ∈ (1 : language α) ↔ x = [] := by refl
@[simp] lemma mem_add (l m : language α) (x : list α) : x ∈ l + m ↔ x ∈ l ∨ x ∈ m :=
by simp [add_def]
lemma mem_mul (l m : language α) (x : list α) : x ∈ l * m ↔ ∃ a b, a ∈ l ∧ b ∈ m ∧ a ++ b = x :=
by simp [mul_def]
lemma mem_star (l : language α) (x : list α) :
x ∈ l.star ↔ ∃ S : list (list α), x = S.join ∧ ∀ y ∈ S, y ∈ l :=
by refl
private lemma mul_assoc_lang (l m n : language α) : (l * m) * n = l * (m * n) :=
by { ext x, simp [mul_def], tauto {closer := `[subst_vars, simp *] } }
private lemma one_mul_lang (l : language α) : 1 * l = l :=
by { ext x, simp [mul_def, one_def], tauto {closer := `[subst_vars, simp [*]] } }
private lemma mul_one_lang (l : language α) : l * 1 = l :=
by { ext x, simp [mul_def, one_def], tauto {closer := `[subst_vars, simp *] } }
private lemma left_distrib_lang (l m n : language α) : l * (m + n) = (l * m) + (l * n) :=
begin
ext x,
simp only [mul_def, add_def, exists_and_distrib_left, set.mem_image2, set.image_prod,
set.mem_image, set.mem_prod, set.mem_union_eq, set.prod_union, prod.exists],
split,
{ rintro ⟨ y, z, (⟨ hy, hz ⟩ | ⟨ hy, hz ⟩), hx ⟩,
{ left,
exact ⟨ y, hy, z, hz, hx ⟩ },
{ right,
exact ⟨ y, hy, z, hz, hx ⟩ } },
{ rintro (⟨ y, hy, z, hz, hx ⟩ | ⟨ y, hy, z, hz, hx ⟩);
refine ⟨ y, z, _, hx ⟩,
{ left,
exact ⟨ hy, hz ⟩ },
{ right,
exact ⟨ hy, hz ⟩ } }
end
private lemma right_distrib_lang (l m n : language α) : (l + m) * n = (l * n) + (m * n) :=
begin
ext x,
simp only [mul_def, set.mem_image, add_def, set.mem_prod, exists_and_distrib_left, set.mem_image2,
set.image_prod, set.mem_union_eq, set.prod_union, prod.exists],
split,
{ rintro ⟨ y, (hy | hy), z, hz, hx ⟩,
{ left,
exact ⟨ y, hy, z, hz, hx ⟩ },
{ right,
exact ⟨ y, hy, z, hz, hx ⟩ } },
{ rintro (⟨ y, hy, z, hz, hx ⟩ | ⟨ y, hy, z, hz, hx ⟩);
refine ⟨ y, _, z, hz, hx ⟩,
{ left,
exact hy },
{ right,
exact hy } }
end
instance : semiring (language α) :=
{ add := (+),
add_assoc := by simp [add_def, set.union_assoc],
zero := 0,
zero_add := by simp [zero_def, add_def],
add_zero := by simp [zero_def, add_def],
add_comm := by simp [add_def, set.union_comm],
mul := (*),
mul_assoc := mul_assoc_lang,
zero_mul := by simp [zero_def, mul_def],
mul_zero := by simp [zero_def, mul_def],
one := 1,
one_mul := one_mul_lang,
mul_one := mul_one_lang,
left_distrib := left_distrib_lang,
right_distrib := right_distrib_lang }
@[simp] lemma add_self (l : language α) : l + l = l := sup_idem
lemma star_def_nonempty (l : language α) :
l.star = { x | ∃ S : list (list α), x = S.join ∧ ∀ y ∈ S, y ∈ l ∧ y ≠ []} :=
begin
ext x,
rw star_def,
split,
{ rintro ⟨ S, hx, h ⟩,
refine ⟨ S.filter (λ l, ¬list.empty l), _, _ ⟩,
{ rw hx,
induction S with y S ih generalizing x,
{ refl },
{ rw list.filter,
cases y with a y,
{ apply ih,
{ intros y hy,
apply h,
rw list.mem_cons_iff,
right,
assumption },
{ refl } },
{ simp only [true_and, list.join, eq_ff_eq_not_eq_tt, if_true, list.cons_append,
list.empty, eq_self_iff_true],
rw list.append_right_inj,
simp only [eq_ff_eq_not_eq_tt, forall_eq] at ih,
apply ih,
intros y hy,
apply h,
rw list.mem_cons_iff,
right,
assumption } } },
{ intros y hy,
simp only [eq_ff_eq_not_eq_tt, list.mem_filter] at hy,
finish } },
{ rintro ⟨ S, hx, h ⟩,
refine ⟨ S, hx, _ ⟩,
finish }
end
lemma le_iff (l m : language α) : l ≤ m ↔ l + m = m := sup_eq_right.symm
lemma le_mul_congr {l₁ l₂ m₁ m₂ : language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ * l₂ ≤ m₁ * m₂ :=
begin
intros h₁ h₂ x hx,
simp only [mul_def, exists_and_distrib_left, set.mem_image2, set.image_prod] at hx ⊢,
tauto
end
lemma le_add_congr {l₁ l₂ m₁ m₂ : language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ + l₂ ≤ m₁ + m₂ := sup_le_sup
lemma supr_mul {ι : Sort v} (l : ι → language α) (m : language α) :
(⨆ i, l i) * m = ⨆ i, l i * m :=
begin
ext x,
simp only [mem_mul, set.mem_Union, exists_and_distrib_left],
tauto
end
lemma mul_supr {ι : Sort v} (l : ι → language α) (m : language α) :
m * (⨆ i, l i) = ⨆ i, m * l i :=
begin
ext x,
simp only [mem_mul, set.mem_Union, exists_and_distrib_left],
tauto
end
lemma supr_add {ι : Sort v} [nonempty ι] (l : ι → language α) (m : language α) :
(⨆ i, l i) + m = ⨆ i, l i + m := supr_sup
lemma add_supr {ι : Sort v} [nonempty ι] (l : ι → language α) (m : language α) :
m + (⨆ i, l i) = ⨆ i, m + l i := sup_supr
lemma star_eq_supr_pow (l : language α) : l.star = ⨆ i : ℕ, l ^ i :=
begin
ext x,
simp only [star_def, set.mem_Union, set.mem_set_of_eq],
split,
{ revert x,
rintros _ ⟨ S, rfl, hS ⟩,
induction S with x S ih,
{ use 0,
tauto },
{ specialize ih _,
{ cases ih with i ih,
use i.succ,
rw [pow_succ, mem_mul],
exact ⟨ x, S.join, hS x (list.mem_cons_self _ _), ih, rfl ⟩ },
{ exact λ y hy, hS _ (list.mem_cons_of_mem _ hy) } } },
{ rintro ⟨ i, hx ⟩,
induction i with i ih generalizing x,
{ rw [pow_zero, mem_one] at hx,
subst hx,
use [[]],
tauto },
{ rw [pow_succ, mem_mul] at hx,
rcases hx with ⟨ a, b, ha, hb, hx ⟩,
rcases ih b hb with ⟨ S, hb, hS ⟩,
use a :: S,
rw list.join,
refine ⟨hb ▸ hx.symm, λ y, or.rec (λ hy, _) (hS _)⟩,
exact hy.symm ▸ ha } }
end
lemma mul_self_star_comm (l : language α) : l.star * l = l * l.star :=
by simp [star_eq_supr_pow, mul_supr, supr_mul, ← pow_succ, ← pow_succ']
@[simp] lemma one_add_self_mul_star_eq_star (l : language α) : 1 + l * l.star = l.star :=
begin
rw [star_eq_supr_pow, mul_supr, add_def, supr_split_single (λ i, l ^ i) 0],
have h : (⨆ (i : ℕ), l * l ^ i) = ⨆ (i : ℕ) (h : i ≠ 0), (λ (i : ℕ), l ^ i) i,
{ ext x,
simp only [exists_prop, set.mem_Union, ne.def],
split,
{ rintro ⟨ i, hi ⟩,
use [i.succ, nat.succ_ne_zero i],
rwa pow_succ },
{ rintro ⟨ (_ | i), h0, hi ⟩,
{ contradiction },
use i,
rwa ←pow_succ } },
rw h,
refl
end
@[simp] lemma one_add_star_mul_self_eq_star (l : language α) : 1 + l.star * l = l.star :=
by rw [mul_self_star_comm, one_add_self_mul_star_eq_star]
lemma star_mul_le_right_of_mul_le_right (l m : language α) : l * m ≤ m → l.star * m ≤ m :=
begin
intro h,
rw [star_eq_supr_pow, supr_mul],
refine supr_le _,
intro n,
induction n with n ih,
{ simp },
rw [pow_succ', mul_assoc (l^n) l m],
exact le_trans (le_mul_congr (le_refl _) h) ih,
end
lemma star_mul_le_left_of_mul_le_left (l m : language α) : m * l ≤ m → m * l.star ≤ m :=
begin
intro h,
rw [star_eq_supr_pow, mul_supr],
refine supr_le _,
intro n,
induction n with n ih,
{ simp },
rw [pow_succ, ←mul_assoc m l (l^n)],
exact le_trans (le_mul_congr h (le_refl _)) ih
end
end language
|
35661e2b76699bf83ef0a57b02ff8bef54f8d20b | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_1583.lean | f02b02a7cb77f521198aa19124b4ccb861be65e5 | [] | 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 | 272 | lean | import data.real.basic
-- BEGIN
example {x y : ℝ} (h : x ≤ y ∧ x ≠ y) : ¬ y ≤ x :=
begin
intro h',
apply h.right,
exact le_antisymm h.left h'
end
example {x y : ℝ} (h : x ≤ y ∧ x ≠ y) : ¬ y ≤ x :=
λ h', h.right (le_antisymm h.left h')
-- END |
bbc04b21ea215624092ce665a9265b03e6587e8a | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/ring_theory/discrete_valuation_ring.lean | a9c6d926ddcfcb5c3c9db8a0d54464e8ad7943a3 | [
"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 | 13,441 | lean | /-
Copyright (c) 2020 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard
-/
import ring_theory.principal_ideal_domain order.conditionally_complete_lattice
import ring_theory.multiplicity
import ring_theory.valuation.basic
import tactic
/-!
# Discrete valuation rings
This file defines discrete valuation rings (DVRs) and develops a basic interface
for them.
## Important definitions
There are various definitions of a DVR in the literature; we define a DVR to be a local PID
which is not a field (the first definition in Wikipedia) and prove that this is equivalent
to being a PID with a unique non-zero prime ideal (the definition in Serre's
book "Local Fields").
Let R be an integral domain, assumed to be a principal ideal ring and a local ring.
* `discrete_valuation_ring R` : a predicate expressing that R is a DVR
### Definitions
## Implementation notes
It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible.
We do not hence define `uniformizer` at all, because we can use `irreducible` instead.
## Tags
discrete valuation ring
-/
open_locale classical
universe u
open ideal local_ring
/-- An integral domain is a discrete valuation ring if it's a local PID which is not a field -/
class discrete_valuation_ring (R : Type u) [integral_domain R]
extends is_principal_ideal_ring R, local_ring R : Prop :=
(not_a_field' : maximal_ideal R ≠ ⊥)
namespace discrete_valuation_ring
variables (R : Type u) [integral_domain R] [discrete_valuation_ring R]
lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field'
variable {R}
open principal_ideal_ring
/-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the
maximal ideal of R -/
theorem irreducible_iff_uniformizer (ϖ : R) :
irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} :=
⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm,
begin
intro h,
have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R,
from h.symm ▸ submodule.mem_span_singleton_self ϖ,
refine ⟨h2, _⟩,
intros a b hab,
by_contra h,
push_neg at h,
obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h,
rw h at ha hb,
rw mem_span_singleton' at ha hb,
rcases ha with ⟨a, rfl⟩,
rcases hb with ⟨b, rfl⟩,
rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab,
have h3 := eq_zero_of_mul_eq_self_right _ hab.symm,
{ apply not_a_field R,
simp [h, h3] },
{ intro hh, apply h2,
refine is_unit_of_dvd_one ϖ _,
use a * b, exact hh.symm }
end⟩
variable (R)
/-- Uniformisers exist in a DVR -/
theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ :=
by {simp_rw [irreducible_iff_uniformizer],
exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal}
/-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/
theorem iff_pid_with_one_nonzero_prime (R : Type u) [integral_domain R] :
discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P :=
begin
split,
{ intro RDVR,
rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩,
split, assumption,
resetI,
use local_ring.maximal_ideal R,
split, split,
{ assumption },
{ apply_instance } ,
{ rintro Q ⟨hQ1, hQ2⟩,
obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1,
have hq : q ≠ 0,
{ rintro rfl,
apply hQ1,
simp },
erw span_singleton_prime hq at hQ2,
replace hQ2 := irreducible_of_prime hQ2,
rw irreducible_iff_uniformizer at hQ2,
exact hQ2.symm } },
{ rintro ⟨RPID, Punique⟩,
haveI : local_ring R := local_of_unique_nonzero_prime R Punique,
refine {not_a_field' := _},
rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩,
have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1),
intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM }
end
lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) :
associated a b :=
begin
rw irreducible_iff_uniformizer at ha hb,
rw [←span_singleton_eq_span_singleton, ←ha, hb],
end
end discrete_valuation_ring
namespace discrete_valuation_ring
variable (R : Type*)
/-- Alternative characterisation of discrete valuation rings. -/
def has_unit_mul_pow_irreducible_factorization [integral_domain R] : Prop :=
∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x
namespace has_unit_mul_pow_irreducible_factorization
variables {R} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R)
include hR
lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) :
associated p q :=
begin
rcases hR with ⟨ϖ, hϖ, hR⟩,
suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ,
{ apply associated.trans (this hp) (this hq).symm, },
clear hp hq p q,
intros p hp,
obtain ⟨n, hn⟩ := hR hp.ne_zero,
have : irreducible (ϖ ^ n) := irreducible_of_associated hn.symm hp,
rcases lt_trichotomy n 1 with (H|rfl|H),
{ obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial },
simpa only [not_irreducible_one, pow_zero] using this, },
{ simpa only [pow_one] using hn.symm, },
{ obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H,
rw pow_succ at this,
rcases this.2 _ _ rfl with H0|H0,
{ exact (hϖ.not_unit H0).elim, },
{ rw [add_comm, pow_succ] at H0,
exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } }
end
/-- Implementation detail: an integral domain in which there is a unit `p`
such that every nonzero element is associated to a power of `p` is a unique factorization domain.
See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/
noncomputable def ufd : unique_factorization_domain R :=
let p := classical.some hR in
let spec := classical.some_spec hR in
{ factors := λ x, if h : x = 0 then 0 else multiset.repeat p (classical.some (spec.2 h)),
factors_prod := λ x hx,
by { rw [dif_neg hx, multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), },
prime_factors :=
begin
intros x hx q hq,
rw dif_neg hx at hq,
have hpq := multiset.eq_of_mem_repeat hq,
rw hpq,
refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩,
intros a b h,
by_cases ha : a = 0,
{ rw ha, simp only [true_or, dvd_zero], },
by_cases hb : b = 0,
{ rw hb, simp only [or_true, dvd_zero], },
obtain ⟨m, u, rfl⟩ := spec.2 ha,
rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (is_unit_unit _)] at h,
rw is_unit.dvd_mul_right (is_unit_unit _),
by_cases hm : m = 0,
{ simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h },
left,
obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm,
apply dvd_mul_of_dvd_left (dvd_refl _) _,
end }
omit hR
lemma of_ufd_of_unique_irreducible [unique_factorization_domain R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
has_unit_mul_pow_irreducible_factorization R :=
begin
obtain ⟨p, hp⟩ := h₁,
refine ⟨p, hp, _⟩,
intros x hx,
refine ⟨(unique_factorization_domain.factors x).card, _⟩,
have H := unique_factorization_domain.factors_prod hx,
rw ← associates.mk_eq_mk_iff_associated at H ⊢,
rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat],
congr' 1,
symmetry,
rw multiset.eq_repeat,
simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true,
multiset.mem_map, exists_imp_distrib],
rintros _ q hq rfl,
rw associates.mk_eq_mk_iff_associated,
apply h₂ (unique_factorization_domain.irreducible_factors hx _ hq) hp,
end
end has_unit_mul_pow_irreducible_factorization
lemma aux_pid_of_ufd_of_unique_irreducible
(R : Type u) [integral_domain R] [unique_factorization_domain R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
is_principal_ideal_ring R :=
begin
constructor,
intro I,
by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], },
obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0,
obtain ⟨p, hp, H⟩ :=
has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂,
have ex : ∃ n : ℕ, p ^ n ∈ I,
{ obtain ⟨n, u, rfl⟩ := H hx0,
refine ⟨n, _⟩,
simpa only [units.mul_inv_cancel_right] using @ideal.mul_mem_right _ _ I _ ↑u⁻¹ hxI, },
constructor,
use p ^ (nat.find ex),
show I = ideal.span _,
apply le_antisymm,
{ intros r hr,
by_cases hr0 : r = 0,
{ simp only [hr0, submodule.zero_mem], },
obtain ⟨n, u, rfl⟩ := H hr0,
simp only [mem_span_singleton, is_unit_unit, is_unit.dvd_mul_right],
apply pow_dvd_pow,
apply nat.find_min',
simpa only [units.mul_inv_cancel_right] using @ideal.mul_mem_right _ _ I _ ↑u⁻¹ hr, },
{ erw submodule.span_singleton_le_iff_mem,
exact nat.find_spec ex, },
end
/--
A unique factorization domain with at least one irreducible element
in which all irreducible elements are associated
is a discrete valuation ring.
-/
lemma of_ufd_of_unique_irreducible {R : Type u} [integral_domain R] [unique_factorization_domain R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
discrete_valuation_ring R :=
begin
rw iff_pid_with_one_nonzero_prime,
haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂,
obtain ⟨p, hp⟩ := h₁,
refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩,
{ rw submodule.ne_bot_iff,
refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, },
{ rwa [ideal.span_singleton_prime hp.ne_zero,
← unique_factorization_domain.irreducible_iff_prime], },
{ intro I,
rw ← submodule.is_principal.span_singleton_generator I,
rintro ⟨I0, hI⟩,
apply span_singleton_eq_span_singleton.mpr,
apply h₂ _ hp,
erw [ne.def, span_singleton_eq_bot] at I0,
rwa [unique_factorization_domain.irreducible_iff_prime, ← ideal.span_singleton_prime I0], },
end
/--
An integral domain in which there is a unit `p`
such that every nonzero element is associated to a power of `p`
is a discrete valuation ring.
-/
lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [integral_domain R]
(hR : has_unit_mul_pow_irreducible_factorization R) :
discrete_valuation_ring R :=
begin
letI : unique_factorization_domain R := hR.ufd,
apply of_ufd_of_unique_irreducible _ hR.unique_irreducible,
unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, },
end
section
variables [integral_domain R] [discrete_valuation_ring R]
variable {R}
lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) :
∃ (n : ℕ), associated x (ϖ ^ n) :=
begin
have : unique_factorization_domain R := principal_ideal_ring.to_unique_factorization_domain,
unfreezingI { use (unique_factorization_domain.factors x).card },
have H := unique_factorization_domain.factors_prod hx,
rw ← associates.mk_eq_mk_iff_associated at H ⊢,
rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat],
congr' 1,
rw multiset.eq_repeat,
simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true,
multiset.mem_map, exists_imp_distrib],
rintros _ _ _ rfl,
rw associates.mk_eq_mk_iff_associated,
refine associated_of_irreducible _ _ hirr,
apply unique_factorization_domain.irreducible_factors hx,
assumption
end
open submodule.is_principal
lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) :
∃ n : ℕ, s = ideal.span {ϖ ^ n} :=
begin
have gen_ne_zero : generator s ≠ 0,
{ rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption },
rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩,
use n,
have : span _ = _ := span_singleton_generator s,
rw [← this, ← hnu, span_singleton_eq_span_singleton],
use u
end
lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q)
(u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) :
m = n :=
begin
have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod,
{ rw [multiset.prod_repeat, multiset.prod_repeat, associated],
refine ⟨u * v⁻¹, _⟩,
simp only [units.coe_mul],
rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], },
letI := @principal_ideal_ring.to_unique_factorization_domain R _ _,
have := multiset.card_eq_card_of_rel (unique_factorization_domain.unique _ _ key),
{ simpa only [multiset.card_repeat] },
all_goals
{ intros x hx, replace hx := multiset.eq_of_mem_repeat hx,
unfreezingI { subst hx, assumption } },
end
lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ)
(h : ↑u * ϖ ^ m = v * ϖ ^ n) :
u = v :=
begin
obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h,
rw ← sub_eq_zero at h,
rw [← sub_mul, mul_eq_zero] at h,
cases h,
{ rw sub_eq_zero at h, exact_mod_cast h },
{ apply (hirr.ne_zero (pow_eq_zero h)).elim, }
end
end
end discrete_valuation_ring
|
1032c8da4345b379bf78d83771c0abe43ee4a2d9 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/limits/shapes/biproducts.lean | eae93103cd06ca1f73a764768f11ecc539d88a70 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 18,951 | 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 category_theory.epi_mono
import category_theory.limits.shapes.binary_products
import category_theory.preadditive
/-!
# Biproducts and binary biproducts
We introduce the notion of biproducts and binary biproducts.
These are slightly unusual relative to the other shapes in the library,
as they are simultaneously limits and colimits.
(Zero objects are similar; they are "biterminal".)
We model these here using a `bicone`, with a cone point `X`,
and natural transformations `π` from the constant functor with value `X` to `F`
and `ι` in the other direction.
We implement `has_bilimit` as a `bicone`, equipped with the evidence
`is_limit bicone.to_cone` and `is_colimit bicone.to_cocone`.
In practice, of course, we are only interested in the special case of bilimits
over `discrete J` for `[fintype J] [decidable_eq J]`,
which corresponds to finite biproducts.
TODO: We should provide a constructor that takes `has_limit F`, `has_colimit F`, and
and iso `limit F ≅ colimit F`, and produces `has_bilimit F`.
TODO: perhaps it makes sense to unify the treatment of zero objects with this a bit.
In addition to biproducts and binary biproducts, we define the notion of preadditive binary
biproduct, which is a preadditive version of binary biproducts. We show that a preadditive binary
biproduct is a binary biproduct and construct preadditive binary biproducts both from binary
products and from binary coproducts.
## Notation
As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for
a binary biproduct. We introduce `⨁ f` for the indexed biproduct.
-/
universes v u
open category_theory
open category_theory.functor
namespace category_theory.limits
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
/--
A `c : bicone F` is:
* an object `c.X` and
* a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`.
* a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor.
-/
@[nolint has_inhabited_instance]
structure bicone {J : Type v} [small_category J] (F : J ⥤ C) :=
(X : C)
(π : (const J).obj X ⟶ F)
(ι : F ⟶ (const J).obj X)
variables {F : J ⥤ C}
namespace bicone
/-- Extract the cone from a bicone. -/
@[simps]
def to_cone (B : bicone F) : cone F :=
{ .. B }
/-- Extract the cocone from a bicone. -/
@[simps]
def to_cocone (B : bicone F) : cocone F :=
{ .. B }
end bicone
/--
`has_bilimit F` represents a particular chosen bicone which is
simultaneously a limit and a colimit of the diagram `F`.
(This is only interesting when the source category is discrete.)
-/
class has_bilimit (F : J ⥤ C) :=
(bicone : bicone F)
(is_limit : is_limit bicone.to_cone)
(is_colimit : is_colimit bicone.to_cocone)
@[priority 100]
instance has_limit_of_has_bilimit [has_bilimit F] : has_limit F :=
{ cone := has_bilimit.bicone.to_cone,
is_limit := has_bilimit.is_limit, }
@[priority 100]
instance has_colimit_of_has_bilimit [has_bilimit F] : has_colimit F :=
{ cocone := has_bilimit.bicone.to_cocone,
is_colimit := has_bilimit.is_colimit, }
variables (J C)
/--
`C` has bilimits of shape `J` if we have chosen
a particular limit and a particular colimit, with the same cone points,
of every functor `F : J ⥤ C`.
(This is only interesting if `J` is discrete.)
-/
class has_bilimits_of_shape :=
(has_bilimit : Π F : J ⥤ C, has_bilimit F)
attribute [instance, priority 100] has_bilimits_of_shape.has_bilimit
@[priority 100]
instance [has_bilimits_of_shape J C] : has_limits_of_shape J C :=
{ has_limit := λ F, by apply_instance }
@[priority 100]
instance [has_bilimits_of_shape J C] : has_colimits_of_shape J C :=
{ has_colimit := λ F, by apply_instance }
/-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C`
indexed by a finite type with decidable equality. -/
class has_finite_biproducts :=
(has_bilimits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J],
has_bilimits_of_shape.{v} (discrete J) C)
attribute [instance] has_finite_biproducts.has_bilimits_of_shape
/--
The isomorphism between the specified limit and the specified colimit for
a functor with a bilimit.
-/
def biproduct_iso {J : Type v} (F : J → C) [has_bilimit (functor.of_function F)] :
limits.pi_obj F ≅ limits.sigma_obj F :=
eq_to_iso rfl
end category_theory.limits
namespace category_theory.limits
variables {J : Type v}
variables {C : Type u} [category.{v} C]
/-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an
abbreviation for `limit (functor.of_function f)`, so for most facts about `biproduct f`, you will
just use general facts about limits and colimits.) -/
abbreviation biproduct (f : J → C) [has_bilimit (functor.of_function f)] :=
limit (functor.of_function f)
notation `⨁ ` f:20 := biproduct f
/-- The projection onto a summand of a biproduct. -/
abbreviation biproduct.π (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : ⨁ f ⟶ f b :=
limit.π (functor.of_function f) b
/-- The inclusion into a summand of a biproduct. -/
abbreviation biproduct.ι (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : f b ⟶ ⨁ f :=
colimit.ι (functor.of_function f) b
/-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/
abbreviation biproduct.lift
{f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f :=
limit.lift _ (fan.mk p)
/-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/
abbreviation biproduct.desc
{f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P :=
colimit.desc _ (cofan.mk p)
/-- Given a collection of maps between corresponding summands of a pair of biproducts
indexed by the same type, we obtain a map betweeen the biproducts. -/
abbreviation biproduct.map [fintype J] [decidable_eq J] {f g : J → C} [has_finite_biproducts.{v} C]
(p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g :=
(@lim (discrete J) _ C _ _).map (nat_trans.of_function p)
instance biproduct.ι_mono [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)]
(b : J) : split_mono (biproduct.ι f b) :=
{ retraction := biproduct.desc $
λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b }
instance biproduct.π_epi [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)]
(b : J) : split_epi (biproduct.π f b) :=
{ section_ := biproduct.lift $
λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' }
variables {C}
/--
A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`,
maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`.
-/
@[nolint has_inhabited_instance]
structure binary_bicone (P Q : C) :=
(X : C)
(π₁ : X ⟶ P)
(π₂ : X ⟶ Q)
(ι₁ : P ⟶ X)
(ι₂ : Q ⟶ X)
namespace binary_bicone
variables {P Q : C}
/-- Extract the cone from a binary bicone. -/
@[simp]
def to_cone (c : binary_bicone.{v} P Q) : cone (pair P Q) :=
binary_fan.mk c.π₁ c.π₂
/-- Extract the cocone from a binary bicone. -/
@[simp]
def to_cocone (c : binary_bicone.{v} P Q) : cocone (pair P Q) :=
binary_cofan.mk c.ι₁ c.ι₂
end binary_bicone
/--
`has_binary_biproduct P Q` represents a particular chosen bicone which is
simultaneously a limit and a colimit of the diagram `pair P Q`.
-/
class has_binary_biproduct (P Q : C) :=
(bicone : binary_bicone.{v} P Q)
(is_limit : is_limit bicone.to_cone)
(is_colimit : is_colimit bicone.to_cocone)
section
variable (C)
/--
`has_binary_biproducts C` represents a particular chosen bicone which is
simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`.
-/
class has_binary_biproducts :=
(has_binary_biproduct : Π (P Q : C), has_binary_biproduct.{v} P Q)
attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct
end
variables {P Q : C}
instance has_binary_biproduct.has_limit_pair [has_binary_biproduct.{v} P Q] :
has_limit (pair P Q) :=
{ cone := has_binary_biproduct.bicone.to_cone,
is_limit := has_binary_biproduct.is_limit.{v}, }
instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct.{v} P Q] :
has_colimit (pair P Q) :=
{ cocone := has_binary_biproduct.bicone.to_cocone,
is_colimit := has_binary_biproduct.is_colimit.{v}, }
@[priority 100]
instance has_limits_of_shape_walking_pair [has_binary_biproducts.{v} C] :
has_limits_of_shape.{v} (discrete walking_pair) C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm }
@[priority 100]
instance has_colimits_of_shape_walking_pair [has_binary_biproducts.{v} C] :
has_colimits_of_shape.{v} (discrete walking_pair) C :=
{ has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) }
@[priority 100]
instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts.{v} C] :
has_binary_products.{v} C :=
⟨by apply_instance⟩
@[priority 100]
instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts.{v} C] :
has_binary_coproducts.{v} C :=
⟨by apply_instance⟩
/--
The isomorphism between the specified binary product and the specified binary coproduct for
a pair for a binary biproduct.
-/
def biprod_iso (X Y : C) [has_binary_biproduct.{v} X Y] :
limits.prod X Y ≅ limits.coprod X Y :=
eq_to_iso rfl
/-- The chosen biproduct of a pair of objects. -/
abbreviation biprod (X Y : C) [has_binary_biproduct.{v} X Y] := limit (pair X Y)
notation X ` ⊞ `:20 Y:20 := biprod X Y
/-- The projection onto the first summand of a binary biproduct. -/
abbreviation biprod.fst {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ X :=
limit.π (pair X Y) walking_pair.left
/-- The projection onto the second summand of a binary biproduct. -/
abbreviation biprod.snd {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ Y :=
limit.π (pair X Y) walking_pair.right
/-- The inclusion into the first summand of a binary biproduct. -/
abbreviation biprod.inl {X Y : C} [has_binary_biproduct.{v} X Y] : X ⟶ X ⊞ Y :=
colimit.ι (pair X Y) walking_pair.left
/-- The inclusion into the second summand of a binary biproduct. -/
abbreviation biprod.inr {X Y : C} [has_binary_biproduct.{v} X Y] : Y ⟶ X ⊞ Y :=
colimit.ι (pair X Y) walking_pair.right
/-- Given a pair of maps into the summands of a binary biproduct,
we obtain a map into the binary biproduct. -/
abbreviation biprod.lift {W X Y : C} [has_binary_biproduct.{v} X Y] (f : W ⟶ X) (g : W ⟶ Y) :
W ⟶ X ⊞ Y :=
limit.lift _ (binary_fan.mk f g)
/-- Given a pair of maps out of the summands of a binary biproduct,
we obtain a map out of the binary biproduct. -/
abbreviation biprod.desc {W X Y : C} [has_binary_biproduct.{v} X Y] (f : X ⟶ W) (g : Y ⟶ W) :
X ⊞ Y ⟶ W :=
colimit.desc _ (binary_cofan.mk f g)
/-- Given a pair of maps between the summands of a pair of binary biproducts,
we obtain a map between the binary biproducts. -/
abbreviation biprod.map {W X Y Z : C} [has_binary_biproducts.{v} C]
(f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z :=
(@lim (discrete walking_pair) _ C _ _).map (@map_pair _ _ (pair W X) (pair Y Z) f g)
instance biprod.inl_mono {X Y : C} [has_binary_biproduct.{v} X Y] :
split_mono (biprod.inl : X ⟶ X ⊞ Y) :=
{ retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) }
instance biprod.inr_mono {X Y : C} [has_binary_biproduct.{v} X Y] :
split_mono (biprod.inr : Y ⟶ X ⊞ Y) :=
{ retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)}
instance biprod.fst_epi {X Y : C} [has_binary_biproduct.{v} X Y] :
split_epi (biprod.fst : X ⊞ Y ⟶ X) :=
{ section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) }
instance biprod.snd_epi {X Y : C} [has_binary_biproduct.{v} X Y] :
split_epi (biprod.snd : X ⊞ Y ⟶ Y) :=
{ section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) }
@[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct.{v} X Y] (f g : Z ⟶ X ⊞ Y)
(h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g :=
binary_fan.is_limit.hom_ext has_binary_biproduct.is_limit h₀ h₁
@[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct.{v} X Y] (f g : X ⊞ Y ⟶ Z)
(h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g :=
binary_cofan.is_colimit.hom_ext has_binary_biproduct.is_colimit h₀ h₁
-- TODO:
-- If someone is interested, they could provide the constructions:
-- has_binary_biproducts ↔ has_finite_biproducts
section preadditive
variables [preadditive.{v} C]
open category_theory.preadditive
/-- A preadditive binary biproduct is a bicone on two objects `X` and `Y` satisfying a set of five
axioms expressing the properties of a biproduct in additive terms. The notion of preadditive
binary biproduct is strictly stronger than the notion of binary biproduct (but it in any
preadditive category, the existence of a binary biproduct implies the existence of a
preadditive binary biproduct: a biproduct is, in particular, a product, and every product gives
rise to a preadditive binary biproduct, see `has_preadditive_binary_biproduct.of_has_limit_pair`). -/
class has_preadditive_binary_biproduct (X Y : C) :=
(bicone : binary_bicone.{v} X Y)
(ι₁_π₁' : bicone.ι₁ ≫ bicone.π₁ = 𝟙 X . obviously)
(ι₂_π₂' : bicone.ι₂ ≫ bicone.π₂ = 𝟙 Y . obviously)
(ι₂_π₁' : bicone.ι₂ ≫ bicone.π₁ = 0 . obviously)
(ι₁_π₂' : bicone.ι₁ ≫ bicone.π₂ = 0 . obviously)
(total' : bicone.π₁ ≫ bicone.ι₁ + bicone.π₂ ≫ bicone.ι₂ = 𝟙 bicone.X . obviously)
restate_axiom has_preadditive_binary_biproduct.ι₁_π₁'
restate_axiom has_preadditive_binary_biproduct.ι₂_π₂'
restate_axiom has_preadditive_binary_biproduct.ι₂_π₁'
restate_axiom has_preadditive_binary_biproduct.ι₁_π₂'
restate_axiom has_preadditive_binary_biproduct.total'
attribute [simp, reassoc] has_preadditive_binary_biproduct.ι₁_π₁
has_preadditive_binary_biproduct.ι₂_π₂ has_preadditive_binary_biproduct.ι₂_π₁
has_preadditive_binary_biproduct.ι₁_π₂
attribute [simp] has_preadditive_binary_biproduct.total
section
local attribute [tidy] tactic.case_bash
/-- A preadditive binary biproduct is a binary biproduct. -/
@[priority 100]
instance (X Y : C) [has_preadditive_binary_biproduct.{v} X Y] : has_binary_biproduct.{v} X Y :=
{ bicone := has_preadditive_binary_biproduct.bicone,
is_limit :=
{ lift := λ s, binary_fan.fst s ≫ has_preadditive_binary_biproduct.bicone.ι₁ +
binary_fan.snd s ≫ has_preadditive_binary_biproduct.bicone.ι₂,
uniq' := λ s m h, by erw [←category.comp_id m, ←has_preadditive_binary_biproduct.total,
comp_add, reassoc_of (h walking_pair.left), reassoc_of (h walking_pair.right)] },
is_colimit :=
{ desc := λ s, has_preadditive_binary_biproduct.bicone.π₁ ≫ binary_cofan.inl s +
has_preadditive_binary_biproduct.bicone.π₂ ≫ binary_cofan.inr s,
uniq' := λ s m h, by erw [←category.id_comp m, ←has_preadditive_binary_biproduct.total,
add_comp, category.assoc, category.assoc, h walking_pair.left, h walking_pair.right] } }
end
section
variables (X Y : C) [has_preadditive_binary_biproduct.{v} X Y]
@[simp, reassoc] lemma biprod.inl_fst : (biprod.inl : X ⟶ X ⊞ Y) ≫ biprod.fst = 𝟙 X :=
has_preadditive_binary_biproduct.ι₁_π₁
@[simp, reassoc] lemma biprod.inr_snd : (biprod.inr : Y ⟶ X ⊞ Y) ≫ biprod.snd = 𝟙 Y :=
has_preadditive_binary_biproduct.ι₂_π₂
@[simp, reassoc] lemma biprod.inr_fst : (biprod.inr : Y ⟶ X ⊞ Y) ≫ biprod.fst = 0 :=
has_preadditive_binary_biproduct.ι₂_π₁
@[simp, reassoc] lemma biprod.inl_snd : (biprod.inl : X ⟶ X ⊞ Y) ≫ biprod.snd = 0 :=
has_preadditive_binary_biproduct.ι₁_π₂
@[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) :=
has_preadditive_binary_biproduct.total
lemma biprod.inl_add_inr {T : C} {f : T ⟶ X} {g : T ⟶ Y} :
f ≫ biprod.inl + g ≫ biprod.inr = biprod.lift f g := rfl
lemma biprod.fst_add_snd {T : C} {f : X ⟶ T} {g : Y ⟶ T} :
biprod.fst ≫ f + biprod.snd ≫ g = biprod.desc f g := rfl
@[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} :
biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i :=
by simp [←biprod.inl_add_inr, ←biprod.fst_add_snd]
end
section has_limit_pair
/-- In a preadditive category, if the product of `X` and `Y` exists, then the preadditive binary
biproduct of `X` and `Y` exists. -/
def has_preadditive_binary_biproduct.of_has_limit_pair (X Y : C) [has_limit.{v} (pair X Y)] :
has_preadditive_binary_biproduct.{v} X Y :=
{ bicone :=
{ X := X ⨯ Y,
π₁ := category_theory.limits.prod.fst,
π₂ := category_theory.limits.prod.snd,
ι₁ := prod.lift (𝟙 X) 0,
ι₂ := prod.lift 0 (𝟙 Y) } }
/-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the preadditive binary
biproduct of `X` and `Y` exists. -/
def has_preadditive_binary_biproduct.of_has_colimit_pair (X Y : C) [has_colimit.{v} (pair X Y)] :
has_preadditive_binary_biproduct.{v} X Y :=
{ bicone :=
{ X := X ⨿ Y,
π₁ := coprod.desc (𝟙 X) 0,
π₂ := coprod.desc 0 (𝟙 Y),
ι₁ := category_theory.limits.coprod.inl,
ι₂ := category_theory.limits.coprod.inr } }
end has_limit_pair
section
variable (C)
/-- A preadditive category `has_preadditive_binary_biproducts` if the preadditive binary biproduct
exists for every pair of objects. -/
class has_preadditive_binary_biproducts :=
(has_preadditive_binary_biproduct : Π (X Y : C), has_preadditive_binary_biproduct.{v} X Y)
attribute [instance, priority 100] has_preadditive_binary_biproducts.has_preadditive_binary_biproduct
@[priority 100]
instance [has_preadditive_binary_biproducts.{v} C] : has_binary_biproducts.{v} C :=
⟨λ X Y, by apply_instance⟩
/-- If a preadditive category has all binary products, then it has all preadditive binary
biproducts. -/
def has_preadditive_binary_biproducts_of_has_binary_products [has_binary_products.{v} C] :
has_preadditive_binary_biproducts.{v} C :=
⟨λ X Y, has_preadditive_binary_biproduct.of_has_limit_pair X Y⟩
/-- If a preadditive category has all binary coproducts, then it has all preadditive binary
biproducts. -/
def has_preadditive_binary_biproducts_of_has_binary_coproducts [has_binary_coproducts.{v} C] :
has_preadditive_binary_biproducts.{v} C :=
⟨λ X Y, has_preadditive_binary_biproduct.of_has_colimit_pair X Y⟩
end
end preadditive
end category_theory.limits
|
02e23ef4c1730cbe11a16b8d7dad972722215b20 | da23b545e1653cafd4ab88b3a42b9115a0b1355f | /src/tidy/injections.lean | 896597dc68d8c31f5421900d44aca4dce843584e | [] | no_license | minchaowu/lean-tidy | 137f5058896e0e81dae84bf8d02b74101d21677a | 2d4c52d66cf07c59f8746e405ba861b4fa0e3835 | refs/heads/master | 1,585,283,406,120 | 1,535,094,033,000 | 1,535,094,033,000 | 145,945,792 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 330 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import tidy.at_least_one
open tactic
meta def injections_and_clear : tactic unit :=
do l ← local_context,
at_least_one $ l.map $ λ e, injection e >> clear e,
skip |
3eb885415266015d7579233da5fc7a02b7294102 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/lie/free.lean | 1823531a53c2aa22e2eb67219b6034cd4af28e1e | [
"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 | 10,992 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.of_associative
import algebra.lie.non_unital_non_assoc_algebra
import algebra.lie.universal_enveloping
import algebra.free_non_unital_non_assoc_algebra
/-!
# Free Lie algebras
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given a commutative ring `R` and a type `X` we construct the free Lie algebra on `X` with
coefficients in `R` together with its universal property.
## Main definitions
* `free_lie_algebra`
* `free_lie_algebra.lift`
* `free_lie_algebra.of`
* `free_lie_algebra.universal_enveloping_equiv_free_algebra`
## Implementation details
### Quotient of free non-unital, non-associative algebra
We follow [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975) and construct
the free Lie algebra as a quotient of the free non-unital, non-associative algebra. Since we do not
currently have definitions of ideals, lattices of ideals, and quotients for
`non_unital_non_assoc_semiring`, we construct our quotient using the low-level `quot` function on
an inductively-defined relation.
### Alternative construction (needs PBW)
An alternative construction of the free Lie algebra on `X` is to start with the free unital
associative algebra on `X`, regard it as a Lie algebra via the ring commutator, and take its
smallest Lie subalgebra containing `X`. I.e.:
`lie_subalgebra.lie_span R (free_algebra R X) (set.range (free_algebra.ι R))`.
However with this definition there does not seem to be an easy proof that the required universal
property holds, and I don't know of a proof that avoids invoking the Poincaré–Birkhoff–Witt theorem.
A related MathOverflow question is [this one](https://mathoverflow.net/questions/396680/).
## Tags
lie algebra, free algebra, non-unital, non-associative, universal property, forgetful functor,
adjoint functor
-/
universes u v w
noncomputable theory
variables (R : Type u) (X : Type v) [comm_ring R]
/- We save characters by using Bourbaki's name `lib` (as in «libre») for
`free_non_unital_non_assoc_algebra` in this file. -/
local notation `lib` := free_non_unital_non_assoc_algebra
local notation `lib.lift` := free_non_unital_non_assoc_algebra.lift
local notation `lib.of` := free_non_unital_non_assoc_algebra.of
local notation `lib.lift_of_apply` := free_non_unital_non_assoc_algebra.lift_of_apply
local notation `lib.lift_comp_of` := free_non_unital_non_assoc_algebra.lift_comp_of
namespace free_lie_algebra
/-- The quotient of `lib R X` by the equivalence relation generated by this relation will give us
the free Lie algebra. -/
inductive rel : lib R X → lib R X → Prop
| lie_self (a : lib R X) : rel (a * a) 0
| leibniz_lie (a b c : lib R X) : rel (a * (b * c)) (((a * b) * c) + (b * (a * c)))
| smul (t : R) {a b : lib R X} : rel a b → rel (t • a) (t • b)
| add_right {a b : lib R X} (c : lib R X) : rel a b → rel (a + c) (b + c)
| mul_left (a : lib R X) {b c : lib R X} : rel b c → rel (a * b) (a * c)
| mul_right {a b : lib R X} (c : lib R X) : rel a b → rel (a * c) (b * c)
variables {R X}
lemma rel.add_left (a : lib R X) {b c : lib R X} (h : rel R X b c) : rel R X (a + b) (a + c) :=
by { rw [add_comm _ b, add_comm _ c], exact h.add_right _, }
lemma rel.neg {a b : lib R X} (h : rel R X a b) : rel R X (-a) (-b) :=
by simpa only [neg_one_smul] using h.smul (-1)
lemma rel.sub_left (a : lib R X) {b c : lib R X} (h : rel R X b c) : rel R X (a - b) (a - c) :=
by simpa only [sub_eq_add_neg] using h.neg.add_left a
lemma rel.sub_right {a b : lib R X} (c : lib R X) (h : rel R X a b) : rel R X (a - c) (b - c) :=
by simpa only [sub_eq_add_neg] using h.add_right (-c)
lemma rel.smul_of_tower {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R]
(t : S) (a b : lib R X)
(h : rel R X a b) : rel R X (t • a) (t • b) :=
begin
rw [←smul_one_smul R t a, ←smul_one_smul R t b],
exact h.smul _,
end
end free_lie_algebra
/-- The free Lie algebra on the type `X` with coefficients in the commutative ring `R`. -/
@[derive inhabited]
def free_lie_algebra := quot (free_lie_algebra.rel R X)
namespace free_lie_algebra
instance {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] :
has_smul S (free_lie_algebra R X) :=
{ smul := λ t, quot.map ((•) t) (rel.smul_of_tower t) }
instance {S : Type*} [monoid S] [distrib_mul_action S R] [distrib_mul_action Sᵐᵒᵖ R]
[is_scalar_tower S R R] [is_central_scalar S R] :
is_central_scalar S (free_lie_algebra R X) :=
{ op_smul_eq_smul := λ t, quot.ind $ by exact λ a, congr_arg (quot.mk _) (op_smul_eq_smul t a) }
instance : has_zero (free_lie_algebra R X) :=
{ zero := quot.mk _ 0 }
instance : has_add (free_lie_algebra R X) :=
{ add := quot.map₂ (+) (λ _ _ _, rel.add_left _) (λ _ _ _, rel.add_right _) }
instance : has_neg (free_lie_algebra R X) :=
{ neg := quot.map has_neg.neg (λ _ _, rel.neg) }
instance : has_sub (free_lie_algebra R X) :=
{ sub := quot.map₂ has_sub.sub (λ _ _ _, rel.sub_left _) (λ _ _ _, rel.sub_right _) }
instance : add_group (free_lie_algebra R X) :=
function.surjective.add_group (quot.mk _) (surjective_quot_mk _)
rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
instance : add_comm_semigroup (free_lie_algebra R X) :=
function.surjective.add_comm_semigroup (quot.mk _) (surjective_quot_mk _) (λ _ _, rfl)
instance : add_comm_group (free_lie_algebra R X) :=
{ ..free_lie_algebra.add_group R X,
..free_lie_algebra.add_comm_semigroup R X }
instance {S : Type*} [semiring S] [module S R] [is_scalar_tower S R R] :
module S (free_lie_algebra R X) :=
function.surjective.module S ⟨quot.mk _, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) (λ _ _, rfl)
/-- Note that here we turn the `has_mul` coming from the `non_unital_non_assoc_semiring` structure
on `lib R X` into a `has_bracket` on `free_lie_algebra`. -/
instance : lie_ring (free_lie_algebra R X) :=
{ bracket := quot.map₂ (*) (λ _ _ _, rel.mul_left _) (λ _ _ _, rel.mul_right _),
add_lie := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, change quot.mk _ _ = quot.mk _ _, rw add_mul, },
lie_add := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, change quot.mk _ _ = quot.mk _ _, rw mul_add, },
lie_self := by { rintros ⟨a⟩, exact quot.sound (rel.lie_self a), },
leibniz_lie := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, exact quot.sound (rel.leibniz_lie a b c), }, }
instance : lie_algebra R (free_lie_algebra R X) :=
{ lie_smul :=
begin
rintros t ⟨a⟩ ⟨c⟩,
change quot.mk _ (a • (t • c)) = quot.mk _ (t • (a • c)),
rw ← smul_comm,
end, }
variables {X}
/-- The embedding of `X` into the free Lie algebra of `X` with coefficients in the commutative ring
`R`. -/
def of : X → free_lie_algebra R X := λ x, quot.mk _ (lib.of R x)
variables {L : Type w} [lie_ring L] [lie_algebra R L]
/-- An auxiliary definition used to construct the equivalence `lift` below. -/
def lift_aux (f : X → commutator_ring L) := lib.lift R f
lemma lift_aux_map_smul (f : X → L) (t : R) (a : lib R X) :
lift_aux R f (t • a) = t • lift_aux R f a :=
non_unital_alg_hom.map_smul _ t a
lemma lift_aux_map_add (f : X → L) (a b : lib R X) :
lift_aux R f (a + b) = (lift_aux R f a) + (lift_aux R f b) :=
non_unital_alg_hom.map_add _ a b
lemma lift_aux_map_mul (f : X → L) (a b : lib R X) :
lift_aux R f (a * b) = ⁅lift_aux R f a, lift_aux R f b⁆ :=
non_unital_alg_hom.map_mul _ a b
lemma lift_aux_spec (f : X → L) (a b : lib R X) (h : free_lie_algebra.rel R X a b) :
lift_aux R f a = lift_aux R f b :=
begin
induction h,
case rel.lie_self : a'
{ simp only [lift_aux_map_mul, non_unital_alg_hom.map_zero, lie_self], },
case rel.leibniz_lie : a' b' c'
{ simp only [lift_aux_map_mul, lift_aux_map_add, sub_add_cancel, lie_lie], },
case rel.smul : t a' b' h₁ h₂
{ simp only [lift_aux_map_smul, h₂], },
case rel.add_right : a' b' c' h₁ h₂
{ simp only [lift_aux_map_add, h₂], },
case rel.mul_left : a' b' c' h₁ h₂
{ simp only [lift_aux_map_mul, h₂], },
case rel.mul_right : a' b' c' h₁ h₂
{ simp only [lift_aux_map_mul, h₂], },
end
/-- The quotient map as a `non_unital_alg_hom`. -/
def mk : lib R X →ₙₐ[R] commutator_ring (free_lie_algebra R X) :=
{ to_fun := quot.mk (rel R X),
map_smul' := λ t a, rfl,
map_zero' := rfl,
map_add' := λ a b, rfl,
map_mul' := λ a b, rfl, }
/-- The functor `X ↦ free_lie_algebra R X` from the category of types to the category of Lie
algebras over `R` is adjoint to the forgetful functor in the other direction. -/
def lift : (X → L) ≃ (free_lie_algebra R X →ₗ⁅R⁆ L) :=
{ to_fun := λ f,
{ to_fun := λ c, quot.lift_on c (lift_aux R f) (lift_aux_spec R f),
map_add' := by { rintros ⟨a⟩ ⟨b⟩, rw ← lift_aux_map_add, refl, },
map_smul' := by { rintros t ⟨a⟩, rw ← lift_aux_map_smul, refl, },
map_lie' := by { rintros ⟨a⟩ ⟨b⟩, rw ← lift_aux_map_mul, refl, }, },
inv_fun := λ F, F ∘ (of R),
left_inv := λ f, by { ext x, simp only [lift_aux, of, quot.lift_on_mk, lie_hom.coe_mk,
function.comp_app, lib.lift_of_apply], },
right_inv := λ F,
begin
ext ⟨a⟩,
let F' := F.to_non_unital_alg_hom.comp (mk R),
exact non_unital_alg_hom.congr_fun (lib.lift_comp_of R F') a,
end, }
@[simp] lemma lift_symm_apply (F : free_lie_algebra R X →ₗ⁅R⁆ L) : (lift R).symm F = F ∘ (of R) :=
rfl
variables {R}
@[simp] lemma of_comp_lift (f : X → L) : (lift R f) ∘ (of R) = f :=
(lift R).left_inv f
@[simp] lemma lift_unique (f : X → L) (g : free_lie_algebra R X →ₗ⁅R⁆ L) :
g ∘ (of R) = f ↔ g = lift R f :=
(lift R).symm_apply_eq
attribute [irreducible] of lift
@[simp] lemma lift_of_apply (f : X → L) (x) : lift R f (of R x) = f x :=
by rw [← function.comp_app (lift R f) (of R) x, of_comp_lift]
@[simp] lemma lift_comp_of (F : free_lie_algebra R X →ₗ⁅R⁆ L) : lift R (F ∘ (of R)) = F :=
by { rw ← lift_symm_apply, exact (lift R).apply_symm_apply F, }
@[ext] lemma hom_ext {F₁ F₂ : free_lie_algebra R X →ₗ⁅R⁆ L} (h : ∀ x, F₁ (of R x) = F₂ (of R x)) :
F₁ = F₂ :=
have h' : (lift R).symm F₁ = (lift R).symm F₂, { ext, simp [h], },
(lift R).symm.injective h'
variables (R X)
/-- The universal enveloping algebra of the free Lie algebra is just the free unital associative
algebra. -/
@[simps] def universal_enveloping_equiv_free_algebra :
universal_enveloping_algebra R (free_lie_algebra R X) ≃ₐ[R] free_algebra R X :=
alg_equiv.of_alg_hom
(universal_enveloping_algebra.lift R $ free_lie_algebra.lift R $ free_algebra.ι R)
(free_algebra.lift R $ (universal_enveloping_algebra.ι R) ∘ (free_lie_algebra.of R))
(by { ext, simp, })
(by { ext, simp, })
end free_lie_algebra
|
4fd1aa77f767e7b75ba24b3959bb28c31ca6067d | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/topology/uniform_space/basic.lean | 6238326d9b69b490f9972daf4452e9dca039362c | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 42,035 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
Theory of uniform spaces.
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* completeness
* extension of uniform continuous functions to complete spaces
* uniform contiunuity & embedding
* totally bounded
* totally bounded ∧ complete → compact
The central concept of uniform spaces is its uniformity: a filter relating two elements of the
space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter
represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the
`triangular` rule holds.
The formalization is mostly based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import order.filter.basic order.filter.lift topology.separation
open set lattice filter classical
open_locale classical topological_space
set_option eqn_compiler.zeta true
universes u
section
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type*} := {p : α × α | p.1 = p.2}
@[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s :=
by simp [subset_def]; exact forall_congr (λ a, by simp)
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
@[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)}
{x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl
@[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm
theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) :=
assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ comp_rel s t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r :=
set.ext $ assume ⟨a, b⟩, by simp
lemma comp_rel_assoc {r s t : set (α×α)} :
comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) :=
by ext p; cases p; simp only [mem_comp_rel]; tauto
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) :=
(uniformity : filter (α × α))
(refl : principal id_rel ≤ uniformity)
(symm : tendsto prod.swap uniformity uniformity)
(comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity)
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r ∈ U) x, (x, x) ∈ r)
(symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U)
(comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α :=
⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm,
begin
intros r ru,
rw [mem_lift'_sets],
exact comp _ ru,
apply monotone_comp_rel; exact monotone_id,
end⟩
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
{ is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity,
is_open_univ := by simp; intro; exact univ_mem_sets,
is_open_inter :=
assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt},
is_open_sUnion :=
assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ }
lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*]
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends topological_space α, uniform_space.core α :=
(is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity))
end prio
@[pattern] def uniform_space.mk' {α} (t : topological_space α)
(c : uniform_space.core α)
(is_open_uniformity : ∀s:set α, t.is_open s ↔
(∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) :
uniform_space α := ⟨c, is_open_uniformity⟩
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
{ to_core := u,
to_topological_space := u.to_topological_space,
is_open_uniformity := assume a, iff.rfl }
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = u.to_topological_space) : uniform_space α :=
{ to_core := u,
to_topological_space := t,
is_open_uniformity := assume a, h.symm ▸ iff.rfl }
lemma uniform_space.to_core_to_topological_space (u : uniform_space α) :
u.to_core.to_topological_space = u.to_topological_space :=
topological_space_eq $ funext $ assume s,
by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity]
@[ext]
lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h :=
have u₁ = u₂, from uniform_space.core_eq h,
have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this],
by simp [*]
lemma uniform_space.of_core_eq_to_core
(u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) :
uniform_space.of_core_eq u.to_core t h = u :=
uniform_space_eq rfl
section uniform_space
variables [uniform_space α]
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
(@uniform_space.to_core α _).uniformity
localized "notation `𝓤` := uniformity" in uniformity
lemma is_open_uniformity {s : set α} :
is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) :=
uniform_space.is_open_uniformity s
lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α :=
(@uniform_space.to_core α _).refl
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) :=
(@uniform_space.to_core α _).symm
lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α :=
(@uniform_space.to_core α _).comp
lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) :=
symm_le_uniformity
lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) :=
assume s hs,
show {x | (a, a) ∈ s} ∈ f,
from univ_mem_sets' $ assume b, refl_mem_uniformity hs
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, comp_rel t t ⊆ s :=
have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t),
from comp_le_uniformity hs,
(mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs,
⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α :=
by rw [map_swap_eq_comap_swap];
from map_le_iff_le_comap.1 tendsto_swap_uniformity
lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α :=
le_antisymm uniformity_le_symm symm_le_uniformity
theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f :=
calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g :
lift_mono uniformity_le_symm (le_refl _)
... ≤ _ :
by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) :
(𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f :=
calc (𝓤 α).lift (λs, f (comp_rel s s)) =
((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _)
lemma comp_le_uniformity3 :
(𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) :=
calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) =
(𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (assume x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) :
lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $
monotone_principal.comp (monotone_comp_rel monotone_const monotone_id)
... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) :
lift_lift'_same_eq_lift'
(assume s, monotone_comp_rel monotone_const monotone_id)
(assume s, monotone_comp_rel monotone_id monotone_const)
... ≤ (𝓤 α) : comp_le_uniformity
lemma mem_nhds_uniformity_iff {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α :=
⟨ begin
simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib],
exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq
end,
assume hs,
mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α},
assume x' hx', refl_mem_uniformity hx' rfl,
is_open_uniformity.mpr $ assume x' hx',
let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in
by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'),
by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b),
have hp : (x', b) ∈ t, from hax' ▸ hp',
have (b, b') ∈ t, from hab ▸ hp'',
have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩,
show b' ∈ s,
from tr this rfl,
hs⟩⟩
lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) :=
by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro
(assume hs, ⟨_, hs, assume x hx, hx rfl⟩)
(assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $
assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp])
lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) :=
begin
ext s,
rw [mem_lift'_sets], tactic.swap, apply monotone_preimage,
simp [mem_nhds_uniformity_iff],
exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩,
assume ⟨t, h₁, h₂⟩,
(𝓤 α).sets_of_superset h₁ $
assume ⟨x', y⟩ hp (eq : x' = x), h₂ $
show (x, y) ∈ t, from eq ▸ hp⟩
end
lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{y : α | (x, y) ∈ s} ∈ 𝓝 x :=
have 𝓝 x ≤ principal {y : α | (x, y) ∈ s},
by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h),
by simp at this; assumption
lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{x : α | (x, y) ∈ s} ∈ 𝓝 y :=
mem_nhds_left _ (symm_le_uniformity h)
lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_right a
lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_left a
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage )
end
(congr_arg _ $ funext $ assume s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm]
... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ hg.comp monotone_preimage
... = _ : by simp [image_swap_eq_preimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
filter.prod (𝓝 a) (𝓝 b) =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α),
set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) :=
begin
rw [prod_def],
show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, principal (set.prod s t))) = _,
rw [lift_nhds_right],
apply congr_arg, funext s,
rw [lift_nhds_left],
refl,
exact monotone_principal.comp (monotone_prod monotone_const monotone_id),
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, monotone_prod monotone_id monotone_const)
end
lemma nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_prod monotone_const monotone_preimage },
{ intro t, exact monotone_prod monotone_preimage monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) :
∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from
assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $
show cl_d ∈ 𝓝 (x, y),
begin
rw [nhds_eq_uniformity_prod, mem_lift'_sets],
exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_prod monotone_preimage monotone_preimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left,
assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩
end
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) :=
set.ext $ assume ⟨a, b⟩,
calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds]
... ↔ (((@prod.swap α α) <$> 𝓤 α).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) :
by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod]
... ↔ ((map (@prod.swap α α) (𝓤 α)).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) :
by refl
... ↔ ((𝓤 α).lift'
(λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) :
begin
rw [map_lift'_eq2],
simp [image_swap_eq_preimage_swap, function.comp],
exact monotone_prod monotone_preimage monotone_preimage
end
... ↔ (∀s ∈ 𝓤 α, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) :
begin
rw [lift'_inf_principal_eq, lift'_neq_bot_iff],
apply forall_congr, intro s, rw [ne_empty_iff_exists_mem],
exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const
end
... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) :
forall_congr $ assume s, forall_congr $ assume hs,
⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩,
assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩
... ↔ _ : by simp
lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure)
(calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) :
lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs)
... ≤ (𝓤 α) : comp_le_uniformity3)
lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_infi $ assume d, le_infi $ assume hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $
assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ 𝓤 α, by filter_upwards [hs] this,
by simp [this])
(assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
interior s ∈ 𝓤 α :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) :
∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s :=
have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h,
have ∃ t ∈ 𝓤 α, closure t ⊆ s,
by rwa [mem_lift'_sets] at this; apply closure_mono,
let ⟨t, ht, hst⟩ := this in
⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩
/- uniform continuity -/
def uniform_continuous [uniform_space β] (f : α → β) :=
tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β)
theorem uniform_continuous_def [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β,
{x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α :=
iff.rfl
lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) :
uniform_continuous c :=
have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from
eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b,
le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity
lemma uniform_continuous_id : uniform_continuous (@id α) :=
by simp [uniform_continuous]; exact tendsto_id
lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) :=
@tendsto_const_uniformity _ _ _ b (𝓤 α)
lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β}
(hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
hg.comp hf
end uniform_space
end
open_locale uniformity
section constructions
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
instance : partial_order (uniform_space α) :=
{ le := λt s, t.uniformity ≤ s.uniformity,
le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl _,
le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ }
instance : has_Inf (uniform_space α) :=
⟨assume s, uniform_space.of_core {
uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ assume u, le_infi $ assume hu, u.refl,
symm := le_infi $ assume u, le_infi $ assume hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ assume u, le_infi $ assume hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩
private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
Inf tt ≤ t :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') :
t ≤ Inf tt :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ assume t', le_infi $ assume ht', h t' ht'
instance : has_top (uniform_space α) :=
⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_bot (uniform_space α) :=
⟨{ to_topological_space := ⊥,
uniformity := principal id_rel,
refl := le_refl _,
symm := by simp [tendsto]; apply subset.refl,
comp :=
begin
rw [lift'_principal], {simp},
exact monotone_comp_rel monotone_id monotone_id
end,
is_open_uniformity :=
assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩
instance : complete_lattice (uniform_space α) :=
{ sup := λa b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h),
le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h),
sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩,
inf := λ a b, Inf {a, b},
le_inf := λ a b c h₁ h₂, le_Inf (λ u h,
by { cases h, exact h.symm ▸ h₂, exact (mem_singleton_iff.1 h).symm ▸ h₁ }),
inf_le_left := λ a b, Inf_le (by simp),
inf_le_right := λ a b, Inf_le (by simp),
top := ⊤,
le_top := λ a, show a.uniformity ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ u, u.refl,
Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t},
le_Sup := λ s u h, le_Inf (λ u' h', h' u h),
Sup_le := λ s u h, Inf_le h,
Inf := Inf,
le_Inf := λ s a hs, le_Inf hs,
Inf_le := λ s a ha, Inf_le ha,
..uniform_space.partial_order }
lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} :
(infi u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from
le_antisymm
(le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _)
lemma inf_uniformity {u v : uniform_space α} :
(u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity :=
have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq],
calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this]
... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq]
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)),
to_topological_space := u.to_topological_space.induced f,
refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl),
symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap,
comp := le_trans
begin
rw [comap_lift'_eq, comap_lift'_eq2],
exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
repeat { exact monotone_comp_rel monotone_id monotone_id }
end
(comap_mono u.comp),
is_open_uniformity := λ s, begin
change (@is_open α (u.to_topological_space.induced f) s ↔ _),
simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff, filter.comap, and_comm],
refine ball_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩,
rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) },
{ rintro ⟨t, ht, hts⟩,
exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl,
mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ }
end }
lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id :=
by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id]
lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp
lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} :
uniform_continuous f ↔ uα ≤ uβ.comap f :=
filter.map_le_iff_le_comap
lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] :
@uniform_continuous α β (uniform_space.comap f u) u f :=
tendsto_comap
theorem to_topological_space_comap {f : α → β} {u : uniform_space β} :
@uniform_space.to_topological_space _ (uniform_space.comap f u) =
topological_space.induced f (@uniform_space.to_topological_space β u) := rfl
lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α]
(h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g :=
tendsto_comap_iff.2 h
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
@uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ :=
le_of_nhds_le_nhds $ assume a,
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _)
lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf
lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl
lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ :=
top_unique $ assume s hs, classical.by_cases
(assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤)
(assume : s ≠ ∅,
let ⟨x, hx⟩ := exists_mem_of_ne_empty this in
have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl,
this.symm ▸ @is_open_univ _ ⊤)
lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} :
(infi u).to_topological_space = ⨅i, (u i).to_topological_space :=
classical.by_cases
(assume h : nonempty ι,
eq_of_nhds_eq_nhds $ assume a,
begin
rw [nhds_infi, nhds_eq_uniformity],
change (infi u).uniformity.lift' (preimage $ prod.mk a) = _,
begin
rw [infi_uniformity, lift'_infi],
exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm),
exact h,
exact assume a b, rfl
end
end)
(assume : ¬ nonempty ι,
le_antisymm
(le_infi $ assume i, to_topological_space_mono $ infi_le _ _)
(have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim,
have @uniform_space.to_topological_space _ (infi u) = ⊤,
from this.symm ▸ to_topological_space_top,
this.symm ▸ le_top))
lemma to_topological_space_Inf {s : set (uniform_space α)} :
(Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) :=
begin
rw [Inf_eq_infi, to_topological_space_infi],
apply congr rfl,
funext x,
exact to_topological_space_infi
end
lemma to_topological_space_inf {u v : uniform_space α} :
(u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space :=
by rw [to_topological_space_Inf, infi_pair]
instance : uniform_space empty := ⊥
instance : uniform_space unit := ⊥
instance : uniform_space bool := ⊥
instance : uniform_space ℕ := ⊥
instance : uniform_space ℤ := ⊥
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.comap subtype.val t
lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] :
𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) :=
rfl
lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] :
uniform_continuous (subtype.val : {a : α // p a} → α) :=
uniform_continuous_comap
lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β]
{f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) :
uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) :=
uniform_continuous_comap' hf
lemma tendsto_of_uniform_continuous_subtype
[uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) :
tendsto f (𝓝 a) (𝓝 (f a)) :=
by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact
tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _)
section prod
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) :=
uniform_space.of_core_eq
(u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core
prod.topological_space
(calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space :
by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl
... = _ : by rw [uniform_space.to_core_to_topological_space])
theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) =
(𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓
(𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) :=
inf_uniformity
lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] :
𝓤 (α×β) =
map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) :=
have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) =
comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))),
from funext $ assume f, map_eq_comap_of_inverse
(funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl),
by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp]
lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} :
t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) :=
mem_map_sets_iff
lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α}
(hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) :
∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s :=
begin
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf,
rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf,
rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht,
refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩,
exact hab,
exact refl_mem_uniformity hv,
refl
end
lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)}
(ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) :
{p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) :=
by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb)
lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le
lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le
lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) :=
tendsto_prod_uniformity_fst
lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) :=
tendsto_prod_uniformity_snd
variables [uniform_space α] [uniform_space β] [uniform_space γ]
lemma uniform_continuous.prod_mk
{f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) :
uniform_continuous (λa, (f₁ a, f₂ a)) :=
by rw [uniform_continuous, uniformity_prod]; exact
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) :
uniform_continuous (λ a, f (a,b)) :=
h.comp (uniform_continuous_id.prod_mk uniform_continuous_const)
lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) :
uniform_continuous (λ b, f (a,b)) :=
h.comp (uniform_continuous_const.prod_mk uniform_continuous_id)
lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] :
@uniform_space.to_topological_space (α × β) prod.uniform_space =
@prod.topological_space α β u.to_topological_space v.to_topological_space := rfl
end prod
section
open uniform_space function
variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
local notation f `∘₂` g := function.bicompr f g
def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry' f)
lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry' f) := iff.rfl
lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
by rw [←uncurry'_curry f] {occs := occurrences.pos [2]} ; refl
lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ}
(hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (g ∘₂ f) :=
hg.comp hf
end
lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} :
@uniform_space.to_topological_space (subtype p) subtype.uniform_space =
@subtype.topological_space α p u.to_topological_space := rfl
section sum
variables [uniform_space α] [uniform_space β]
open sum
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum : uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β))
(λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂])
(λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩)
(λ r ⟨Hrα, Hrβ⟩, begin
rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩,
rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩,
refine ⟨_,
⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩,
mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩,
rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩,
⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩,
{ have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩,
exact Htα A },
{ have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩,
exact Htβ A }
end)
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/
lemma union_mem_uniformity_sum
{a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) :
((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity :=
⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
{ p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity :=
begin
cases x,
{ refine mem_sets_of_superset
(union_mem_uniformity_sum (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets)
(union_subset _ _);
rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
{ refine mem_sets_of_superset
(union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.2 xs)))
(union_subset _ _);
rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
end
lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)}
(hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) :
is_open s :=
begin
split,
{ refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff.2 _),
rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩,
refine mem_sets_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl },
{ refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff.2 _),
rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩,
refine mem_sets_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }
end
/- We can now define the uniform structure on the disjoint union -/
instance sum.uniform_space : uniform_space (α ⊕ β) :=
{ to_core := uniform_space.core.sum,
is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ }
lemma sum.uniformity : 𝓤 (α ⊕ β) =
map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔
map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl
end sum
end constructions
lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α}
(hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i :=
begin
let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i},
have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n),
{ refine λ n hn, is_open_uniformity.2 _,
rintro x ⟨i, m, hm, h⟩,
rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩,
apply (𝓤 α).sets_of_superset hm',
rintros ⟨x, y⟩ hp rfl,
refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩,
dsimp at hz ⊢, rw comp_rel_assoc,
exact ⟨y, hp, hz⟩ },
have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n,
{ intros x hx,
rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩,
rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩,
exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ },
rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩,
refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩,
rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩,
refine ⟨i, λ y hy, h _⟩,
exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy)
end
lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma hs (by simpa) hc₂
|
da61641136bf00fef77247fd415126dd67f8aa59 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Level.lean | 610d44a1416e0c9a9669828db3c6ef420d19c729 | [
"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 | 3,373 | 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.Log
import Lean.Parser.Level
import Lean.Elab.Exception
import Lean.Elab.AutoBound
namespace Lean.Elab.Level
structure Context where
options : Options
ref : Syntax
autoBoundImplicit : Bool
structure State where
ngen : NameGenerator
mctx : MetavarContext
levelNames : List Name
abbrev LevelElabM := ReaderT Context (EStateM Exception State)
instance : MonadOptions LevelElabM where
getOptions := return (← read).options
@[always_inline]
instance : MonadRef LevelElabM where
getRef := return (← read).ref
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : AddMessageContext LevelElabM where
addMessageContext msg := pure msg
@[always_inline]
instance : MonadNameGenerator LevelElabM where
getNGen := return (← get).ngen
setNGen ngen := modify fun s => { s with ngen := ngen }
def mkFreshLevelMVar : LevelElabM Level := do
let mvarId ← mkFreshLMVarId
modify fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId }
return mkLevelMVar mvarId
register_builtin_option maxUniverseOffset : Nat := {
defValue := 32
descr := "maximum universe level offset"
}
private def checkUniverseOffset [Monad m] [MonadError m] [MonadOptions m] (n : Nat) : m Unit := do
let max := maxUniverseOffset.get (← getOptions)
unless n <= max do
throwError "maximum universe level offset threshold ({max}) has been reached, you can increase the limit using option `set_option maxUniverseOffset <limit>`, but you are probably misusing universe levels since offsets are usually small natural numbers"
partial def elabLevel (stx : Syntax) : LevelElabM Level := withRef stx do
let kind := stx.getKind
if kind == ``Lean.Parser.Level.paren then
elabLevel (stx.getArg 1)
else if kind == ``Lean.Parser.Level.max then
let args := stx.getArg 1 |>.getArgs
args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl =>
return mkLevelMax' (← elabLevel stx) lvl
else if kind == ``Lean.Parser.Level.imax then
let args := stx.getArg 1 |>.getArgs
args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl =>
return mkLevelIMax' (← elabLevel stx) lvl
else if kind == ``Lean.Parser.Level.hole then
mkFreshLevelMVar
else if kind == numLitKind then
match stx.isNatLit? with
| some val => checkUniverseOffset val; return Level.ofNat val
| none => throwIllFormedSyntax
else if kind == identKind then
let paramName := stx.getId
unless (← get).levelNames.contains paramName do
if (← read).autoBoundImplicit && isValidAutoBoundLevelName paramName (relaxedAutoImplicit.get (← read).options) then
modify fun s => { s with levelNames := paramName :: s.levelNames }
else
throwError "unknown universe level '{paramName}'"
return mkLevelParam paramName
else if kind == `Lean.Parser.Level.addLit then
let lvl ← elabLevel (stx.getArg 0)
match stx.getArg 2 |>.isNatLit? with
| some val => checkUniverseOffset val; return lvl.addOffset val
| none => throwIllFormedSyntax
else
throwError "unexpected universe level syntax kind"
end Lean.Elab.Level
|
d35e3b01eeab50331a2b365476db2486b23d6146 | d5b53bc87e7f4dda87570c8ef6ee4b4de685f315 | /src/induced_maps.lean | 1c76b49ab79b0d852da105ce7ed34d7b0ff0c99d | [] | no_license | Shenyang1995/M4R | 3bec366fba7262ed29d7f64b4ba7cc978494c022 | a6a3399c4d1935b39a22f64c30f293ef2a32fdeb | refs/heads/master | 1,597,008,096,640 | 1,591,722,931,000 | 1,591,722,931,000 | 214,177,424 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,864 | lean | import cohomology
import G_module.hom
variables {G : Type*} [group G]
variables {M : Type*}[add_comm_group M] [G_module G M]
variables {N : Type*} [add_comm_group N] [G_module G N]
variables {n : ℕ}
def cochain.map (f : M →[G] N) : cochain n G M → cochain n G N :=
λ b c, f (b c)
theorem d_map (f : M →[G] N) (c : cochain n G M) :
cochain.map f (d.to_fun c) = d.to_fun (cochain.map f c) :=
begin
ext gs,
unfold d.to_fun,
unfold cochain.map,
rw f.map_add,
rw f.map_smul,
rw f.map_sum,
congr',
ext x,
show (f.f) _ = _,
exact add_monoid_hom.map_gsmul _ _ _,
end
def cocycle.map (f : M →[G] N) : cocycle n G M → cocycle n G N :=
λ c, ⟨cochain.map f c.1, begin
show d.to_fun (cochain.map f c.val) = 0,
rw ←d_map,
have h0 : d.to_fun c.val = 0,
exact c.property,
rw h0,
ext i,
apply add_monoid_hom.map_zero,
end⟩
def coboundary.map (f : M →[G] N) : coboundary n G M → coboundary n G N:=
λ c, ⟨cochain.map f c.1, begin
unfold coboundary,
unfold add_group_hom.range,
unfold add_group_hom.map,
dsimp,
rw set.mem_image,
have h0: ∃ (x : cochain n G M), d.to_fun x = c.val,
sorry,
rcases h0 with ⟨ y, hy1⟩,
use cochain.map f y,
split,
trivial,
rw <-hy1,
exact (d_map f y).symm,
end⟩
def cochain.hom (f : M →[G] N) : cochain n G M →+ cochain n G N :=
{ to_fun := cochain.map f,
map_zero' := begin unfold cochain.map, ext, apply add_monoid_hom.map_zero, end,
map_add' := begin intros, unfold cochain.map, funext, apply add_monoid_hom.map_add,end }
lemma cocycle.map_incl (f : M →[G] N): set.image (cochain.hom f).to_fun (cohomology n G M).top.carrier ⊆ (cohomology n G N).top.carrier:= begin
unfold cochain.hom,
unfold cohomology,
unfold set.image,
intros x hx,
show d.to_fun x = 0,
cases hx with a ha,
have h2: cochain.map f a=x, exact and.right ha,
rw <-h2,
rw ←d_map,
have h0 : d.to_fun a = 0,
exact and.left ha,
rw h0,
ext i,
apply add_monoid_hom.map_zero,
end
lemma coboundary.map_incl (f : M →[G] N): set.image (cochain.hom f).to_fun (cohomology n G M).bottom.carrier ⊆ (cohomology n G N).bottom.carrier:=
begin
unfold cochain.hom,
unfold cohomology,
unfold set.image,
dsimp,
rintros x ⟨ a, ha1, h2⟩ ,
rw <-h2,
unfold coboundary,
unfold add_group_hom.range,
unfold add_group_hom.map,
dsimp,
rw set.mem_image,
unfold coboundary at ha1,
unfold add_group_hom.range at ha1,
unfold add_group_hom.map at ha1,
dsimp at ha1,
rw set.mem_image at ha1,
rcases ha1 with ⟨ y, hy1, hy2⟩,
use cochain.map f y,
split,
trivial,
rw <-hy2,
exact (d_map f y).symm,
end
def cohomology.map (f : M →[G] N) : cohomology n G M →+ cohomology n G N:=
add_subquotient.to_add_monoid_hom (cocycle.map_incl f) (coboundary.map_incl f)
/-
Need:
If M → P is a G-module map then there's an induced map H^n(M) → H^n(P)
this is cohomology.map (what about n)
-/ |
f896879fcf65cf9fdc22ecca6bd11d5a1432c026 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1815.lean | 0a0cea29ddb17be3a4f151360ddffc790b5391ff | [
"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 | 284 | lean | variable {α : Type _} [Mul α] [Inhabited α]
abbrev Left (a : α) : α := a * default
abbrev Right (a : α): α := default * a
theorem mul_comm (a b : α) : a * b = b * a := sorry
set_option trace.Meta.Tactic.simp true
example (a : α) : Left a = Right a := by
simp [mul_comm]
|
729e5105c34c23ebf0f4ec529545b6251b09a3c3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/mk_has_sizeof_instance_auto.lean | dc7f9842d0e66cad3f6e281451ceef172a1b16c4 | [] | 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 | 466 | 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 constructing has_sizeof instance.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.rec_util
import Mathlib.Lean3Lib.init.meta.constructor_tactic
namespace Mathlib
namespace tactic
/- Retrieve the name of the type we are building a has_sizeof instance for. -/
end Mathlib |
f046795bd8b6fb3d995b7059fa7dfdca1eb647ec | 29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f | /Exercises week 4/21_exercise_sheet.lean | a06e253e68cd9e31b1c637cddb165f8f049dc6f7 | [] | no_license | KjellZijlemaker/Logical_Verification_VU | ced0ba95316a30e3c94ba8eebd58ea004fa6f53b | 4578b93bf1615466996157bb333c84122b201d99 | refs/heads/master | 1,585,966,086,108 | 1,549,187,704,000 | 1,549,187,704,000 | 155,690,284 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,508 | lean | /- Exercise 2.1: Functional Programming — Lists -/
/- Question 1: Counting elements -/
/- 1.1. Define a function `count` that counts the number of occurrences of an element in a list. It
should be similar to `bcount` from the lecture, except that it takes a value `α` instead of a
predicate `α → bool`.
`decidable_eq` is the type class of types whose equality is decidable. -/
def count {α : Type} (a : α) [decidable_eq α] : list α → ℕ
| [] := 0
| (x :: xs) := count xs + (if x = a then 1 else count xs)
def reverse {α: Type}: list α → list α
| [] := []
| (x :: xs) := reverse xs ++ [x]
lemma count_reverse_eq_count {α: Type} (a: α) (xs: list α) [decidable_eq α]: count a (reverse xs) = count xs
begin
end
/- 1.2. Test your definition of `count` on a few examples to convince yourself that it is
correct. This is something you should always do regardless of whether we ask for it.
You can use `#reduce` or (if `#reduce` fails) `#eval` to do this. -/
#reduce count "a" ["a", "a"]
#reduce count 2 [2,2,2,2,2]
#reduce count 0 [0,0,0,0]
#reduce count 9 []
/- 1.3. Complete the following proof (or replace it with a new proof structure of your own).
Hints: Some of the following lemmas might be useful to reason about `≤`. Moreover, if it helps you
carry out the proof, you could reconsider revising your answer to question 1.1. -/
#check nat.le_add_left
#check nat.le_add_right
#check add_le_add_left
#check add_le_add_right
lemma count_le_length {α : Type} (a : α) [decidable_eq α] :
∀xs : list α, count a xs ≤ list.length xs
| [] := by refl
| (x :: xs) :=
calc count a (x :: xs) = count a xs + (if x = a then 1 else 0) :
by refl
... ≤ list.length xs + (if x = a then 1 else 0) :
begin
apply add_le_add_right,
simp[count_le_length xs]
end
... ≤ list.length (x :: xs) :
begin
apply add_le_add_left,
by_cases (x=a),
simp[h, list.length],
simp[h, list.length],
apply nat.le_add_left
end
/- Question 2: Removing duplicates -/
/- 2.1. Define a predicate `mem x xs` that returns true if `x` is an element of `xs`. -/
def mem {α: Type} (x: α) [decidable_eq α]: list α → bool
| [] := false
| (xs :: xss):= if (xs = x) then true else mem xss
#reduce mem 2 [7,1]
/- The above `mem` predicate is not quite as convenient as the predefined `list.mem`, for which
theorems and a nice notation (infix `∈`) are available, including a proof of decidability. Let's use
`list.mem` from now on. -/
#print list.has_mem
#check list.mem
#check list.decidable_mem
/- 2.2. Define a function `remdups` that removes duplicate elements in a list. For example,
`remdups [1, 2, 1, 3]` could return either `[1, 2, 3]` or `[2, 1, 3]`, depending of which of the two
occurrences of `1` is kept.
Hint: One of the two behaviors is easier to implement. -/
def remdumps {α: Type} [decidable_eq α]: list α → list α
| [] := []
| (x :: xs) := if list.mem x xs then remdumps xs else x :: remdumps xs
/- 2.3. Test your implementation on more than two input values, using `#reduce` or `#eval`, and put
the expected value in a comment. -/
#reduce remdumps [2,2,2,3,4,4,4] --Expect 2,3,4
/- Do you find yourself copy-pasting the outcome of `#reduce` into the comment? If so, this defeats
the point of writing a test. You should first think for yourself of the expected result, write it
down, and then compare the actual result with it. -/
/- 2.4. Define a function `remdups_adj` that compresses adjacent duplicates. For example, it would
leave `[1, 2, 1, 3]` unchanged but compress `[1, 1, 2, 2, 2, 1, 3, 3]` to `[1, 2, 1, 3]`. -/
def remdumps_adj {α: Type} [decidable_eq α]: list α → list α
| [] := []
| (x :: xs) := if list.mem x xs && (list.take (list.length xs - list.length(remdumps_adj xs)) = x then remdumps_adj xs else x :: remdumps_adj xs
/- 2.5. Test your implementation on the same values as you used for question 2.3. -/
#reduce remdumps_adj [2,2,2,3,4,3,4]
/- Do the tests detect any difference in behavior between `remdups` and `remdups_adj`? If the answer
is no, this is a strong indication that your tests were incomplete to start with. -/
/- 2.6. Prove that `remdups` does not influence the behavior of `list.mem`.
Hint: Use `by_cases` to distinguish between the case where a given element is kept and the case
where it is removed. -/
@[simp] lemma mem_remdups {α : Type} (a : α) [decidable_eq α] :
∀xs : list α, a ∈ remdumps xs ↔ a ∈ xs
| [] := by refl
| (x :: xs) := begin simp[remdumps], by_cases list.mem x xs, { simp [h, mem_remdups xs],
apply iff.intro,
{ intro, apply or.intro_right, assumption },
{ intro hor,
apply hor.elim,
{ intro a_eq_x, rw a_eq_x, assumption },
{ intro, assumption } } },
{ simp [h, mem_remdups xs] } end
-- begin
-- intro xs,
-- apply iff.intro,
-- intro l,
-- by_cases a ∈ xs,
-- assumption,
-- cases xs,
-- simp,
-- apply l,
-- end
/- 2.7. State and prove that `remdups_adj` does not influence the behavior of `list.mem`. -/
lemma test {α: Type} (xs: list α) (x: α) [decidable_eq α]: remdumps_adj xs = xs :=
begin
cases xs,
refl,
simp[remdumps_adj],
by_cases
end
/- 2.8. State and prove that `remdups` is idempotent (i.e., that applying it twice has the same
effect as applying it only once). -/
-- enter your answer here
/- 2.9 (**optional bonus**). State and prove that `remdups_adj` is idempotent.
Warning: This one is difficult. -/
-- enter your answer here
|
281cc2ace70d26e20c808dae65f108ab1b30398d | 43390109ab88557e6090f3245c47479c123ee500 | /src/Topology/Material/Sutherland_Chapter_8.lean | 5e5f8ac0525a9c851749e52b797c732266b54988 | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,600 | lean | import analysis.topology.continuity
import analysis.topology.topological_space
import analysis.topology.infinite_sum
import analysis.topology.topological_structures
import analysis.topology.uniform_space
import data.equiv.basic
local attribute [instance] classical.prop_decidable
universes u v w
open set filter lattice classical
definition is_open_sets {α : Type u} (is_open : set α → Prop) :=
is_open univ ∧ (∀s t, is_open s → is_open t → is_open (s ∩ t)) ∧ (∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
definition is_to_top {α : Type u} (is_open : set α → Prop) (H : is_open_sets (is_open)) : topological_space α :=
{ is_open := is_open,
is_open_univ := H.left,
is_open_inter := H.right.left,
is_open_sUnion := H.right.right
}
definition top_to_is {α : Type u} (T : topological_space α) : is_open_sets (T.is_open) :=
⟨T.is_open_univ,T.is_open_inter,T.is_open_sUnion⟩
structure homeomorphism {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) extends equiv α β :=
(to_is_continuous : continuous to_fun)
(from_is_continuous : continuous inv_fun)
definition is_homeomorphic_to {α : Type u} {β : Type v} (X :topological_space α) (Y : topological_space β) : Prop := nonempty (homeomorphism X Y)
--Proposition 8.6a
lemma id_map_continuous {α : Type u} {X : topological_space α} : continuous (@id α) :=
begin
intros s H1,
exact H1,
end
--Proposition 8.6b
lemma constant_map_is_continuous {α : Type u} {β : Type v} {X : topological_space α} {Y : topological_space β} {f : α → β} (H : (∃ (b : β), f = function.const α b)) : continuous f :=
begin
unfold continuous,
cases H with b Hb,
rw Hb,
intros s Hs,
by_cases (b ∈ s),
unfold set.preimage,
unfold function.const,
have H : {x : α | b ∈ s} = univ,
apply set.ext,
simp,
intro,
assumption,
rw H,
exact X.is_open_univ,
unfold set.preimage,
unfold function.const,
have H : {x : α | b ∈ s} = ∅,
apply set.ext,
simp,
intro,
assumption,
rw H,
simp,
end
def indiscrete_topology (α : Type u) : topological_space α := {
is_open := λ y, y = ∅ ∨ y = univ,
is_open_univ := or.inr rfl,
is_open_inter := begin
intros s t Hs Ht,
cases Hs with Hsempty Hsuniv;
cases Ht with Htempty Htuniv,
rw Hsempty,
simp,
rw Hsempty,
simp,
rw Htempty,
simp,
rw [Hsuniv, Htuniv],
simp,
end,
is_open_sUnion := begin
intros I HI,
by_cases ∃ t ∈ I, t = univ,
cases h with U HU,
cases HU with U_in_I U_is_univ,
apply or.inr,
rw U_is_univ at U_in_I,
exact set.eq_of_subset_of_subset (set.subset_univ ⋃₀ I) (set.subset_sUnion_of_mem U_in_I),
simp at h,
apply or.inl,
have HI2 : ∀ (t : set α), t ∈ I → t = ∅,
intros t Ht,
cases (HI t Ht),
assumption,
rw h_1 at Ht,
cc,
rw set.sUnion_eq_Union,
apply set.ext,
intro x,
simp,
intros t Ht,
rw (HI2 t Ht),
simp,
end
}
def discrete_topology (α : Type u) : topological_space α := {
is_open := λ y, true,
is_open_univ := trivial,
is_open_inter := λ _ _ _ _, trivial,
is_open_sUnion := λ _ _, trivial,
}
--Proposition 8.6c
lemma maps_from_discrete_are_continuous {α : Type u} {β : Type v} [X : topological_space α] [Y : topological_space β]
(H : X = discrete_topology α)(f : α → β) : continuous f :=
begin
unfold continuous,
unfold is_open,
intros s Hs,
rw H,
trivial,
end
--Proposition 8.6d
lemma maps_to_indiscrete_are_continuous {α : Type u} {β : Type v} [X : topological_space α] [Y : topological_space β]
(H : Y = indiscrete_topology β)(f : α → β) : continuous f :=
begin
unfold continuous,
unfold is_open,
intros s Hs,
rw H at Hs,
cases Hs,
rw Hs,
simp,
rw ←set.sUnion_empty,
exact X.is_open_sUnion ∅ (λ t Ht, false.elim Ht),
rw Hs,
simp,
exact X.is_open_univ,
end
definition id_is_homeomorphism {α : Type u} {X : topological_space α} : homeomorphism X X := {
to_fun := id,
inv_fun := id,
left_inv :=
begin
unfold function.left_inverse,
intro x,
simp,
end,
right_inv :=
begin
unfold function.right_inverse,
intro x,
simp,
end,
to_is_continuous :=
begin
unfold continuous,
unfold set.preimage,
intros s H1,
exact H1,
end,
from_is_continuous :=
begin
unfold continuous,
unfold set.preimage,
intros s H1,
exact H1,
end,
}
theorem homeomorphism_is_reflexive : reflexive (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) :=
begin
unfold reflexive,
intro x,
unfold is_homeomorphic_to,
have hom : homeomorphism (x.snd) (x.snd),
exact id_is_homeomorphism,
exact ⟨hom⟩,
end
theorem homeomorphism_is_symmetric : symmetric (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) :=
begin
unfold symmetric,
intros x y Hxy,
unfold is_homeomorphic_to, unfold is_homeomorphic_to at Hxy,
have homto : homeomorphism x.snd y.snd,
exact classical.choice Hxy,
have homfrom : homeomorphism y.snd x.snd,
exact {to_fun := homto.inv_fun, inv_fun := homto.to_fun, left_inv := homto.right_inv, right_inv := homto.left_inv, to_is_continuous := homto.from_is_continuous, from_is_continuous := homto.to_is_continuous},
exact nonempty.intro homfrom,
end
theorem homeomorphism_is_transitive : transitive (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) :=
begin
unfold transitive,
intros x y z Hxy Hyz,
unfold is_homeomorphic_to at *,
have homxy : homeomorphism x.snd y.snd, by exact classical.choice Hxy,
have homyz : homeomorphism y.snd z.snd, by exact classical.choice Hyz,
have homxz : homeomorphism x.snd z.snd,
exact {to_fun := homyz.to_fun ∘ homxy.to_fun,
inv_fun := homxy.inv_fun ∘ homyz.inv_fun,
left_inv := begin
unfold function.left_inverse,
simp,
intro a,
have H1 : (homyz.to_equiv).inv_fun ∘ (homyz.to_equiv).to_fun = id,
exact function.id_of_left_inverse homyz.left_inv,
rw function.funext_iff at H1,
simp at H1,
rw H1,
have H2 : (homxy.to_equiv).inv_fun ∘ (homxy.to_equiv).to_fun = id,
exact function.id_of_left_inverse homxy.left_inv,
rw function.funext_iff at H2,
simp at H2,
rw H2,
end,
right_inv := begin
unfold function.right_inverse,
unfold function.left_inverse,
simp,
intro a,
have H1: (homxy.to_equiv).to_fun ∘ (homxy.to_equiv).inv_fun = id,
exact function.id_of_right_inverse homxy.right_inv,
rw function.funext_iff at H1,
simp at H1,
rw H1,
have H2 : (homyz.to_equiv).to_fun ∘ (homyz.to_equiv).inv_fun = id,
exact function.id_of_right_inverse homyz.right_inv,
rw function.funext_iff at H2,
simp at H2,
rw H2,
end,
to_is_continuous := begin
exact @continuous.comp _ _ _ x.2 y.2 z.2 _ _ homxy.to_is_continuous homyz.to_is_continuous,
end,
from_is_continuous := begin
exact @continuous.comp _ _ _ z.2 y.2 x.2 _ _ homyz.from_is_continuous homxy.from_is_continuous,
end},
exact nonempty.intro homxz,
end
--Exercise 8.4
theorem homeomorphism_is_equivalence : equivalence (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) := ⟨homeomorphism_is_reflexive, homeomorphism_is_symmetric, homeomorphism_is_transitive⟩
--Proposition 8.12
theorem continuous_basis_to_continuous {α : Type*} {β : Type*} [X : topological_space α] [Y : topological_space β] : ∀ f : α → β, (∀ B : set (set β), topological_space.is_topological_basis B → (∀ b : B, is_open (f ⁻¹' b)) → continuous f) :=
begin
intros f Basis HBasis HBasisInverses U HU,
have HU_union_basis : ∃ S ⊆ Basis, U = ⋃₀ S, by exact topological_space.sUnion_basis_of_is_open HBasis HU,
cases HU_union_basis with S HS,
cases HS with HS1 HS2,
rw HS2,
rw set.preimage_sUnion,
have f_inv_t_open : ∀ t : set β, t ∈ S → topological_space.is_open X (f ⁻¹' t),
intros t HtS,
have t_is_open : topological_space.is_open Y t,
exact topological_space.is_open_of_is_topological_basis HBasis (set.mem_of_subset_of_mem HS1 HtS),
simp at HBasisInverses,
exact HBasisInverses t (set.mem_of_subset_of_mem HS1 HtS),
let set_of_preimages : set (set α) := {x | ∃ t ∈ S, x = f ⁻¹' t},
have preimages_are_open : topological_space.is_open X (⋃₀ set_of_preimages),
have H3 : ∀ (t : set α), t ∈ set_of_preimages → topological_space.is_open X t,
intros tinv Htinv,
simp at Htinv,
cases Htinv with t Ht,
rw Ht.2,
exact f_inv_t_open t Ht.1,
exact X.is_open_sUnion set_of_preimages H3,
unfold is_open,
have equal : (⋃₀ set_of_preimages) = (⋃ (t : set β) (H : t ∈ S), f ⁻¹' t),
rw set.sUnion_eq_Union,
apply set.ext,
intro x,
split,
intro Hx,
simp,
simp at Hx,
cases Hx with f_inv_t Hf_inv_t,
cases Hf_inv_t.1 with t Ht,
existsi t,
split,
exact Ht.1,
rw ← set.mem_preimage_eq,
rw ← Ht.2,
exact Hf_inv_t.2,
intro Hx,
simp,
rw set.mem_Union_eq at Hx,
cases Hx with i Hi,
simp at Hi,
existsi (f ⁻¹' i),
split,
existsi i,
exact ⟨Hi.1, eq.refl (f ⁻¹' i)⟩,
simp,
exact Hi.2,
rw ← equal,
assumption,
end
|
f98dcb4b68255ac7443dadf954f003ecc375f21a | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/normed_space/exponential.lean | 7b45ab0eddfc3c96102edd6514781d97e469baba | [
"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 | 15,900 | lean | /-
Copyright (c) 2021 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.specific_limits
import analysis.analytic.basic
import analysis.complex.basic
/-!
# Exponential in a Banach algebra
In this file, we define `exp 𝕂 𝔸`, the exponential map in a normed algebra `𝔸` over a nondiscrete
normed field `𝕂`. Although the definition doesn't require `𝔸` to be complete, we need to assume it
for most results.
We then prove some basic results, but we avoid importing derivatives here to minimize dependencies.
Results involving derivatives and comparisons with `real.exp` and `complex.exp` can be found in
`analysis/special_functions/exponential`.
## Main results
We prove most result for an arbitrary field `𝕂`, and then specialize to `𝕂 = ℝ` or `𝕂 = ℂ`.
### General case
- `exp_add_of_commute_of_lt_radius` : if `𝕂` has characteristic zero, then given two commuting
elements `x` and `y` in the disk of convergence, we have
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`
- `exp_add_of_lt_radius` : if `𝕂` has characteristic zero and `𝔸` is commutative, then given two
elements `x` and `y` in the disk of convergence, we have
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`
### `𝕂 = ℝ` or `𝕂 = ℂ`
- `exp_series_radius_eq_top` : the `formal_multilinear_series` defining `exp 𝕂 𝔸` has infinite
radius of convergence
- `exp_add_of_commute` : given two commuting elements `x` and `y`, we have
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`
- `exp_add` : if `𝔸` is commutative, then we have `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`
for any `x` and `y`
### Other useful compatibility results
- `exp_eq_exp` : if `𝔸` is a normed algebra over two fields `𝕂` and `𝕂'`, then `exp 𝕂 𝔸 = exp 𝕂' 𝔸`
-/
open filter is_R_or_C continuous_multilinear_map normed_field asymptotics
open_locale nat topological_space big_operators ennreal
section any_field_any_algebra
variables (𝕂 𝔸 : Type*) [nondiscrete_normed_field 𝕂] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸]
/-- In a Banach algebra `𝔸` over a normed field `𝕂`, `exp_series 𝕂 𝔸` is the
`formal_multilinear_series` whose `n`-th term is the map `(xᵢ) : 𝔸ⁿ ↦ (1/n! : 𝕂) • ∏ xᵢ`.
Its sum is the exponential map `exp 𝕂 𝔸 : 𝔸 → 𝔸`. -/
def exp_series : formal_multilinear_series 𝕂 𝔸 𝔸 :=
λ n, (1/n! : 𝕂) • continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸
/-- In a Banach algebra `𝔸` over a normed field `𝕂`, `exp 𝕂 𝔸 : 𝔸 → 𝔸` is the exponential map
determined by the action of `𝕂` on `𝔸`.
It is defined as the sum of the `formal_multilinear_series` `exp_series 𝕂 𝔸`. -/
noncomputable def exp (x : 𝔸) : 𝔸 := (exp_series 𝕂 𝔸).sum x
variables {𝕂 𝔸}
lemma exp_series_apply_eq (x : 𝔸) (n : ℕ) : exp_series 𝕂 𝔸 n (λ _, x) = (1 / n! : 𝕂) • x^n :=
by simp [exp_series]
lemma exp_series_apply_eq' (x : 𝔸) :
(λ n, exp_series 𝕂 𝔸 n (λ _, x)) = (λ n, (1 / n! : 𝕂) • x^n) :=
funext (exp_series_apply_eq x)
lemma exp_series_apply_eq_field (x : 𝕂) (n : ℕ) : exp_series 𝕂 𝕂 n (λ _, x) = x^n / n! :=
begin
rw [div_eq_inv_mul, ←smul_eq_mul, inv_eq_one_div],
exact exp_series_apply_eq x n,
end
lemma exp_series_apply_eq_field' (x : 𝕂) : (λ n, exp_series 𝕂 𝕂 n (λ _, x)) = (λ n, x^n / n!) :=
funext (exp_series_apply_eq_field x)
lemma exp_series_sum_eq (x : 𝔸) : (exp_series 𝕂 𝔸).sum x = ∑' (n : ℕ), (1 / n! : 𝕂) • x^n :=
tsum_congr (λ n, exp_series_apply_eq x n)
lemma exp_series_sum_eq_field (x : 𝕂) : (exp_series 𝕂 𝕂).sum x = ∑' (n : ℕ), x^n / n! :=
tsum_congr (λ n, exp_series_apply_eq_field x n)
lemma exp_eq_tsum : exp 𝕂 𝔸 = (λ x : 𝔸, ∑' (n : ℕ), (1 / n! : 𝕂) • x^n) :=
funext exp_series_sum_eq
lemma exp_eq_tsum_field : exp 𝕂 𝕂 = (λ x : 𝕂, ∑' (n : ℕ), x^n / n!) :=
funext exp_series_sum_eq_field
lemma exp_zero : exp 𝕂 𝔸 0 = 1 :=
begin
suffices : (λ x : 𝔸, ∑' (n : ℕ), (1 / n! : 𝕂) • x^n) 0 = ∑' (n : ℕ), if n = 0 then 1 else 0,
{ have key : ∀ n ∉ ({0} : finset ℕ), (if n = 0 then (1 : 𝔸) else 0) = 0,
from λ n hn, if_neg (finset.not_mem_singleton.mp hn),
rw [exp_eq_tsum, this, tsum_eq_sum key, finset.sum_singleton],
simp },
refine tsum_congr (λ n, _),
split_ifs with h h;
simp [h]
end
lemma norm_exp_series_summable_of_mem_ball (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
summable (λ n, ∥exp_series 𝕂 𝔸 n (λ _, x)∥) :=
(exp_series 𝕂 𝔸).summable_norm_apply hx
lemma norm_exp_series_summable_of_mem_ball' (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
summable (λ n, ∥(1 / n! : 𝕂) • x^n∥) :=
begin
change summable (norm ∘ _),
rw ← exp_series_apply_eq',
exact norm_exp_series_summable_of_mem_ball x hx
end
lemma norm_exp_series_field_summable_of_mem_ball (x : 𝕂)
(hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) :
summable (λ n, ∥x^n / n!∥) :=
begin
change summable (norm ∘ _),
rw ← exp_series_apply_eq_field',
exact norm_exp_series_summable_of_mem_ball x hx
end
section complete_algebra
variables [complete_space 𝔸]
lemma exp_series_summable_of_mem_ball (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) :=
summable_of_summable_norm (norm_exp_series_summable_of_mem_ball x hx)
lemma exp_series_summable_of_mem_ball' (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
summable (λ n, (1 / n! : 𝕂) • x^n) :=
summable_of_summable_norm (norm_exp_series_summable_of_mem_ball' x hx)
lemma exp_series_field_summable_of_mem_ball [complete_space 𝕂] (x : 𝕂)
(hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : summable (λ n, x^n / n!) :=
summable_of_summable_norm (norm_exp_series_field_summable_of_mem_ball x hx)
lemma exp_series_has_sum_exp_of_mem_ball (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 𝔸 x) :=
formal_multilinear_series.has_sum (exp_series 𝕂 𝔸) hx
lemma exp_series_has_sum_exp_of_mem_ball' (x : 𝔸)
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
has_sum (λ n, (1 / n! : 𝕂) • x^n) (exp 𝕂 𝔸 x):=
begin
rw ← exp_series_apply_eq',
exact exp_series_has_sum_exp_of_mem_ball x hx
end
lemma exp_series_field_has_sum_exp_of_mem_ball [complete_space 𝕂] (x : 𝕂)
(hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : has_sum (λ n, x^n / n!) (exp 𝕂 𝕂 x) :=
begin
rw ← exp_series_apply_eq_field',
exact exp_series_has_sum_exp_of_mem_ball x hx
end
lemma has_fpower_series_on_ball_exp_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) :
has_fpower_series_on_ball (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 (exp_series 𝕂 𝔸).radius :=
(exp_series 𝕂 𝔸).has_fpower_series_on_ball h
lemma has_fpower_series_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) :
has_fpower_series_at (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 :=
(has_fpower_series_on_ball_exp_of_radius_pos h).has_fpower_series_at
lemma continuous_on_exp :
continuous_on (exp 𝕂 𝔸) (emetric.ball 0 (exp_series 𝕂 𝔸).radius) :=
formal_multilinear_series.continuous_on
lemma analytic_at_exp_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
analytic_at 𝕂 (exp 𝕂 𝔸) x:=
begin
by_cases h : (exp_series 𝕂 𝔸).radius = 0,
{ rw h at hx, exact (ennreal.not_lt_zero hx).elim },
{ have h := pos_iff_ne_zero.mpr h,
exact (has_fpower_series_on_ball_exp_of_radius_pos h).analytic_at_of_mem hx }
end
/-- In a Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero, if `x` and `y` are
in the disk of convergence and commute, then `exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/
lemma exp_add_of_commute_of_mem_ball [char_zero 𝕂]
{x y : 𝔸} (hxy : commute x y) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius)
(hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) :=
begin
rw [exp_eq_tsum, tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm
(norm_exp_series_summable_of_mem_ball' x hx) (norm_exp_series_summable_of_mem_ball' y hy)],
dsimp only,
conv_lhs {congr, funext, rw [hxy.add_pow' _, finset.smul_sum]},
refine tsum_congr (λ n, finset.sum_congr rfl $ λ kl hkl, _),
rw [nsmul_eq_smul_cast 𝕂, smul_smul, smul_mul_smul, ← (finset.nat.mem_antidiagonal.mp hkl),
nat.cast_add_choose, (finset.nat.mem_antidiagonal.mp hkl)],
congr' 1,
have : (n! : 𝕂) ≠ 0 := nat.cast_ne_zero.mpr n.factorial_ne_zero,
field_simp [this]
end
end complete_algebra
end any_field_any_algebra
section any_field_comm_algebra
variables {𝕂 𝔸 : Type*} [nondiscrete_normed_field 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸]
[complete_space 𝔸]
/-- In a commutative Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero,
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` for all `x`, `y` in the disk of convergence. -/
lemma exp_add_of_mem_ball [char_zero 𝕂] {x y : 𝔸}
(hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius)
(hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) :
exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) :=
exp_add_of_commute_of_mem_ball (commute.all x y) hx hy
end any_field_comm_algebra
section is_R_or_C
section any_algebra
variables (𝕂 𝔸 : Type*) [is_R_or_C 𝕂] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸]
/-- In a normed algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, the series defining the exponential map
has an infinite radius of convergence. -/
lemma exp_series_radius_eq_top : (exp_series 𝕂 𝔸).radius = ∞ :=
begin
refine (exp_series 𝕂 𝔸).radius_eq_top_of_summable_norm (λ r, _),
refine summable_of_norm_bounded_eventually _ (real.summable_pow_div_factorial r) _,
filter_upwards [eventually_cofinite_ne 0],
intros n hn,
rw [norm_mul, norm_norm (exp_series 𝕂 𝔸 n), exp_series, norm_smul, norm_div, norm_one, norm_pow,
nnreal.norm_eq, norm_eq_abs, abs_cast_nat, mul_comm, ←mul_assoc, ←mul_div_assoc, mul_one],
have : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸∥ ≤ 1 :=
norm_mk_pi_algebra_fin_le_of_pos (nat.pos_of_ne_zero hn),
exact mul_le_of_le_one_right (div_nonneg (pow_nonneg r.coe_nonneg n) n!.cast_nonneg) this
end
lemma exp_series_radius_pos : 0 < (exp_series 𝕂 𝔸).radius :=
begin
rw exp_series_radius_eq_top,
exact with_top.zero_lt_top
end
variables {𝕂 𝔸}
section complete_algebra
lemma norm_exp_series_summable (x : 𝔸) : summable (λ n, ∥exp_series 𝕂 𝔸 n (λ _, x)∥) :=
norm_exp_series_summable_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
lemma norm_exp_series_summable' (x : 𝔸) : summable (λ n, ∥(1 / n! : 𝕂) • x^n∥) :=
norm_exp_series_summable_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
lemma norm_exp_series_field_summable (x : 𝕂) : summable (λ n, ∥x^n / n!∥) :=
norm_exp_series_field_summable_of_mem_ball x
((exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _)
variables [complete_space 𝔸]
lemma exp_series_summable (x : 𝔸) : summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) :=
summable_of_summable_norm (norm_exp_series_summable x)
lemma exp_series_summable' (x : 𝔸) : summable (λ n, (1 / n! : 𝕂) • x^n) :=
summable_of_summable_norm (norm_exp_series_summable' x)
lemma exp_series_field_summable (x : 𝕂) : summable (λ n, x^n / n!) :=
summable_of_summable_norm (norm_exp_series_field_summable x)
lemma exp_series_has_sum_exp (x : 𝔸) : has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 𝔸 x) :=
exp_series_has_sum_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
lemma exp_series_has_sum_exp' (x : 𝔸) : has_sum (λ n, (1 / n! : 𝕂) • x^n) (exp 𝕂 𝔸 x):=
exp_series_has_sum_exp_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
lemma exp_series_field_has_sum_exp (x : 𝕂) : has_sum (λ n, x^n / n!) (exp 𝕂 𝕂 x):=
exp_series_field_has_sum_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _)
lemma exp_has_fpower_series_on_ball :
has_fpower_series_on_ball (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 ∞ :=
exp_series_radius_eq_top 𝕂 𝔸 ▸
has_fpower_series_on_ball_exp_of_radius_pos (exp_series_radius_pos _ _)
lemma exp_has_fpower_series_at_zero :
has_fpower_series_at (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 :=
exp_has_fpower_series_on_ball.has_fpower_series_at
lemma exp_continuous :
continuous (exp 𝕂 𝔸) :=
begin
rw [continuous_iff_continuous_on_univ, ← metric.eball_top_eq_univ (0 : 𝔸),
← exp_series_radius_eq_top 𝕂 𝔸],
exact continuous_on_exp
end
lemma exp_analytic (x : 𝔸) :
analytic_at 𝕂 (exp 𝕂 𝔸) x :=
analytic_at_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
end complete_algebra
local attribute [instance] char_zero_R_or_C
/-- In a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, if `x` and `y` commute, then
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/
lemma exp_add_of_commute [complete_space 𝔸]
{x y : 𝔸} (hxy : commute x y) :
exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) :=
exp_add_of_commute_of_mem_ball hxy ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
end any_algebra
section comm_algebra
variables {𝕂 𝔸 : Type*} [is_R_or_C 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸]
local attribute [instance] char_zero_R_or_C
/-- In a comutative Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`,
`exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/
lemma exp_add {x y : 𝔸} : exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) :=
exp_add_of_mem_ball ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _)
end comm_algebra
end is_R_or_C
section scalar_tower
variables (𝕂 𝕂' 𝔸 : Type*) [nondiscrete_normed_field 𝕂] [nondiscrete_normed_field 𝕂']
[normed_ring 𝔸] [normed_algebra 𝕂 𝔸] [normed_algebra 𝕂' 𝔸]
/-- If a normed ring `𝔸` is a normed algebra over two fields, then they define the same
`exp_series` on `𝔸`. -/
lemma exp_series_eq_exp_series (n : ℕ) (x : 𝔸) :
(exp_series 𝕂 𝔸 n (λ _, x)) = (exp_series 𝕂' 𝔸 n (λ _, x)) :=
by rw [exp_series, exp_series,
smul_apply, mk_pi_algebra_fin_apply, list.of_fn_const, list.prod_repeat,
smul_apply, mk_pi_algebra_fin_apply, list.of_fn_const, list.prod_repeat,
one_div, one_div, inv_nat_cast_smul_eq 𝕂 𝕂']
/-- If a normed ring `𝔸` is a normed algebra over two fields, then they define the same
exponential function on `𝔸`. -/
lemma exp_eq_exp : exp 𝕂 𝔸 = exp 𝕂' 𝔸 :=
begin
ext,
rw [exp, exp],
refine tsum_congr (λ n, _),
rw exp_series_eq_exp_series 𝕂 𝕂' 𝔸 n x
end
lemma exp_ℝ_ℂ_eq_exp_ℂ_ℂ : exp ℝ ℂ = exp ℂ ℂ :=
exp_eq_exp ℝ ℂ ℂ
end scalar_tower
|
149d85a669ba6d37f08518211e29b1efd39a2f74 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/over.lean | 8ff5e284e5c127967482eb321c2b3bf8a233d357 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 7,721 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import category_theory.comma
import category_theory.punit
import category_theory.reflect_isomorphisms
/-!
# Over and under categories
Over (and under) categories are special cases of comma categories.
* If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or
"over" category over the object `R` maps to.
* Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the
"coslice" or "under" category under the object `L` maps to.
## Tags
comma, slice, coslice, over, under
-/
namespace category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {T : Type u₁} [category.{v₁} T]
/-- The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative
triangles. -/
@[derive category]
def over (X : T) := comma.{v₁ 0 v₁} (𝟭 T) (functor.from_punit X)
-- Satisfying the inhabited linter
instance over.inhabited [inhabited T] : inhabited (over (default T)) :=
{ default :=
{ left := default T,
hom := 𝟙 _ } }
namespace over
variables {X : T}
@[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V}
(h : f.left = g.left) : f = g :=
by tidy
@[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy
@[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl
@[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).left = f.left ≫ g.left := rfl
@[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom :=
by have := f.w; tidy
/-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/
def mk {X Y : T} (f : Y ⟶ X) : over X :=
{ left := Y, hom := f }
@[simp] lemma mk_left {X Y : T} (f : Y ⟶ X) : (mk f).left = Y := rfl
@[simp] lemma mk_hom {X Y : T} (f : Y ⟶ X) : (mk f).hom = f := rfl
/-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative
triangle. -/
@[simps]
def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) :
U ⟶ V :=
{ left := f }
/-- The forgetful functor mapping an arrow to its domain. -/
def forget : (over X) ⥤ T := comma.fst _ _
@[simp] lemma forget_obj {U : over X} : forget.obj U = U.left := rfl
@[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : forget.map f = f.left := rfl
/-- A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way. -/
def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V}
@[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl
@[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl
end
instance forget_reflects_iso : reflects_isomorphisms (forget : over X ⥤ T) :=
{ reflects := λ X Y f t, by exactI
{ inv := over.hom_mk t.inv ((as_iso (forget.map f)).inv_comp_eq.2 (over.w f).symm) } }
section iterated_slice
variables (f : over X)
/-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/
@[simps]
def iterated_slice_forward : over f ⥤ over f.left :=
{ obj := λ α, over.mk α.hom.left,
map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) }
/-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/
@[simps]
def iterated_slice_backward : over f.left ⥤ over f :=
{ obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f),
map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) }
/-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/
@[simps]
def iterated_slice_equiv : over f ≌ over f.left :=
{ functor := iterated_slice_forward f,
inverse := iterated_slice_backward f,
unit_iso :=
nat_iso.of_components
(λ g, ⟨hom_mk (hom_mk (𝟙 g.left.left)) (by apply_auto_param),
hom_mk (hom_mk (𝟙 g.left.left)) (by apply_auto_param),
by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩)
(λ X Y g, by { ext, dsimp, simp }),
counit_iso :=
nat_iso.of_components
(λ g, ⟨hom_mk (𝟙 g.left) (by apply_auto_param),
hom_mk (𝟙 g.left) (by apply_auto_param),
by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩)
(λ X Y g, by { ext, dsimp, simp }) }
lemma iterated_slice_forward_forget :
iterated_slice_forward f ⋙ forget = forget ⋙ forget :=
rfl
lemma iterated_slice_backward_forget_forget :
iterated_slice_backward f ⋙ forget ⋙ forget = forget :=
rfl
end iterated_slice
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/
def post (F : T ⥤ D) : over X ⥤ over (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ left := F.map f.left,
w' := by tidy; erw [← F.map_comp, w] } }
end
end over
/-- The under category has as objects arrows with domain `X` and as morphisms commutative
triangles. -/
@[derive category]
def under (X : T) := comma.{0 v₁ v₁} (functor.from_punit X) (𝟭 T)
-- Satisfying the inhabited linter
instance under.inhabited [inhabited T] : inhabited (under (default T)) :=
{ default :=
{ right := default T,
hom := 𝟙 _ } }
namespace under
variables {X : T}
@[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V}
(h : f.right = g.right) : f = g :=
by tidy
@[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy
@[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl
@[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).right = f.right ≫ g.right := rfl
@[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom :=
by have := f.w; tidy
/-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/
@[simps]
def mk {X Y : T} (f : X ⟶ Y) : under X :=
{ right := Y, hom := f }
/-- To give a morphism in the under category, it suffices to give a morphism fitting in a
commutative triangle. -/
@[simps]
def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) :
U ⟶ V :=
{ right := f }
/-- The forgetful functor mapping an arrow to its domain. -/
def forget : (under X) ⥤ T := comma.snd _ _
@[simp] lemma forget_obj {U : under X} : forget.obj U = U.right := rfl
@[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : forget.map f = f.right := rfl
/-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/
def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V}
@[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl
@[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl
end
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/
def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ right := F.map f.right,
w' := by tidy; erw [← F.map_comp, w] } }
end
end under
end category_theory
|
545cde802544b5936ca8ae41458e8c0d72d4457b | 42c01158c2730cc6ac3e058c1339c18cb90366e2 | /M1F/group_projects/rational_powers.lean | 45b34d369e16bfa8b2d0af6f96dd71fab55dc4ba | [] | no_license | ChrisHughes24/xena | c80d94355d0c2ae8deddda9d01e6d31bc21c30ae | 337a0d7c9f0e255e08d6d0a383e303c080c6ec0c | refs/heads/master | 1,631,059,898,392 | 1,511,200,551,000 | 1,511,200,551,000 | 111,468,589 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,927 | lean | -- let's define the real numbers to be a number system which satisfies
-- the basic properties of the real numbers which we will need.
noncomputable theory
constant real : Type
@[instance] constant real_field : linear_ordered_field real
-- This piece of magic means that "real" now behaves a lot like
-- the real numbers. In particular we now have a bunch
-- of theorems:
example : ∀ x y : real, x * y = y * x := mul_comm
#check mul_assoc
variable x : real
variable n : nat
-- We do _not_ have powers though. So we need to make them.
open nat
definition natural_power : real → nat → real
| x 0 := 1
| x (succ n) := (natural_power x n) * x
-- Proof by Eduard Oravkin
theorem T1 : ∀ x:real, ∀ m n:nat, natural_power x (m+n) = natural_power x m *natural_power x n :=
begin
intro x, intro m, intro n,
induction n with s H1,
have H : natural_power x 0 = 1,
refl,
rw [add_zero, H , mul_one],
unfold natural_power,
rw [← mul_assoc, H1],
end
-- Proof by Chris Hughes
theorem T2 : ∀ x: real, ∀ m n : nat, natural_power (natural_power x m) n = natural_power x (m*n) :=
begin
assume x m n,
induction n with n H,
unfold natural_power,
rw [mul_zero, eq_comm],
unfold natural_power,
rw [succ_eq_add_one,mul_add,mul_one,add_one],
unfold natural_power,
rw [T1,H]
end
-- Proof by Ali Barkhordarian
theorem T3 : ∀ x y: real, ∀ n : nat, natural_power x n * natural_power y n = natural_power (x*y) n :=
begin
assume x y n,
induction n with n H,
unfold natural_power,
exact one_mul 1,
unfold natural_power,
rw [mul_assoc],
rw [← mul_assoc x],
rw [mul_comm x],
rw [mul_assoc, ←mul_assoc],
rw [H]
end
constant nth_root (x : real) (n : nat) : (x>0) → (n>0) → real
axiom is_nth_root (x : real) (n : nat) (Hx : x>0) (Hn : n>0) : natural_power (nth_root x n Hx Hn) n = x
definition rational_power_v0 (x : real) (n : nat) (d : nat) (Hx : x > 0) (Hd : d > 0) : real :=
natural_power (nth_root x d Hx Hd) n
|
83e718c4609f05676b9fac20801ea2feebaf5c55 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/complex/basic.lean | ad138d39c1f16f20fd4a559d11b8b2f05bca985e | [
"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 | 26,719 | lean | /-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Mario Carneiro
-/
import data.real.sqrt
/-!
# The complex numbers
The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field
of characteristic zero. The result that the complex numbers are algebraically closed, see
`field_theory.algebraic_closure`.
-/
open_locale big_operators
/-! ### Definition and basic arithmmetic -/
/-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
namespace complex
noncomputable instance : decidable_eq ℂ := classical.dec_eq _
/-- The equivalence between the complex numbers and `ℝ × ℝ`. -/
def equiv_real_prod : ℂ ≃ (ℝ × ℝ) :=
{ to_fun := λ z, ⟨z.re, z.im⟩,
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := λ ⟨x, y⟩, rfl,
right_inv := λ ⟨x, y⟩, rfl }
@[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl
theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl
theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨a, b⟩ := rfl
@[ext]
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩
@[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl
@[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
instance : has_zero ℂ := ⟨(0 : ℝ)⟩
instance : inhabited ℂ := ⟨0⟩
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
instance : has_one ℂ := ⟨(1 : ℝ)⟩
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
@[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl
@[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl
@[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _
@[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _
@[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s :=
ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r :=
ext_iff.2 $ by simp [bit0]
@[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r :=
ext_iff.2 $ by simp [bit1]
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
@[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp
instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
@[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp
lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp
lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ :=
ext (of_real_mul_re _ _) (of_real_mul_im _ _)
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
@[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp
lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ :=
ext_iff.2 $ by simp
lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
/-! ### Commutative ring instance and lemmas -/
instance : comm_ring ℂ :=
by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, one := 1, mul := (*),
sub_eq_add_neg := _, ..};
{ intros, apply ext_iff.2; split; simp; {ring1 <|> ring_nf} }
instance re.is_add_group_hom : is_add_group_hom complex.re :=
{ map_add := complex.add_re }
instance im.is_add_group_hom : is_add_group_hom complex.im :=
{ map_add := complex.add_im }
@[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [pow_bit0', I_mul_I]
@[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [pow_bit1', I_mul_I]
/-! ### Complex conjugation -/
/-- The complex conjugate. -/
def conj : ℂ →+* ℂ :=
begin
refine_struct { to_fun := λ z : ℂ, (⟨z.re, -z.im⟩ : ℂ), .. };
{ intros, ext; simp [add_comm], },
end
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
@[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp
@[simp] lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0]
@[simp] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0]
@[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp
@[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z :=
ext_iff.2 $ by simp
lemma conj_involutive : function.involutive conj := conj_conj
lemma conj_bijective : function.bijective conj := conj_involutive.bijective
lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w :=
conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 :=
by simpa using @conj_inj z 0
lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, by rw [e, conj_of_real]⟩
lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
instance : star_ring ℂ :=
{ star := λ z, conj z,
star_involutive := λ z, by simp,
star_mul := λ r s, by { ext; simp [mul_comm], },
star_add := by simp, }
/-! ### Norm squared -/
/-- The norm squared function. -/
@[pp_nodot] def norm_sq : monoid_with_zero_hom ℂ ℝ :=
{ to_fun := λ z, z.re * z.re + z.im * z.im,
map_zero' := by simp,
map_one' := by simp,
map_mul' := λ z w, by { dsimp, ring } }
lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z :=
by { ext; simp [norm_sq, mul_comm], }
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
(norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero)
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
norm_sq.map_mul z w
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
/-- The coercion `ℝ → ℂ` as a `ring_hom`. -/
def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩
@[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl
@[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I]
@[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl
@[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl
@[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I :=
ext_iff.2 $ by simp [two_mul, sub_eq_add_neg]
lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * (z * conj w).re :=
by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg]
/-! ### Inversion -/
noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩
theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl
@[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def]
@[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def]
@[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ :=
ext_iff.2 $ by simp
protected lemma inv_zero : (0⁻¹ : ℂ) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul,
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
/-! ### Field instance and lemmas -/
noncomputable instance : field ℂ :=
{ inv := has_inv.inv,
exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩,
mul_inv_cancel := @complex.mul_inv_cancel,
inv_zero := complex.inv_zero,
..complex.comm_ring }
@[simp] lemma I_fpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [fpow_bit0', I_mul_I]
@[simp] lemma I_fpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [fpow_bit1', I_mul_I]
lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg]
lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm]
@[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s :=
of_real.map_div r s
@[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n :=
of_real.map_fpow r n
@[simp] lemma div_I (z : ℂ) : z / I = -(z * I) :=
(div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc]
@[simp] lemma inv_I : I⁻¹ = -I :=
by simp [inv_eq_one_div]
@[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
norm_sq.map_inv' z
@[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w :=
norm_sq.map_div z w
/-! ### Cast lemmas -/
@[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n :=
of_real.map_nat_cast n
@[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n :=
of_real.map_int_cast n
@[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n :=
of_real.map_rat_cast n
@[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 :=
by rw [← of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
instance char_zero_complex : char_zero ℂ :=
char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
/-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/
theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 :=
by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0,
mul_div_cancel_left (z.re:ℂ) two_ne_zero']
/-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/
theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) :=
by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm,
mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)]
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt
local notation `abs'` := _root_.abs
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = abs' r :=
by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : ℕ) : complex.abs n = n :=
calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast]
... = _ : abs_of_nonneg (nat.cast_nonneg n)
lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp] lemma abs_zero : abs 0 = 0 := by simp [abs]
@[simp] lemma abs_one : abs 1 = 1 := by simp [abs]
@[simp] lemma abs_I : abs I = 1 := by simp [abs]
@[simp] lemma abs_two : abs 2 = 2 :=
calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : ℂ) : 0 ≤ abs z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 :=
not_congr abs_eq_zero
@[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : ℂ) : z.re ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : ℂ) : z.im ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value abs :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs
lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
@[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
@[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑(abs' n) = abs n :=
by rw [← of_real_int_cast, abs_of_real, int.cast_abs]
lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 :=
by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)]
/--
We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative.
Complex numbers with different imaginary parts are incomparable.
-/
def complex_order : partial_order ℂ :=
{ le := λ z w, ∃ x : ℝ, 0 ≤ x ∧ w = z + x,
le_refl := λ x, ⟨0, by simp⟩,
le_trans := λ x y z h₁ h₂,
begin
obtain ⟨w₁, l₁, rfl⟩ := h₁,
obtain ⟨w₂, l₂, rfl⟩ := h₂,
refine ⟨w₁ + w₂, _, _⟩,
{ linarith, },
{ simp [add_assoc], },
end,
le_antisymm := λ z w h₁ h₂,
begin
obtain ⟨w₁, l₁, rfl⟩ := h₁,
obtain ⟨w₂, l₂, e⟩ := h₂,
have h₃ : w₁ + w₂ = 0,
{ symmetry,
rw add_assoc at e,
apply of_real_inj.mp,
apply add_left_cancel,
convert e; simp, },
have h₄ : w₁ = 0, linarith,
simp [h₄],
end, }
localized "attribute [instance] complex_order" in complex_order
section complex_order
open_locale complex_order
lemma le_def {z w : ℂ} : z ≤ w ↔ ∃ x : ℝ, 0 ≤ x ∧ w = z + x := iff.refl _
lemma lt_def {z w : ℂ} : z < w ↔ ∃ x : ℝ, 0 < x ∧ w = z + x :=
begin
rw [lt_iff_le_not_le],
fsplit,
{ rintro ⟨⟨x, l, rfl⟩, h⟩,
by_cases hx : x = 0,
{ simp [hx] at h, exfalso, exact h (le_refl _), },
{ replace l : 0 < x := l.lt_of_ne (ne.symm hx),
exact ⟨x, l, rfl⟩, } },
{ rintro ⟨x, l, rfl⟩,
fsplit,
{ exact ⟨x, l.le, rfl⟩, },
{ rintro ⟨x', l', e⟩,
rw [add_assoc] at e,
replace e := add_left_cancel (by { convert e, simp }),
norm_cast at e,
linarith, } }
end
@[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y :=
begin
rw [le_def],
fsplit,
{ rintro ⟨r, l, e⟩,
norm_cast at e,
subst e,
exact le_add_of_nonneg_right l, },
{ intro h,
exact ⟨y - x, sub_nonneg.mpr h, (by simp)⟩, },
end
@[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y :=
begin
rw [lt_def],
fsplit,
{ rintro ⟨r, l, e⟩,
norm_cast at e,
subst e,
exact lt_add_of_pos_right x l, },
{ intro h,
exact ⟨y - x, sub_pos.mpr h, (by simp)⟩, },
end
@[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real
@[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring.
-/
def complex_ordered_comm_ring : ordered_comm_ring ℂ :=
{ zero_le_one := ⟨1, zero_le_one, by simp⟩,
add_le_add_left := λ w z h y,
begin
obtain ⟨x, l, rfl⟩ := h,
exact ⟨x, l, by simp [add_assoc]⟩,
end,
mul_pos := λ z w hz hw,
begin
obtain ⟨zx, lz, rfl⟩ := lt_def.mp hz,
obtain ⟨wx, lw, rfl⟩ := lt_def.mp hw,
norm_cast,
simp only [mul_pos, lz, lw, zero_add],
end,
le_of_add_le_add_left := λ u v z h,
begin
obtain ⟨x, l, e⟩ := h,
rw add_assoc at e,
exact ⟨x, l, add_left_cancel e⟩,
end,
mul_lt_mul_of_pos_left := λ u v z h₁ h₂,
begin
obtain ⟨x₁, l₁, rfl⟩ := lt_def.mp h₁,
obtain ⟨x₂, l₂, rfl⟩ := lt_def.mp h₂,
simp only [mul_add, zero_add],
exact lt_def.mpr ⟨x₂ * x₁, mul_pos l₂ l₁, (by norm_cast)⟩,
end,
mul_lt_mul_of_pos_right := λ u v z h₁ h₂,
begin
obtain ⟨x₁, l₁, rfl⟩ := lt_def.mp h₁,
obtain ⟨x₂, l₂, rfl⟩ := lt_def.mp h₂,
simp only [add_mul, zero_add],
exact lt_def.mpr ⟨x₁ * x₂, mul_pos l₁ l₂, (by norm_cast)⟩,
end,
-- we need more instances here because comm_ring doesn't have zero_add et al as fields,
-- they are derived as lemmas
..(by apply_instance : partial_order ℂ),
..(by apply_instance : comm_ring ℂ),
..(by apply_instance : comm_semiring ℂ),
..(by apply_instance : add_cancel_monoid ℂ) }
localized "attribute [instance] complex_ordered_comm_ring" in complex_order
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring.
(That is, an ordered ring in which every element of the form `star z * z` is nonnegative.)
In fact, the nonnegative elements are precisely those of this form.
This hold in any `C^*`-algebra, e.g. `ℂ`,
but we don't yet have `C^*`-algebras in mathlib.
-/
def complex_star_ordered_ring : star_ordered_ring ℂ :=
{ star_mul_self_nonneg := λ z,
begin
refine ⟨z.abs^2, pow_nonneg (abs_nonneg z) 2, _⟩,
simp only [has_star.star, of_real_pow, zero_add],
norm_cast,
rw [←norm_sq_eq_abs, norm_sq_eq_conj_mul_self],
end, }
localized "attribute [instance] complex_star_ordered_ring" in complex_order
end complex_order
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
/-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
/-- The limit of a Cauchy sequence of complex numbers. -/
noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ :=
⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩
theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) :=
λ ε ε0, (exists_forall_ge_and
(cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0))
(cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $
λ i H j ij, begin
cases H _ ij with H₁ H₂,
apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _),
dsimp [lim_aux] at *,
have := add_lt_add H₁ H₂,
rwa add_halves at this,
end
noncomputable instance : cau_seq.is_complete ℂ abs :=
⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩
open cau_seq
lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f =
↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I :=
lim_eq_of_equiv_const $
calc f ≈ _ : equiv_lim_aux f
... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) :
cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im]))
lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) :=
λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in
⟨i, λ j hj, by rw [← conj.map_sub, abs_conj]; exact hi j hj⟩
/-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/
noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs :=
⟨_, is_cau_seq_conj f⟩
lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) :=
complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re])
(by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl)
/-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_abs f.2⟩
lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) :=
lim_eq_of_equiv_const (λ ε ε0,
let ⟨i, hi⟩ := equiv_lim f ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩)
@[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) :
((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) :=
ring_hom.map_prod of_real _ _
@[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) :
((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) :=
ring_hom.map_sum of_real _ _
end complex
|
ba80306a0a479163742d3b1fb8b0b7f6704d41d6 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Elab/Tactic/Generalize.lean | bb1923a0a502edb36413bbfebb540a9e3e2f8b5b | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,795 | 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.Meta.Tactic.Generalize
import Lean.Meta.Check
import Lean.Meta.Tactic.Intro
import Lean.Elab.Tactic.ElabTerm
namespace Lean
namespace Elab
namespace Tactic
open Meta
private def getAuxHypothesisName (stx : Syntax) : Option Name :=
if (stx.getArg 1).isNone then none
else some ((stx.getArg 1).getIdAt 0)
private def getVarName (stx : Syntax) : Name :=
stx.getIdAt 4
private def evalGeneralizeFinalize (mvarId : MVarId) (e : Expr) (target : Expr) : MetaM (List MVarId) := do
tag ← Meta.getMVarTag mvarId;
eType ← inferType e;
u ← Meta.getLevel eType;
mvar' ← Meta.mkFreshExprSyntheticOpaqueMVar target tag;
let rfl := mkApp2 (Lean.mkConst `Eq.refl [u]) eType e;
let val := mkApp2 mvar' e rfl;
assignExprMVar mvarId val;
let mvarId' := mvar'.mvarId!;
(_, mvarId') ← Meta.introNP mvarId' 2;
pure [mvarId']
private def evalGeneralizeWithEq (h : Name) (e : Expr) (x : Name) : TacticM Unit :=
liftMetaTactic $ fun mvarId => do
mvarId ← Meta.generalize mvarId e x false;
mvarDecl ← getMVarDecl mvarId;
match mvarDecl.type with
| Expr.forallE _ _ b _ => do
(_, mvarId) ← Meta.intro1P mvarId;
eType ← inferType e;
u ← Meta.getLevel eType;
let eq := mkApp3 (Lean.mkConst `Eq [u]) eType e (mkBVar 0);
let target := Lean.mkForall x BinderInfo.default eType $ Lean.mkForall h BinderInfo.default eq (b.liftLooseBVars 0 1);
evalGeneralizeFinalize mvarId e target
| _ => throwError "unexpected type after generalize"
-- If generalizing fails, fall back to not replacing anything
private def evalGeneralizeFallback (h : Name) (e : Expr) (x : Name) : TacticM Unit :=
liftMetaTactic $ fun mvarId => do
eType ← inferType e;
u ← Meta.getLevel eType;
mvarType ← Meta.getMVarType mvarId;
let eq := mkApp3 (Lean.mkConst `Eq [u]) eType e (mkBVar 0);
let target := Lean.mkForall x BinderInfo.default eType $ Lean.mkForall h BinderInfo.default eq mvarType;
evalGeneralizeFinalize mvarId e target
def evalGeneralizeAux (h? : Option Name) (e : Expr) (x : Name) : TacticM Unit :=
match h? with
| none => liftMetaTactic $ fun mvarId => do
mvarId ← Meta.generalize mvarId e x false;
(_, mvarId) ← Meta.intro1P mvarId;
pure [mvarId]
| some h =>
evalGeneralizeWithEq h e x <|> evalGeneralizeFallback h e x
@[builtinTactic Lean.Parser.Tactic.generalize] def evalGeneralize : Tactic :=
fun stx => do
let h? := getAuxHypothesisName stx;
let x := getVarName stx;
e ← elabTerm (stx.getArg 2) none;
evalGeneralizeAux h? e x
end Tactic
end Elab
end Lean
|
216a7a9fb089455a13a61aa06e790833a831a2a2 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/special_functions/trigonometric/bounds.lean | d0ad2627ea9e4098fff170367aa85d05d01f9d8a | [
"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,377 | lean | /-
Copyright (c) 2022 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import analysis.special_functions.trigonometric.basic
import analysis.special_functions.trigonometric.arctan_deriv
/-!
# Polynomial bounds for trigonometric functions
## Main statements
This file contains upper and lower bounds for real trigonometric functions in terms
of polynomials. See `trigonometric.basic` for more elementary inequalities, establishing
the ranges of these functions, and their monotonicity in suitable intervals.
Here we prove the following:
* `sin_lt`: for `x > 0` we have `sin x < x`.
* `sin_gt_sub_cube`: For `0 < x ≤ 1` we have `x - x ^ 3 / 4 < sin x`.
* `lt_tan`: for `0 < x < π/2` we have `x < tan x`.
## Tags
sin, cos, tan, angle
-/
noncomputable theory
open set
namespace real
open_locale real
/-- For 0 < x, we have sin x < x. -/
lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x :=
begin
cases lt_or_le 1 x with h' h',
{ exact (sin_le_one x).trans_lt h' },
have hx : |x| = x := abs_of_nonneg h.le,
have := le_of_abs_le (sin_bound $ show |x| ≤ 1, by rwa [hx]),
rw [sub_le_iff_le_add', hx] at this,
apply this.trans_lt,
rw [sub_add, sub_lt_self_iff, sub_pos, div_eq_mul_inv (x ^ 3)],
refine mul_lt_mul' _ (by norm_num) (by norm_num) (pow_pos h 3),
apply pow_le_pow_of_le_one h.le h',
norm_num
end
/-- For 0 < x ≤ 1 we have x - x ^ 3 / 4 < sin x.
This is also true for x > 1, but it's nontrivial for x just above 1. This inequality is not
tight; the tighter inequality is sin x > x - x ^ 3 / 6 for all x > 0, but this inequality has
a simpler proof. -/
lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x :=
begin
have hx : |x| = x := abs_of_nonneg h.le,
have := neg_le_of_abs_le (sin_bound $ show |x| ≤ 1, by rwa [hx]),
rw [le_sub_iff_add_le, hx] at this,
refine lt_of_lt_of_le _ this,
have : x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 * 12⁻¹ := by norm_num [div_eq_mul_inv, ← mul_sub],
rw [add_comm, sub_add, sub_neg_eq_add, sub_lt_sub_iff_left, ←lt_sub_iff_add_lt', this],
refine mul_lt_mul' _ (by norm_num) (by norm_num) (pow_pos h 3),
apply pow_le_pow_of_le_one h.le h',
norm_num
end
/-- The derivative of `tan x - x` is `1/(cos x)^2 - 1` away from the zeroes of cos. -/
lemma deriv_tan_sub_id (x : ℝ) (h : cos x ≠ 0) :
deriv (λ y : ℝ, tan y - y) x = 1 / cos x ^ 2 - 1 :=
has_deriv_at.deriv $ by simpa using (has_deriv_at_tan h).add (has_deriv_at_id x).neg
/-- For all `0 ≤ x < π/2` we have `x < tan x`.
This is proved by checking that the function `tan x - x` vanishes
at zero and has non-negative derivative. -/
theorem lt_tan (x : ℝ) (h1 : 0 < x) (h2 : x < π / 2) : x < tan x :=
begin
let U := Ico 0 (π / 2),
have intU : interior U = Ioo 0 (π / 2) := interior_Ico,
have half_pi_pos : 0 < π / 2 := div_pos pi_pos two_pos,
have cos_pos : ∀ {y : ℝ}, y ∈ U → 0 < cos y,
{ intros y hy,
exact cos_pos_of_mem_Ioo (Ico_subset_Ioo_left (neg_lt_zero.mpr half_pi_pos) hy) },
have sin_pos : ∀ {y : ℝ}, y ∈ interior U → 0 < sin y,
{ intros y hy,
rw intU at hy,
exact sin_pos_of_mem_Ioo (Ioo_subset_Ioo_right (div_le_self pi_pos.le one_le_two) hy) },
have tan_cts_U : continuous_on tan U,
{ apply continuous_on.mono continuous_on_tan,
intros z hz,
simp only [mem_set_of_eq],
exact (cos_pos hz).ne' },
have tan_minus_id_cts : continuous_on (λ y : ℝ, tan y - y) U :=
tan_cts_U.sub continuous_on_id,
have deriv_pos : ∀ y : ℝ, y ∈ interior U → 0 < deriv (λ y' : ℝ, tan y' - y') y,
{ intros y hy,
have := cos_pos (interior_subset hy),
simp only [deriv_tan_sub_id y this.ne', one_div, gt_iff_lt, sub_pos],
have bd2 : cos y ^ 2 < 1,
{ apply lt_of_le_of_ne y.cos_sq_le_one,
rw cos_sq',
simpa only [ne.def, sub_eq_self, pow_eq_zero_iff, nat.succ_pos']
using (sin_pos hy).ne' },
rwa [lt_inv, inv_one],
{ exact zero_lt_one },
simpa only [sq, mul_self_pos] using this.ne' },
have mono := convex.strict_mono_on_of_deriv_pos (convex_Ico 0 (π / 2)) tan_minus_id_cts deriv_pos,
have zero_in_U : (0 : ℝ) ∈ U,
{ rwa left_mem_Ico },
have x_in_U : x ∈ U := ⟨h1.le, h2⟩,
simpa only [tan_zero, sub_zero, sub_pos] using mono zero_in_U x_in_U h1
end
end real
|
2f5468fabc1a967d5dfc1637c3685113791f6950 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/finiteness.lean | c9e7c23eed13a94e62c9913eb3276abe342c8546 | [
"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 | 33,173 | 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
import ring_theory.ideal.operations
import ring_theory.algebra_tower
import group_theory.finiteness
/-!
# Finiteness conditions in commutative algebra
In this file we define several notions of finiteness that are common in commutative algebra.
## Main declarations
- `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite`
all of these express that some object is finitely generated *as module* over some base ring.
- `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type`
all of these express that some object is finitely generated *as algebra* over some base ring.
- `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation`
all of these express that some object is finitely presented *as algebra* over some base ring.
-/
open function (surjective)
open_locale big_operators
section module_and_algebra
variables (R A B M N : Type*) [comm_ring R]
variables [comm_ring A] [algebra R A] [comm_ring B] [algebra R B]
variables [add_comm_group M] [module R M]
variables [add_comm_group N] [module R N]
/-- A module over a commutative ring is `finite` if it is finitely generated as a module. -/
class module.finite (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] :
Prop := (out : (⊤ : submodule R M).fg)
/-- An algebra over a commutative ring is of `finite_type` if it is finitely generated
over the base ring as algebra. -/
class algebra.finite_type : Prop := (out : (⊤ : subalgebra R A).fg)
/-- An algebra over a commutative ring is `finite_presentation` if it is the quotient of a
polynomial ring in `n` variables by a finitely generated ideal. -/
def algebra.finite_presentation : Prop :=
∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A),
surjective f ∧ f.to_ring_hom.ker.fg
namespace module
lemma finite_def {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] :
finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian.finite [is_noetherian R M] : finite R M :=
⟨is_noetherian.noetherian ⊤⟩
namespace finite
open submodule set
lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M :=
⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h),
λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩
lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G :=
⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h),
λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩
variables {R M N}
lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ :=
submodule.fg_iff_exists_fin_generating_family.mp out
lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) :
finite R N :=
⟨begin
rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top],
exact submodule.fg_map hM.1
end⟩
lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N)
(hf : function.injective f) : finite R M :=
⟨fg_of_injective f $ linear_map.ker_eq_bot.2 hf⟩
variables (R)
instance self : finite R R :=
⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩
variables {R}
instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) :=
⟨begin
rw ← submodule.prod_top,
exact submodule.fg_prod hM.1 hN.1
end⟩
lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N :=
of_surjective (e : M →ₗ[R] N) e.surjective
section algebra
lemma trans [algebra A B] [is_scalar_tower R A B] :
∀ [finite R A] [finite A B], finite R B
| ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2
⟨set.image2 (•) (↑s : set A) (↑t : set B),
set.finite.image2 _ s.finite_to_set t.finite_to_set,
by rw [set.image2_smul, submodule.span_smul hs (↑t : set B),
ht, submodule.restrict_scalars_top]⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance finite_type [hRA : finite R A] : algebra.finite_type R A :=
⟨subalgebra.fg_of_submodule_fg hRA.1⟩
end algebra
end finite
end module
namespace algebra
namespace finite_type
lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩
section
open_locale classical
protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) :=
⟨⟨finset.univ.image mv_polynomial.X, begin
rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p
(λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x)
(λ i n f hif hn ih, _))
(λ p q ihp ihq, subalgebra.add_mem _ ihp ihq),
rw [add_comm, mv_polynomial.monomial_add_single],
exact subalgebra.mul_mem _ ih
(subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _)
end⟩⟩
end
variables {R A B}
lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) :
finite_type R B :=
⟨begin
convert subalgebra.fg_map _ f hRA.1,
simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf
end⟩
lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B :=
hRA.of_surjective e e.surjective
lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) :
finite_type R B :=
⟨fg_trans' hRA.1 hAB.1⟩
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a finset. -/
lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A)
(f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rintro ⟨s, hs⟩,
use [s, mv_polynomial.aeval coe],
intro x,
have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl,
rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs],
exact set.mem_univ x },
{ rintro ⟨s, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a fintype. -/
lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) [fintype ι]
(f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial,
rintro ⟨s, ⟨f, hsur⟩⟩,
use [{x // x ∈ s}, by apply_instance, f, hsur] },
{ rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩,
letI : fintype ι := hfintype,
exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n`
variables. -/
lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ)
(f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial',
rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩,
letI := hfintype,
obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) hfintype,
replace equiv := mv_polynomial.rename_equiv R equiv,
exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur
(alg_equiv.symm equiv).surjective⟩ },
{ rintro ⟨n, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur }
end
/-- A finitely presented algebra is of finite type. -/
lemma of_finite_presentation : finite_presentation R A → finite_type R A :=
begin
rintro ⟨n, f, hf⟩,
apply (finite_type.iff_quotient_mv_polynomial'').2,
exact ⟨n, f, hf.1⟩
end
instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) :=
⟨begin
rw ← subalgebra.prod_top,
exact subalgebra.fg_prod hA.1 hB.1
end⟩
end finite_type
namespace finite_presentation
variables {R A B}
/-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely
presented. -/
lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A :=
begin
refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩,
obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h,
refine ⟨n, f, hf, _⟩,
have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance,
replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian,
exact hnoet f.to_ring_hom.ker,
end
/-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/
lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B :=
begin
obtain ⟨n, f, hf⟩ := hfp,
use [n, alg_hom.comp ↑e f],
split,
{ exact function.surjective.comp e.surjective hf.1 },
suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker,
{ rw hker, exact hf.2 },
{ have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom,
{ have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl,
have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl,
rw [h, h1] },
rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot,
ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] }
end
variable (R)
/-- The ring of polynomials in finitely many variables is finitely presented. -/
lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) :=
begin
obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _,
replace equiv := mv_polynomial.rename_equiv R equiv,
refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩,
split,
{ exact (alg_equiv.symm equiv).surjective },
suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom,
{ rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj],
exact submodule.fg_bot },
exact (alg_equiv.symm equiv).injective
end
/-- `R` is finitely presented as `R`-algebra. -/
lemma self : finite_presentation R R :=
equiv (mv_polynomial R pempty) (mv_polynomial.pempty_alg_equiv R)
variable {R}
/-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely
presented. -/
lemma quotient {I : ideal A} (h : submodule.fg I) (hfp : finite_presentation R A) :
finite_presentation R I.quotient :=
begin
obtain ⟨n, f, hf⟩ := hfp,
refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩,
{ exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 },
{ refine submodule.fg_ker_ring_hom_comp _ _ hf.2 _ hf.1,
simp [h] }
end
/-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented,
then so is `B`. -/
lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg)
(hfp : finite_presentation R A) : finite_presentation R B :=
equiv (quotient hker hfp) (ideal.quotient_ker_alg_equiv_of_surjective hf)
lemma iff : finite_presentation R A ↔
∃ n (I : ideal (_root_.mv_polynomial (fin n) R)) (e : I.quotient ≃ₐ[R] A), I.fg :=
begin
refine ⟨λ h,_, λ h, _⟩,
{ obtain ⟨n, f, hf⟩ := h,
use [n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2] },
{ obtain ⟨n, I, e, hfg⟩ := h,
exact equiv (quotient hfg (mv_polynomial R _)) e }
end
/-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose
variables are indexed by a fintype by a finitely generated ideal. -/
lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) [fintype ι]
(f : (_root_.mv_polynomial ι R) →ₐ[R] A), (surjective f) ∧ f.to_ring_hom.ker.fg :=
begin
split,
{ rintro ⟨n, f, hfs, hfk⟩,
set ulift_var := mv_polynomial.rename_equiv R equiv.ulift,
refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom,
hfs.comp ulift_var.surjective,
submodule.fg_ker_ring_hom_comp _ _ _ hfk ulift_var.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, },
{ rintro ⟨ι, hfintype, f, hf⟩,
haveI : fintype ι := hfintype,
obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _,
replace equiv := mv_polynomial.rename_equiv R equiv,
refine ⟨fintype.card ι, f.comp equiv.symm,
hf.1.comp (alg_equiv.symm equiv).surjective,
submodule.fg_ker_ring_hom_comp _ f _ hf.2 equiv.symm.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), }
end
/-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented
as `R`-algebra. -/
lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*)
[fintype ι] : finite_presentation R (_root_.mv_polynomial ι A) :=
begin
classical,
let n := fintype.card ι,
obtain ⟨e⟩ := fintype.trunc_equiv_fin ι,
replace e := (mv_polynomial.rename_equiv A e).restrict_scalars R,
refine equiv _ e.symm,
obtain ⟨m, I, e, hfg⟩ := iff.1 hfp,
refine equiv _ (mv_polynomial.map_alg_equiv (fin n) e),
-- typeclass inference seems to struggle to find this path
letI : is_scalar_tower R
(_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin m) R) :=
is_scalar_tower.right,
letI : is_scalar_tower R
(_root_.mv_polynomial (fin m) R)
(_root_.mv_polynomial (fin n) (_root_.mv_polynomial (fin m) R)) :=
mv_polynomial.is_scalar_tower,
refine equiv _ ((@mv_polynomial.quotient_equiv_quotient_mv_polynomial
_ (fin n) _ I).restrict_scalars R).symm,
refine quotient (submodule.map_fg_of_fg I hfg _) _,
let := mv_polynomial.sum_alg_equiv R (fin n) (fin m),
refine equiv _ this,
exact equiv (mv_polynomial R (fin (n + m))) (mv_polynomial.rename_equiv R fin_sum_fin_equiv).symm
end
/-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is
finitely presented as `R`-algebra. -/
lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A)
(hfpB : finite_presentation A B) : finite_presentation R B :=
begin
obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB,
exact equiv (quotient hfg (mv_polynomial_of_finite_presentation hfpA _)) (e.restrict_scalars R)
end
end finite_presentation
end algebra
end module_and_algebra
namespace ring_hom
variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C]
/-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/
def finite (f : A →+* B) : Prop :=
by letI : algebra A B := f.to_algebra; exact module.finite A B
/-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra
/-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as
`A`-algebra. -/
def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra
namespace finite
variables (A)
lemma id : finite (ring_hom.id A) := module.finite.self A
variables {A}
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite :=
begin
letI := f.to_algebra,
exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf
end
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite :=
@module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
end finite
namespace finite_type
variables (A)
lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
@algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf
{ to_fun := g, commutes' := λ a, rfl, .. g } hg
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf }
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
@algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type :=
@algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf
end finite_type
namespace finite_presentation
variables (A)
lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g)
(hker : g.ker.fg) : (g.comp f).finite_presentation :=
@algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra
{ to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf
lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf hker}
lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation :=
@algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) :
(g.comp f).finite_presentation :=
@algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
{ smul_assoc := λ a b c, begin
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end }
hf hg
end finite_presentation
end ring_hom
namespace alg_hom
variables {R A B C : Type*} [comm_ring R]
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra R A] [algebra R B] [algebra R C]
/-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism.
In other words, if `B` is finitely generated as `A`-module. -/
def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite
/-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism.
In other words, if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type
/-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as
ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/
def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation
namespace finite
variables (R A)
lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite :=
ring_hom.finite.comp hg hf
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite :=
ring_hom.finite.of_surjective f hf
lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f :=
ring_hom.finite.finite_type hf
end finite
namespace finite_type
variables (R A)
lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp_surjective hf hg
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type :=
ring_hom.finite_type.of_surjective f hf
lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type :=
ring_hom.finite_type.of_finite_presentation hf
end finite_type
namespace finite_presentation
variables (R A)
lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation)
(hf : f.finite_presentation) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation)
(hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp_surjective hf hg hker
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) :
f.finite_presentation :=
ring_hom.finite_presentation.of_surjective f hf hker
lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} :
f.finite_type ↔ f.finite_presentation :=
ring_hom.finite_presentation.of_finite_type
end finite_presentation
end alg_hom
section monoid_algebra
variables {R : Type*} {M : Type*}
namespace add_monoid_algebra
open algebra add_submonoid submodule
section span
section semiring
variables [comm_semiring R] [add_monoid M]
/-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) :=
begin
suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of
elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : of' R M '' f.support ⊆
⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support,
{ intros s hs,
exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of
the supports of elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [add_comm_monoid M]
/-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its
image generates, as algera, `add_monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of'_mem_span [nontrivial R] {m : M} {S : set M} :
of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h,
simpa using h
end
/--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
the closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) :
m ∈ closure S :=
begin
suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S),
{ simpa [← to_submonoid_closure] },
rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x),
← monoid_hom.map_mclosure] at h,
simpa using of'_mem_span.1 h
end
end ring
end span
variables [add_comm_monoid M]
/-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra,
`add_monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]; refl⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
/-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite
type. -/
instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] :
finite_type R (add_monoid_algebra R M) :=
begin
obtain ⟨S, hS⟩ := h.out,
exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval
(λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS)
end
/-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of
finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M :=
begin
refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩,
obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h,
refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩,
have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule,
{ simp only [hS, top_to_submodule, submodule.mem_top], },
rw [adjoin_eq_span] at hm,
exact mem_closure_of_mem_span_closure hm
end
/-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] :
add_monoid.fg M :=
finite_type_iff_fg.1 h
/-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of
finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R G) ↔ add_group.fg G :=
by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg
end add_monoid_algebra
namespace monoid_algebra
open algebra submonoid submodule
section span
section semiring
variables [comm_semiring R] [monoid M]
/-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) :=
begin
suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements
of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : (of R M) '' f.support ⊆
⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support,
{ intros s hs,
exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoint_support f)
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the
supports of elements of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [comm_monoid M]
/-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image
generates, as algera, `monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} :
of R M m ∈ span R (of R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h,
simpa using h
end
/--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the
closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) :
m ∈ closure S :=
begin
rw ← monoid_hom.map_mclosure at h,
simpa using of_mem_span_of_iff.1 h
end
end ring
end span
variables [comm_monoid M]
/-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra,
`monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
/-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/
instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) :=
add_monoid_algebra.finite_type_of_fg.equiv (to_additive_alg_equiv R M).symm
/-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R M) ↔ monoid.fg M :=
⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $
to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩
/-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] :
monoid.fg M :=
finite_type_iff_fg.1 h
/-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R G) ↔ group.fg G :=
by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg
end monoid_algebra
end monoid_algebra
|
da334b08c33c77c34702308f7003e93b3c21c7be | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Elab/MutualDef.lean | a6e7e96d8c147bec779d23fec0b0cfa1dc6a53c6 | [
"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 | 32,868 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Parser.Term
import Lean.Meta.Closure
import Lean.Meta.Check
import Lean.Elab.Command
import Lean.Elab.DefView
import Lean.Elab.PreDefinition
import Lean.Elab.DeclarationRange
namespace Lean.Elab
open Lean.Parser.Term
/- DefView after elaborating the header. -/
structure DefViewElabHeader where
ref : Syntax
modifiers : Modifiers
kind : DefKind
shortDeclName : Name
declName : Name
levelNames : List Name
numParams : Nat
type : Expr -- including the parameters
valueStx : Syntax
deriving Inhabited
namespace Term
open Meta
private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do
unless m₁.isUnsafe == m₂.isUnsafe do
throwError "cannot mix unsafe and safe definitions"
unless m₁.isNoncomputable == m₂.isNoncomputable do
throwError "cannot mix computable and non-computable definitions"
unless m₁.isPartial == m₂.isPartial do
throwError "cannot mix partial and non-partial definitions"
private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do
unless k₁.isExample == k₂.isExample do
throwError "cannot mix examples and definitions" -- Reason: we should discard examples
unless k₁.isTheorem == k₂.isTheorem do
throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s.
private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do
if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then
throwError "'unsafe' theorems are not allowed"
if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then
throwError "'partial' theorems are not allowed, 'partial' is a code generation directive"
if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then
throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems"
if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then
throwError "'noncomputable unsafe' is not allowed"
if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then
throwError "'noncomputable partial' is not allowed"
if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then
throwError "'unsafe' subsumes 'partial'"
if h : 0 < prevHeaders.size then
let firstHeader := prevHeaders.get ⟨0, h⟩
try
unless newHeader.levelNames == firstHeader.levelNames do
throwError "universe parameters mismatch"
checkModifiers newHeader.modifiers firstHeader.modifiers
checkKinds newHeader.kind firstHeader.kind
catch
| Exception.error ref msg => throw (Exception.error ref m!"invalid mutually recursive definitions, {msg}")
| ex => throw ex
else
pure ()
private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=
registerCustomErrorIfMVar type ref "failed to infer definition type"
/--
Return `some [b, c]` if the given `views` are representing a declaration of the form
```
constant a b c : Nat
``` -/
private def isMultiConstant? (views : Array DefView) : Option (List Name) :=
if views.size == 1 &&
views[0].kind == DefKind.opaque &&
views[0].binders.getArgs.size > 0 &&
views[0].binders.getArgs.all (·.getKind == ``Parser.Term.simpleBinder) then
some <| (views[0].binders.getArgs.toList.map (fun stx => stx[0].getArgs.toList.map (·.getId))).join
else
none
private def getPendindMVarErrorMessage (views : Array DefView) : String :=
match isMultiConstant? views with
| some ids =>
let idsStr := ", ".intercalate <| ids.map fun id => s!"`{id}`"
let paramsStr := ", ".intercalate <| ids.map fun id => s!"`({id} : _)`"
s!"\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}"
| none =>
"\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed"
private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do
let mut headers := #[]
for view in views do
let newHeader ← withRef view.ref do
let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers
addDeclarationRanges declName view.ref
applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration
withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <|
elabBinders view.binders.getArgs fun xs => do
let refForElabFunType := view.value
let type ← match view.type? with
| some typeStx =>
let type ← elabType typeStx
registerFailedToInferDefTypeInfo type typeStx
pure type
| none =>
let hole := mkHole refForElabFunType
let type ← elabType hole
registerFailedToInferDefTypeInfo type refForElabFunType
pure type
Term.synthesizeSyntheticMVarsNoPostponing
let type ← mkForallFVars xs type
let type ← mkForallFVars (← read).autoBoundImplicits.toArray type
let type ← instantiateMVars type
let xs ← addAutoBoundImplicits xs
let levelNames ← getLevelNames
if view.type?.isSome then
let pendingMVarIds ← getMVars type
discard <| logUnassignedUsingErrorInfos pendingMVarIds <|
getPendindMVarErrorMessage views
let newHeader := {
ref := view.ref,
modifiers := view.modifiers,
kind := view.kind,
shortDeclName := shortDeclName,
declName := declName,
levelNames := levelNames,
numParams := xs.size,
type := type,
valueStx := view.value : DefViewElabHeader }
check headers newHeader
pure newHeader
headers := headers.push newHeader
pure headers
private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) := do
if h : i < headers.size then
let header := headers.get ⟨i, h⟩
if header.modifiers.isNonrec then
loop (i+1) fvars
else
withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar)
else
k fvars
loop 0 #[]
private def expandWhereDeclsAsStructInst : Macro
| `(whereDecls|where $[$decls:letRecDecl$[;]?]*) => do
let letIdDecls ← decls.mapM fun stx => match stx with
| `(letRecDecl|$attrs:attributes $decl:letDecl) => Macro.throwErrorAt stx "attributes are 'where' elements are currently not supported here"
| `(letRecDecl|$decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here"
| `(letRecDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl
| `(letRecDecl|$decl:letIdDecl) => pure decl
| _ => Macro.throwUnsupported
let structInstFields ← letIdDecls.mapM fun
| stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do
let mut val := val
if let some ty := ty? then
val ← `(($val : $ty))
val ← if binders.size > 0 then `(fun $[$binders]* => $val:term) else val
`(structInstField|$id:ident := $val)
| _ => Macro.throwUnsupported
`({ $[$structInstFields,]* })
| _ => Macro.throwUnsupported
/-
Recall that
```
def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls
def declValEqns := leading_parser Term.matchAltsWhereDecls
def declVal := declValSimple <|> declValEqns <|> Term.whereDecls
```
-/
private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do
if declVal.isOfKind `Lean.Parser.Command.declValSimple then
expandWhereDeclsOpt declVal[2] declVal[1]
else if declVal.isOfKind `Lean.Parser.Command.declValEqns then
expandMatchAltsWhereDecls declVal[0]
else if declVal.isOfKind `Lean.Parser.Term.whereDecls then
expandWhereDeclsAsStructInst declVal
else if declVal.isMissing then
Macro.throwErrorAt declVal "declaration body is missing"
else
Macro.throwErrorAt declVal "unexpected declaration body"
private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) :=
headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do
let valStx ← liftMacroM $ declValToTerm header.valueStx
forallBoundedTelescope header.type header.numParams fun xs type => do
let val ← elabTermEnsuringType valStx type
mkLambdaFVars xs val
private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)
: StateRefT CollectFVars.State MetaM Unit := do
headers.forM fun header => collectUsedFVars header.type
values.forM collectUsedFVars
toLift.forM fun letRecToLift => do
collectUsedFVars letRecToLift.type
collectUsedFVars letRecToLift.val
private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)
: TermElabM (LocalContext × LocalInstances × Array Expr) := do
let (_, used) ← (collectUsed headers values toLift).run {}
removeUnused vars used
private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)
(k : Array Expr → TermElabM α) : TermElabM α := do
let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift
withLCtx lctx localInsts $ k vars
private def isExample (views : Array DefView) : Bool :=
views.any (·.kind.isExample)
private def isTheorem (views : Array DefView) : Bool :=
views.any (·.kind.isTheorem)
private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do
let type ← instantiateMVars header.type
pure { header with type := type }
private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do
let type ← instantiateMVars toLift.type
let val ← instantiateMVars toLift.val
pure { toLift with type := type, val := val }
private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId :=
let occ? := type.find? fun e => match e with
| Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId
| _ => false
match occ? with
| some (Expr.fvar fvarId _) => some fvarId
| _ => none
private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do
match (← findLocalDecl? fvarId) with
| some decl => pure decl.userName
| none =>
/- Recall that the FVarId of nested let-recs are not in the current local context. -/
match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with
| none => throwError "unknown function"
| some n => pure n
/-
Ensures that the of let-rec definition types do not contain functions being defined.
In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components.
However, this extra complication doesn't seem worth it.
-/
private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit :=
letRecsToLift.forM fun toLift =>
match typeHasRecFun toLift.type funVars letRecsToLift with
| none => pure ()
| some fvarId => do
let fnName ← getFunName fvarId letRecsToLift
throwErrorAt toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously"
namespace MutualClosure
/- A mapping from FVarId to Set of FVarIds. -/
abbrev UsedFVarsMap := FVarIdMap FVarIdSet
/-
Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of
free variables in its definition.
For `mainFVars`, this is just the set of section variables `sectionVars` used.
For nested let-rec functions, we collect their free variables.
Recall that a `let rec` expressions are encoded as follows in the elaborator.
```lean
let rec
f : A := t,
g : B := s;
body
```
is encoded as
```lean
let f : A := ?m₁;
let g : B := ?m₂;
body
```
where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module.
We may have nested `let rec`s.
```lean
let rec f : A :=
let rec g : B := t;
s;
body
```
is encoded as
```lean
let f : A := ?m₁;
body
```
and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above,
we would have a `LetRecToLift` containing:
```
{
mvarId := m₁,
val := `(let g : B := ?m₂; body)
...
}
```
Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that
`f` depends on `g` because it contains `m₂`
-/
private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift)
: UsedFVarsMap := do
let mut sectionVarSet := {}
for var in sectionVars do
sectionVarSet := sectionVarSet.insert var.fvarId!
let mut usedFVarMap := {}
for mainFVarId in mainFVarIds do
usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet
for toLift in letRecsToLift do
let state := Lean.collectFVars {} toLift.val
let state := Lean.collectFVars state toLift.type
let mut set := state.fvarSet
/- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId
for the associated let-rec because we need this information to compute the fixpoint later. -/
let mvarIds := (toLift.val.collectMVars {}).result
for mvarId in mvarIds do
match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with
| some fvarId => set := set.insert fvarId
| none => pure ()
usedFVarMap := usedFVarMap.insert toLift.fvarId set
pure usedFVarMap
/-
The let-recs may invoke each other. Example:
```
let rec
f (x : Nat) := g x + y
g : Nat → Nat
| 0 => 1
| x+1 => f x + z
```
`y` is free variable in `f`, and `z` is a free variable in `g`.
To close `f` and `g`, `y` and `z` must be in the closure of both.
That is, we need to generate the top-level definitions.
```
def f (y z x : Nat) := g y z x + y
def g (y z : Nat) : Nat → Nat
| 0 => 1
| x+1 => f y z x + z
```
-/
namespace FixPoint
structure State where
usedFVarsMap : UsedFVarsMap := {}
modified : Bool := false
abbrev M := ReaderT (List FVarId) $ StateM State
private def isModified : M Bool := do pure (← get).modified
private def resetModified : M Unit := modify fun s => { s with modified := false }
private def markModified : M Unit := modify fun s => { s with modified := true }
private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap
private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap }
-- merge s₂ into s₁
private def merge (s₁ s₂ : FVarIdSet) : M FVarIdSet :=
s₂.foldM (init := s₁) fun s₁ k => do
if s₁.contains k then
pure s₁
else
markModified
pure $ s₁.insert k
private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do
let usedFVarsMap ← getUsedFVarsMap
match usedFVarsMap.find? fvarId with
| none => pure ()
| some fvarIds =>
let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' =>
if fvarId == fvarId' then
pure fvarIdsNew
else
match usedFVarsMap.find? fvarId' with
| none => pure fvarIdsNew
/- We are being sloppy here `otherFVarIds` may contain free variables that are
not in the context of the let-rec associated with fvarId.
We filter these out-of-context free variables later. -/
| some otherFVarIds => merge fvarIdsNew otherFVarIds
modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew
private partial def fixpoint : Unit → M Unit
| _ => do
resetModified
let letRecFVarIds ← read
letRecFVarIds.forM updateUsedVarsOf
if (← isModified) then
fixpoint ()
def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap :=
let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap }
s.usedFVarsMap
end FixPoint
abbrev FreeVarMap := FVarIdMap (Array FVarId)
private def mkFreeVarMap
(mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId)
(recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do
let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift
let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId
let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap
let mut freeVarMap := {}
for toLift in letRecsToLift do
let lctx := toLift.lctx
let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get!
let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId =>
if lctx.contains fvarId && !recFVarIds.contains fvarId then
fvarIds.push fvarId
else
fvarIds
freeVarMap := freeVarMap.insert toLift.fvarId fvarIds
pure freeVarMap
structure ClosureState where
newLocalDecls : Array LocalDecl := #[]
localDecls : Array LocalDecl := #[]
newLetDecls : Array LocalDecl := #[]
exprArgs : Array Expr := #[]
private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId :=
fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index
private def preprocess (e : Expr) : TermElabM Expr := do
let e ← instantiateMVars e
-- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.
Meta.check e
pure e
/- Push free variables in `s` to `toProcess` if they are not already there. -/
private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId :=
s.fvarSet.fold (init := toProcess) fun toProcess fvarId =>
if toProcess.contains fvarId then toProcess else toProcess.push fvarId
private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default)
: StateRefT ClosureState TermElabM (Array FVarId) := do
let type ← preprocess type
modify fun s => { s with
newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi,
exprArgs := s.exprArgs.push (mkFVar fvarId)
}
pure $ pushNewVars toProcess (collectFVars {} type)
private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do
let lctx ← getLCtx
match pickMaxFVar? lctx toProcess with
| none => pure ()
| some fvarId =>
trace[Elab.definition.mkClosure] "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}"
let toProcess := toProcess.erase fvarId
let localDecl ← getLocalDecl fvarId
match localDecl with
| LocalDecl.cdecl _ _ userName type bi =>
let toProcess ← pushLocalDecl toProcess fvarId userName type bi
mkClosureForAux toProcess
| LocalDecl.ldecl _ _ userName type val _ =>
let zetaFVarIds ← getZetaFVarIds
if !zetaFVarIds.contains fvarId then
/- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/
let toProcess ← pushLocalDecl toProcess fvarId userName type
mkClosureForAux toProcess
else
/- Dependent let-decl. -/
let type ← preprocess type
let val ← preprocess val
modify fun s => { s with
newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false,
/- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId
at `newLocalDecls` and `localDecls` -/
newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val),
localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val)
}
mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val))
private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do
let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls }
pure { s with
newLocalDecls := s.newLocalDecls.reverse,
newLetDecls := s.newLetDecls.reverse,
exprArgs := s.exprArgs.reverse
}
structure LetRecClosure where
ref : Syntax
localDecls : Array LocalDecl
closed : Expr -- expression used to replace occurrences of the let-rec FVarId
toLift : LetRecToLift
private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do
let lctx := toLift.lctx
withLCtx lctx toLift.localInstances do
lambdaTelescope toLift.val fun xs val => do
let type ← instantiateForall toLift.type xs
let lctx ← getLCtx
let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId!
let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type
let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val
let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs
assignExprMVar toLift.mvarId c
return {
ref := toLift.ref
localDecls := s.newLocalDecls
closed := c
toLift := { toLift with val := val, type := type }
}
private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) :=
letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!
/- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/
abbrev Replacement := FVarIdMap Expr
def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement :=
mainFVars.size.fold (init := r) fun i r =>
r.insert mainFVars[i].fvarId! (mkAppN (Lean.mkConst mainHeaders[i].declName) sectionVars)
def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement :=
letRecClosures.foldl (init := r) fun r c =>
r.insert c.toLift.fvarId c.closed
def Replacement.apply (r : Replacement) (e : Expr) : Expr :=
e.replace fun e => match e with
| Expr.fvar fvarId _ => match r.find? fvarId with
| some c => some c
| _ => none
| _ => none
def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr)
: TermElabM (Array PreDefinition) :=
mainHeaders.size.foldM (init := preDefs) fun i preDefs => do
let header := mainHeaders[i]
let val ← mkLambdaFVars sectionVars mainVals[i]
let type ← mkForallFVars sectionVars header.type
return preDefs.push {
ref := getDeclarationSelectionRef header.ref
kind := header.kind
declName := header.declName
levelParams := [], -- we set it later
modifiers := header.modifiers
type := type
value := val
}
def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition :=
letRecClosures.foldl (init := preDefs) fun preDefs c =>
let type := Closure.mkForall c.localDecls c.toLift.type
let val := Closure.mkLambda c.localDecls c.toLift.val
preDefs.push {
ref := c.ref
kind := kind
declName := c.toLift.declName
levelParams := [] -- we set it later
modifiers := { modifiers with attrs := c.toLift.attrs }
type := type
value := val
}
def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind :=
if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem»
else DefKind.«def»
def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := {
isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable
recKind := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default
isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe
}
/-
- `sectionVars`: The section variables used in the `mutual` block.
- `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block.
- `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block.
- `mainVals`: The elaborated value for the top-level definitions
- `letRecsToLift`: The let-rec's definitions that need to be lifted
-/
def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift)
: TermElabM (Array PreDefinition) := do
-- Store in recFVarIds the fvarId of every function being defined by the mutual block.
let mainFVarIds := mainFVars.map Expr.fvarId!
let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds
-- Compute the set of free variables (excluding `recFVarIds`) for each let-rec.
let mctx ← getMCtx
let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift
resetZetaFVarIds
withTrackingZeta do
-- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`.
letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val
let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap
-- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations.
let mainVals ← mainVals.mapM (instantiateMVars ·)
let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader
let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) }
-- Replace fvarIds for functions being defined with closed terms
let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars
let r := insertReplacementForLetRecs r letRecClosures
let mainVals := mainVals.map r.apply
let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type }
let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } }
let letRecKind := getKindForLetRecs mainHeaders
let letRecMods := getModifiersForLetRecs mainHeaders
pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals
end MutualClosure
private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name :=
if h : 0 < headers.size then
-- Recall that all top-level functions must have the same levels. See `check` method above
(headers.get ⟨0, h⟩).levelNames
else
[]
/-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/
private def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do
let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do
let mut newHeaders := #[]
for view in views, header in headers do
if view.kind.isTheorem then
newHeaders := newHeaders.push { header with type := (← levelMVarToParam' header.type) }
else
newHeaders := newHeaders.push header
return newHeaders
let newHeaders ← process.run' 1
newHeaders.mapM fun header => return { header with type := (← instantiateMVars header.type) }
/-- Result for `mkInst?` -/
structure MkInstResult where
instVal : Expr
instType : Expr
outParams : Array Expr := #[]
/--
Construct an instance for `className out₁ ... outₙ type`.
The method support classes with a prefix of `outParam`s (e.g. `MonadReader`). -/
private partial def mkInst? (className : Name) (type : Expr) : MetaM (Option MkInstResult) := do
let rec go? (instType instTypeType : Expr) (outParams : Array Expr) : MetaM (Option MkInstResult) := do
let instTypeType ← whnfD instTypeType
unless instTypeType.isForall do
return none
let d := instTypeType.bindingDomain!
if isOutParam d then
let mvar ← mkFreshExprMVar d
go? (mkApp instType mvar) (instTypeType.bindingBody!.instantiate1 mvar) (outParams.push mvar)
else
unless (← isDefEqGuarded (← inferType type) d) do
return none
let instType ← instantiateMVars (mkApp instType type)
let instVal ← synthInstance instType
return some { instVal, instType, outParams }
let instType ← mkConstWithFreshMVarLevels className
go? instType (← inferType instType) #[]
def processDefDeriving (className : Name) (declName : Name) : TermElabM Bool := do
try
let ConstantInfo.defnInfo info ← getConstInfo declName | return false
let some result ← mkInst? className info.value | return false
let instTypeNew := mkApp result.instType.appFn! (Lean.mkConst declName (info.levelParams.map mkLevelParam))
Meta.check instTypeNew
let instName ← liftMacroM <| mkUnusedBaseName (declName.appendBefore "inst" |>.appendAfter className.getString!)
addAndCompile <| Declaration.defnDecl {
name := instName
levelParams := info.levelParams
type := (← instantiateMVars instTypeNew)
value := (← instantiateMVars result.instVal)
hints := info.hints
safety := info.safety
}
addInstance instName AttributeKind.global (eval_prio default)
return true
catch ex =>
return false
def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit :=
if isExample views then
withoutModifyingEnv go
else
go
where
go := do
let scopeLevelNames ← getLevelNames
let headers ← elabHeaders views
let headers ← levelMVarToParamHeaders views headers
let allUserLevelNames := getAllUserLevelNames headers
withFunLocalDecls headers fun funFVars => do
let values ← elabFunValues headers
Term.synthesizeSyntheticMVarsNoPostponing
let values ← values.mapM (instantiateMVars ·)
let headers ← headers.mapM instantiateMVarsAtHeader
let letRecsToLift ← getLetRecsToLift
let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift
checkLetRecsToLiftTypes funFVars letRecsToLift
withUsed vars headers values letRecsToLift fun vars => do
let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift
let preDefs ← levelMVarToParamPreDecls preDefs
let preDefs ← instantiateMVarsAtPreDecls preDefs
let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames
addPreDefinitions preDefs
processDeriving headers
processDeriving (headers : Array DefViewElabHeader) := do
for header in headers, view in views do
if let some classNamesStx := view.deriving? then
for classNameStx in classNamesStx do
let className ← resolveGlobalConstNoOverload classNameStx
withRef classNameStx do
unless (← processDefDeriving className header.declName) do
throwError "failed to synthesize instance '{className}' for '{header.declName}'"
end Term
namespace Command
def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do
let views ← ds.mapM fun d => do
let modifiers ← elabModifiers d[0]
if ds.size > 1 && modifiers.isNonrec then
throwErrorAt d "invalid use of 'nonrec' modifier in 'mutual' block"
mkDefView modifiers d[1]
runTermElabM none fun vars => Term.elabMutualDef vars views
end Command
end Lean.Elab
|
80cf226d9b760b7eef430f9434c697ab682176a1 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/multiset/bind.lean | 031bc820e400e0e3295c7a8f864f94e68c148bb3 | [
"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 | 9,593 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.big_operators.multiset.basic
/-!
# Bind operation for multisets
This file defines a few basic operations on `multiset`, notably the monadic bind.
## Main declarations
* `multiset.join`: The join, aka union or sum, of multisets.
* `multiset.bind`: The bind of a multiset-indexed family of multisets.
* `multiset.product`: Cartesian product of two multisets.
* `multiset.sigma`: Disjoint sum of multisets in a sigma type.
-/
variables {α β γ δ : Type*}
namespace multiset
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
lemma coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] lemma join_zero : @join α 0 = 0 := rfl
@[simp] lemma join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _
@[simp] lemma join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _
@[simp] lemma singleton_join (a) : join ({a} : multiset (multiset α)) = a := sum_singleton _
@[simp] lemma mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] lemma card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
lemma rel_join {r : α → β → Prop} {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
/-! ### Bind -/
section bind
variables (a : α) (s t : multiset α) (f g : α → multiset β)
/-- `s.bind f` is the monad bind operation, defined as `(s.map f).join`. It is the union of `f a` as
`a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β := (s.map f).join
@[simp] lemma coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ←coe_join, list.map_map]; refl
@[simp] lemma zero_bind : bind 0 f = 0 := rfl
@[simp] lemma cons_bind : (a ::ₘ s).bind f = f a + s.bind f := by simp [bind]
@[simp] lemma singleton_bind : bind {a} f = f a := by simp [bind]
@[simp] lemma add_bind : (s + t).bind f = s.bind f + t.bind f := by simp [bind]
@[simp] lemma bind_zero : s.bind (λ a, 0 : α → multiset β) = 0 := by simp [bind, join, nsmul_zero]
@[simp] lemma bind_add : s.bind (λ a, f a + g a) = s.bind f + s.bind g := by simp [bind, join]
@[simp] lemma bind_cons (f : α → β) (g : α → multiset β) :
s.bind (λ a, f a ::ₘ g a) = map f s + s.bind g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] lemma bind_singleton (f : α → β) : s.bind (λ x, ({f x} : multiset β)) = map f s :=
multiset.induction_on s (by rw [zero_bind, map_zero]) (by simp [singleton_add])
@[simp] lemma mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] lemma card_bind : (s.bind f).card = (s.map (card ∘ f)).sum := by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} :
(∀ a ∈ m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a ∈ m, f a == f' a) :
bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λ a, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λ a, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λ a, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λ a, bind n $ λ b, f a b) = (bind n $ λ b, bind m $ λ a, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λ a, n.map $ λ b, f a b) = (bind n $ λ b, m.map $ λ a, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
(s.bind t).prod = (s.map $ λ a, (t a).prod).prod :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
lemma rel_bind {r : α → β → Prop} {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by { apply rel_join, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) }
lemma count_sum [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λ b, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λ b, count a $ f b) := count_sum
lemma le_bind {α β : Type*} {f : α → multiset β} (S : multiset α) {x : α} (hx : x ∈ S) :
f x ≤ S.bind f :=
begin
classical,
rw le_iff_count, intro a,
rw count_bind, apply le_sum_of_mem,
rw mem_map, exact ⟨x, hx, rfl⟩
end
@[simp] theorem attach_bind_coe (s : multiset α) (f : α → multiset β) :
s.attach.bind (λ i, f i) = s.bind f :=
congr_arg join $ attach_map_coe' _ _
end bind
/-! ### Product of two multisets -/
section product
variables (a : α) (b : β) (s : multiset α) (t : multiset β)
/-- The multiplicity of `(a, b)` in `s ×ˢ t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a
/- This notation binds more strongly than (pre)images, unions and intersections. -/
infixr (name := multiset.product) ` ×ˢ `:82 := multiset.product
@[simp] lemma coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ :=
by { rw [product, list.product, ←coe_bind], simp }
@[simp] lemma zero_product : @product α β 0 t = 0 := rfl
@[simp] lemma cons_product : (a ::ₘ s) ×ˢ t = map (prod.mk a) t + s ×ˢ t := by simp [product]
@[simp] lemma product_zero : s ×ˢ (0 : multiset β) = 0 := by simp [product]
@[simp] lemma product_cons : s ×ˢ (b ::ₘ t) = s.map (λ a, (a, b)) + s ×ˢ t := by simp [product]
@[simp] lemma product_singleton : ({a} : multiset α) ×ˢ ({b} : multiset β) = {(a, b)} :=
by simp only [product, bind_singleton, map_singleton]
@[simp] lemma add_product (s t : multiset α) (u : multiset β) : (s + t) ×ˢ u = s ×ˢ u + t ×ˢ u :=
by simp [product]
@[simp] lemma product_add (s : multiset α) : ∀ t u : multiset β, s ×ˢ (t + u) = s ×ˢ t + s ×ˢ u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] lemma mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] lemma card_product : (s ×ˢ t).card = s.card * t.card :=
by simp [product, repeat, (∘), mul_comm]
end product
/-! ### Disjoint sum of multisets -/
section sigma
variables {σ : α → Type*} (a : α) (s : multiset α) (t : Π a, multiset (σ a))
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] lemma coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ←coe_bind]; simp
@[simp] lemma zero_sigma : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] lemma cons_sigma : (a ::ₘ s).sigma t = (t a).map (sigma.mk a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] lemma sigma_singleton (b : α → β) :
({a} : multiset α).sigma (λ a, ({b a} : multiset β)) = {⟨a, b a⟩} := rfl
@[simp] lemma add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] lemma sigma_add : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] lemma mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] lemma card_sigma :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end sigma
end multiset
|
e1bfd2e63e19358a04ff61d3f8e1a76683b46cc1 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/bases.lean | 11a0a4ccd903d0655c12a8c280daaf540e1510b8 | [
"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 | 31,556 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.continuous_on
import topology.constructions
/-!
# Bases of topologies. Countability axioms.
A topological basis on a topological space `t` is a collection of sets,
such that all open sets can be generated as unions of these sets, without the need to take
finite intersections of them. This file introduces a framework for dealing with these collections,
and also what more we can say under certain countability conditions on bases,
which are referred to as first- and second-countable.
We also briefly cover the theory of separable spaces, which are those with a countable, dense
subset. If a space is second-countable, and also has a countably generated uniformity filter
(for example, if `t` is a metric space), it will automatically be separable (and indeed, these
conditions are equivalent in this case).
## Main definitions
* `is_topological_basis s`: The topological space `t` has basis `s`.
* `separable_space α`: The topological space `t` has a countable, dense subset.
* `first_countable_topology α`: A topology in which `𝓝 x` is countably generated for every `x`.
* `second_countable_topology α`: A topology which has a topological basis which is countable.
## Main results
* `first_countable_topology.tendsto_subseq`: In a first-countable space,
cluster points are limits of subsequences.
* `second_countable_topology.is_open_Union_countable`: In a second-countable space, the union of
arbitrarily-many open sets is equal to a sub-union of only countably many of these sets.
* `second_countable_topology.countable_cover_nhds`: Consider `f : α → set α` with the property that
`f x ∈ 𝓝 x` for all `x`. Then there is some countable set `s` whose image covers the space.
## Implementation Notes
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
### TODO:
More fine grained instances for `first_countable_topology`, `separable_space`, `t2_space`, and more
(see the comment below `subtype.second_countable_topology`.)
-/
open set filter classical
open_locale topological_space filter
noncomputable theory
namespace topological_space
universe u
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
structure is_topological_basis (s : set (set α)) : Prop :=
(exists_subset_inter : ∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂)
(sUnion_eq : (⋃₀ s) = univ)
(eq_generate_from : t = generate_from s)
/-- If a family of sets `s` generates the topology, then nonempty intersections of finite
subcollections of `s` form a topological basis. -/
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λ f, ⋂₀ f) '' {f : set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) :=
begin
refine ⟨_, _, _⟩,
{ rintro _ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, rfl⟩ _ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, rfl⟩ x h,
have : ⋂₀ (t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂ := sInter_union t₁ t₂,
exact ⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, this.symm ▸ ⟨x, h⟩⟩, this⟩, h,
subset.rfl⟩ },
{ rw [sUnion_image, bUnion_eq_univ_iff],
intro x, have : x ∈ ⋂₀ ∅, { rw sInter_empty, exact mem_univ x },
exact ⟨∅, ⟨finite_empty, empty_subset _, x, this⟩, this⟩ },
{ rw hs,
apply le_antisymm; apply le_generate_from,
{ rintro _ ⟨t, ⟨hft, htb, ht⟩, rfl⟩,
exact @is_open_sInter _ (generate_from s) _ hft (λ s hs, generate_open.basic _ $ htb hs) },
{ intros t ht,
rcases t.eq_empty_or_nonempty with rfl|hne, { apply @is_open_empty _ _ },
rw ← sInter_singleton t at hne ⊢,
exact generate_open.basic _ ⟨{t}, ⟨finite_singleton t, singleton_subset_iff.2 ht, hne⟩,
rfl⟩ } }
end
/-- If a family of open sets `s` is such that every open neighbourhood contains some
member of `s`, then `s` is a topological basis. -/
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
begin
refine ⟨λ t₁ ht₁ t₂ ht₂ x hx, h_nhds _ _ hx (is_open.inter (h_open _ ht₁) (h_open _ ht₂)), _, _⟩,
{ refine sUnion_eq_univ_iff.2 (λ a, _),
rcases h_nhds a univ trivial is_open_univ with ⟨u, h₁, h₂, -⟩,
exact ⟨u, h₁, h₂⟩ },
{ refine (le_generate_from h_open).antisymm (λ u hu, _),
refine (@is_open_iff_nhds α (generate_from s) u).mpr (λ a ha, _),
rcases h_nhds a u ha hu with ⟨v, hvs, hav, hvu⟩,
rw nhds_generate_from,
exact binfi_le_of_le v ⟨hav, hvs⟩ (le_principal_iff.2 hvu) }
end
/-- A set `s` is in the neighbourhood of `a` iff there is some basis set `t`, which
contains `a` and is itself contained in `s`. -/
lemma is_topological_basis.mem_nhds_iff {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s,
rw [hb.eq_generate_from, nhds_generate_from, binfi_sets_eq],
{ simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)),
le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ },
{ rcases eq_univ_iff_forall.1 hb.sUnion_eq a with ⟨i, h1, h2⟩,
exact ⟨i, h2, h1⟩ }
end
lemma is_topological_basis.nhds_has_basis {b : set (set α)} (hb : is_topological_basis b) {a : α} :
(𝓝 a).has_basis (λ t : set α, t ∈ b ∧ a ∈ t) (λ t, t) :=
⟨λ s, hb.mem_nhds_iff.trans $ by simp only [exists_prop, and_assoc]⟩
protected lemma is_topological_basis.is_open {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : is_open s :=
by { rw hb.eq_generate_from, exact generate_open.basic s hs }
lemma is_topological_basis.exists_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
hb.mem_nhds_iff.1 $ is_open.mem_nhds ou au
/-- Any open set is the union of the basis sets contained in it. -/
lemma is_topological_basis.open_eq_sUnion' {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : is_open u) :
u = ⋃₀ {s ∈ B | s ⊆ u} :=
ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := hB.exists_subset_of_mem_open ha ou in ⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩
lemma is_topological_basis.open_eq_sUnion {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, hB.open_eq_sUnion' ou⟩
lemma is_topological_basis.open_eq_Union {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
⟨↥{s ∈ B | s ⊆ u}, coe, by { rw ← sUnion_eq_Union, apply hB.open_eq_sUnion' ou }, λ s, and.left s.2⟩
/-- A point `a` is in the closure of `s` iff all basis sets containing `a` intersect `s`. -/
lemma is_topological_basis.mem_closure_iff {b : set (set α)} (hb : is_topological_basis b)
{s : set α} {a : α} :
a ∈ closure s ↔ ∀ o ∈ b, a ∈ o → (o ∩ s).nonempty :=
(mem_closure_iff_nhds_basis' hb.nhds_has_basis).trans $ by simp only [and_imp]
/-- A set is dense iff it has non-trivial intersection with all basis sets. -/
lemma is_topological_basis.dense_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} :
dense s ↔ ∀ o ∈ b, set.nonempty o → (o ∩ s).nonempty :=
begin
simp only [dense, hb.mem_closure_iff],
exact ⟨λ h o hb ⟨a, ha⟩, h a o hb ha, λ h a o hb ha, h o hb ⟨a, ha⟩⟩
end
lemma is_topological_basis.is_open_map_iff {β} [topological_space β] {B : set (set α)}
(hB : is_topological_basis B) {f : α → β} :
is_open_map f ↔ ∀ s ∈ B, is_open (f '' s) :=
begin
refine ⟨λ H o ho, H _ (hB.is_open ho), λ hf o ho, _⟩,
rw [hB.open_eq_sUnion' ho, sUnion_eq_Union, image_Union],
exact is_open_Union (λ s, hf s s.2.1)
end
lemma is_topological_basis.exists_nonempty_subset {B : set (set α)}
(hb : is_topological_basis B) {u : set α} (hu : u.nonempty) (ou : is_open u) :
∃ v ∈ B, set.nonempty v ∧ v ⊆ u :=
begin
cases hu with x hx,
rw [hb.open_eq_sUnion' ou, mem_sUnion] at hx,
rcases hx with ⟨v, hv, hxv⟩,
exact ⟨v, hv.1, ⟨x, hxv⟩, hv.2⟩
end
lemma is_topological_basis_opens : is_topological_basis { U : set α | is_open U } :=
is_topological_basis_of_open_of_nhds (by tauto) (by tauto)
protected lemma is_topological_basis.prod {β} [topological_space β] {B₁ : set (set α)}
{B₂ : set (set β)} (h₁ : is_topological_basis B₁) (h₂ : is_topological_basis B₂) :
is_topological_basis (image2 set.prod B₁ B₂) :=
begin
refine is_topological_basis_of_open_of_nhds _ _,
{ rintro _ ⟨u₁, u₂, hu₁, hu₂, rfl⟩,
exact (h₁.is_open hu₁).prod (h₂.is_open hu₂) },
{ rintro ⟨a, b⟩ u hu uo,
rcases (h₁.nhds_has_basis.prod_nhds h₂.nhds_has_basis).mem_iff.1 (is_open.mem_nhds uo hu)
with ⟨⟨s, t⟩, ⟨⟨hs, ha⟩, ht, hb⟩, hu⟩,
exact ⟨s.prod t, mem_image2_of_mem hs ht, ⟨ha, hb⟩, hu⟩ }
end
protected lemma is_topological_basis.inducing {β} [topological_space β]
{f : α → β} {T : set (set β)} (hf : inducing f) (h : is_topological_basis T) :
is_topological_basis (image (preimage f) T) :=
begin
refine is_topological_basis_of_open_of_nhds _ _,
{ rintros _ ⟨V, hV, rfl⟩,
rwa hf.is_open_iff,
refine ⟨V, h.is_open hV, rfl⟩ },
{ intros a U ha hU,
rw hf.is_open_iff at hU,
obtain ⟨V, hV, rfl⟩ := hU,
obtain ⟨S, hS, rfl⟩ := h.open_eq_sUnion hV,
obtain ⟨W, hW, ha⟩ := ha,
refine ⟨f ⁻¹' W, ⟨_, hS hW, rfl⟩, ha, set.preimage_mono $ set.subset_sUnion_of_mem hW⟩ }
end
lemma is_topological_basis_of_cover {ι} {U : ι → set α} (Uo : ∀ i, is_open (U i))
(Uc : (⋃ i, U i) = univ) {b : Π i, set (set (U i))} (hb : ∀ i, is_topological_basis (b i)) :
is_topological_basis (⋃ i : ι, image (coe : U i → α) '' (b i)) :=
begin
refine is_topological_basis_of_open_of_nhds (λ u hu, _) _,
{ simp only [mem_Union, mem_image] at hu,
rcases hu with ⟨i, s, sb, rfl⟩,
exact (Uo i).is_open_map_subtype_coe _ ((hb i).is_open sb) },
{ intros a u ha uo,
rcases Union_eq_univ_iff.1 Uc a with ⟨i, hi⟩,
lift a to ↥(U i) using hi,
rcases (hb i).exists_subset_of_mem_open (by exact ha) (uo.preimage continuous_subtype_coe)
with ⟨v, hvb, hav, hvu⟩,
exact ⟨coe '' v, mem_Union.2 ⟨i, mem_image_of_mem _ hvb⟩, mem_image_of_mem _ hav,
image_subset_iff.2 hvu⟩ }
end
protected lemma is_topological_basis.continuous {β : Type*} [topological_space β]
{B : set (set β)} (hB : is_topological_basis B) (f : α → β) (hf : ∀ s ∈ B, is_open (f ⁻¹' s)) :
continuous f :=
begin rw hB.eq_generate_from, exact continuous_generated_from hf end
variables (α)
/-- A separable space is one with a countable dense subset, available through
`topological_space.exists_countable_dense`. If `α` is also known to be nonempty, then
`topological_space.dense_seq` provides a sequence `ℕ → α` with dense range, see
`topological_space.dense_range_dense_seq`.
If `α` is a uniform space with countably generated uniformity filter (e.g., an `emetric_space`),
then this condition is equivalent to `topological_space.second_countable_topology α`. In this case
the latter should be used as a typeclass argument in theorems because Lean can automatically deduce
`separable_space` from `second_countable_topology` but it can't deduce `second_countable_topology`
and `emetric_space`. -/
class separable_space : Prop :=
(exists_countable_dense : ∃s:set α, countable s ∧ dense s)
lemma exists_countable_dense [separable_space α] :
∃ s : set α, countable s ∧ dense s :=
separable_space.exists_countable_dense
/-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the
conclusion of this lemma, you might want to use `topological_space.dense_seq` and
`topological_space.dense_range_dense_seq`.
If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/
lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, dense_range u :=
begin
obtain ⟨s : set α, hs, s_dense⟩ := exists_countable_dense α,
cases countable_iff_exists_surjective.mp hs with u hu,
exact ⟨u, s_dense.mono hu⟩,
end
/-- A dense sequence in a non-empty separable topological space.
If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/
def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α)
/-- The sequence `dense_seq α` has dense range. -/
@[simp] lemma dense_range_dense_seq [separable_space α] [nonempty α] :
dense_range (dense_seq α) := classical.some_spec (exists_dense_seq α)
variable {α}
/-- In a separable space, a family of nonempty disjoint open sets is countable. -/
lemma _root_.set.pairwise_disjoint.countable_of_is_open [separable_space α] {ι : Type*}
{s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s) (ha : ∀ i ∈ a, is_open (s i))
(h'a : ∀ i ∈ a, (s i).nonempty) :
countable a :=
begin
rcases eq_empty_or_nonempty a with rfl|H, { exact countable_empty },
haveI : inhabited α,
{ choose i ia using H,
choose y hy using h'a i ia,
exact ⟨y⟩ },
rcases exists_countable_dense α with ⟨u, u_count, u_dense⟩,
have : ∀ i, i ∈ a → ∃ y, y ∈ s i ∩ u :=
λ i hi, dense_iff_inter_open.1 u_dense (s i) (ha i hi) (h'a i hi),
choose! f hf using this,
have f_inj : inj_on f a,
{ assume i hi j hj hij,
have : ¬disjoint (s i) (s j),
{ rw not_disjoint_iff_nonempty_inter,
refine ⟨f i, (hf i hi).1, _⟩,
rw hij,
exact (hf j hj).1 },
contrapose! this,
exact h i hi j hj this },
apply countable_of_injective_of_countable_image f_inj,
apply u_count.mono _,
exact image_subset_iff.2 (λ i hi, (hf i hi).2)
end
/-- In a separable space, a family of disjoint sets with nonempty interiors is countable. -/
lemma _root_.set.pairwise_disjoint.countable_of_nonempty_interior [separable_space α] {ι : Type*}
{s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s)
(ha : ∀ i ∈ a, (interior (s i)).nonempty) :
countable a :=
(h.mono $ λ i, interior_subset).countable_of_is_open (λ i hi, is_open_interior) ha
end topological_space
open topological_space
lemma is_topological_basis_pi {ι : Type*} {X : ι → Type*}
[∀ i, topological_space (X i)] {T : Π i, set (set (X i))}
(cond : ∀ i, is_topological_basis (T i)) :
is_topological_basis {S : set (Π i, X i) | ∃ (U : Π i, set (X i)) (F : finset ι),
(∀ i, i ∈ F → (U i) ∈ T i) ∧ S = (F : set ι).pi U } :=
begin
classical,
refine is_topological_basis_of_open_of_nhds _ _,
{ rintro _ ⟨U, F, h1, rfl⟩,
apply is_open_set_pi F.finite_to_set,
intros i hi,
exact is_topological_basis.is_open (cond i) (h1 i hi) },
{ intros a U ha hU,
have : U ∈ nhds a := is_open.mem_nhds hU ha,
rw [nhds_pi, filter.mem_infi] at this,
obtain ⟨F, hF, V, hV1, rfl⟩ := this,
choose U' hU' using hV1,
obtain ⟨hU1, hU2⟩ := ⟨λ i, (hU' i).1, λ i, (hU' i).2⟩,
have : ∀ j : F, ∃ (T' : set (X j)) (hT : T' ∈ T j), a j ∈ T' ∧ T' ⊆ U' j,
{ intros i,
specialize hU1 i,
rwa (cond i).mem_nhds_iff at hU1 },
choose U'' hU'' using this,
let U : Π (i : ι), set (X i) := λ i,
if hi : i ∈ F then U'' ⟨i, hi⟩ else set.univ,
refine ⟨F.pi U, ⟨U, hF.to_finset, λ i hi, _, by simp⟩, _, _⟩,
{ dsimp only [U],
rw [dif_pos],
swap, { simpa using hi },
exact (hU'' _).1 },
{ rw set.mem_pi,
intros i hi,
dsimp only [U],
rw dif_pos hi,
exact (hU'' _).2.1 },
{ intros x hx,
rintros - ⟨i, rfl⟩,
refine hU2 i ((hU'' i).2.2 _),
convert hx i i.2,
rcases i with ⟨i, p⟩,
dsimp [U],
rw dif_pos p, } },
end
lemma is_topological_basis_infi {β : Type*} {ι : Type*} {X : ι → Type*}
[t : ∀ i, topological_space (X i)] {T : Π i, set (set (X i))}
(cond : ∀ i, is_topological_basis (T i)) (f : Π i, β → X i) :
@is_topological_basis β (⨅ i, induced (f i) (t i))
{ S | ∃ (U : Π i, set (X i)) (F : finset ι),
(∀ i, i ∈ F → U i ∈ T i) ∧ S = ⋂ i (hi : i ∈ F), (f i) ⁻¹' (U i) } :=
begin
convert (is_topological_basis_pi cond).inducing (inducing_infi_to_pi _),
ext V,
split,
{ rintros ⟨U, F, h1, h2⟩,
have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F),
(λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp },
refine ⟨(F : set ι).pi U, ⟨U, F, h1, rfl⟩, _⟩,
rw [this, h2, set.preimage_Inter],
congr' 1,
ext1,
rw set.preimage_Inter,
refl },
{ rintros ⟨U, ⟨U, F, h1, rfl⟩, h⟩,
refine ⟨U, F, h1, _⟩,
have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F),
(λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp },
rw [← h, this, set.preimage_Inter],
congr' 1,
ext1,
rw set.preimage_Inter,
refl }
end
/-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is
a separable space as well. E.g., the completion of a separable uniform space is separable. -/
protected lemma dense_range.separable_space {α β : Type*} [topological_space α] [separable_space α]
[topological_space β] {f : α → β} (h : dense_range f) (h' : continuous f) :
separable_space β :=
let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α in
⟨⟨f '' s, countable.image s_cnt f, h.dense_image h' s_dense⟩⟩
lemma dense.exists_countable_dense_subset {α : Type*} [topological_space α]
{s : set α} [separable_space s] (hs : dense s) :
∃ t ⊆ s, countable t ∧ dense t :=
let ⟨t, htc, htd⟩ := exists_countable_dense s
in ⟨coe '' t, image_subset_iff.2 $ λ x _, mem_preimage.2 $ subtype.coe_prop _, htc.image coe,
hs.dense_range_coe.dense_image continuous_subtype_val htd⟩
/-- Let `s` be a dense set in a topological space `α` with partial order structure. If `s` is a
separable space (e.g., if `α` has a second countable topology), then there exists a countable
dense subset `t ⊆ s` such that `t` contains bottom/top element of `α` when they exist and belong
to `s`. -/
lemma dense.exists_countable_dense_subset_bot_top {α : Type*} [topological_space α]
[partial_order α] {s : set α} [separable_space s] (hs : dense s) :
∃ t ⊆ s, countable t ∧ dense t ∧ (∀ x, is_bot x → x ∈ s → x ∈ t) ∧
(∀ x, is_top x → x ∈ s → x ∈ t) :=
begin
rcases hs.exists_countable_dense_subset with ⟨t, hts, htc, htd⟩,
refine ⟨(t ∪ ({x | is_bot x} ∪ {x | is_top x})) ∩ s, _, _, _, _, _⟩,
exacts [inter_subset_right _ _,
(htc.union ((countable_is_bot α).union (countable_is_top α))).mono (inter_subset_left _ _),
htd.mono (subset_inter (subset_union_left _ _) hts),
λ x hx hxs, ⟨or.inr $ or.inl hx, hxs⟩, λ x hx hxs, ⟨or.inr $ or.inr hx, hxs⟩]
end
instance separable_space_univ {α : Type*} [topological_space α] [separable_space α] :
separable_space (univ : set α) :=
(equiv.set.univ α).symm.surjective.dense_range.separable_space
(continuous_subtype_mk _ continuous_id)
/-- If `α` is a separable topological space with a partial order, then there exists a countable
dense set `s : set α` that contains those of both bottom and top elements of `α` that actually
exist. -/
lemma exists_countable_dense_bot_top (α : Type*) [topological_space α] [separable_space α]
[partial_order α] :
∃ s : set α, countable s ∧ dense s ∧ (∀ x, is_bot x → x ∈ s) ∧ (∀ x, is_top x → x ∈ s) :=
by simpa using dense_univ.exists_countable_dense_subset_bot_top
namespace topological_space
universe u
variables (α : Type u) [t : topological_space α]
include t
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated)
attribute [instance] first_countable_topology.nhds_generated_countable
namespace first_countable_topology
variable {α}
/-- In a first-countable space, a cluster point `x` of a sequence
is the limit of some subsequence. -/
lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α}
(hx : map_cluster_pt x at_top u) :
∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) :=
subseq_tendsto_of_ne_bot hx
end first_countable_topology
variables {α}
instance is_countably_generated_nhds_within (x : α) [is_countably_generated (𝓝 x)] (s : set α) :
is_countably_generated (𝓝[s] x) :=
inf.is_countably_generated _ _
variable (α)
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable [] :
∃ b : set (set α), countable b ∧ t = topological_space.generate_from b)
variable {α}
protected lemma is_topological_basis.second_countable_topology
{b : set (set α)} (hb : is_topological_basis b) (hc : countable b) :
second_countable_topology α :=
⟨⟨b, hc, hb.eq_generate_from⟩⟩
variable (α)
lemma exists_countable_basis [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in
⟨b',
((countable_set_of_finite_subset hb₁).mono
(by { simp only [← and_assoc], apply inter_subset_left })).image _,
assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp),
is_topological_basis_of_subbasis hb₂⟩
/-- A countable topological basis of `α`. -/
def countable_basis [second_countable_topology α] : set (set α) :=
(exists_countable_basis α).some
lemma countable_countable_basis [second_countable_topology α] : countable (countable_basis α) :=
(exists_countable_basis α).some_spec.1
instance encodable_countable_basis [second_countable_topology α] :
encodable (countable_basis α) :=
(countable_countable_basis α).to_encodable
lemma empty_nmem_countable_basis [second_countable_topology α] : ∅ ∉ countable_basis α :=
(exists_countable_basis α).some_spec.2.1
lemma is_basis_countable_basis [second_countable_topology α] :
is_topological_basis (countable_basis α) :=
(exists_countable_basis α).some_spec.2.2
lemma eq_generate_from_countable_basis [second_countable_topology α] :
‹topological_space α› = generate_from (countable_basis α) :=
(is_basis_countable_basis α).eq_generate_from
variable {α}
lemma is_open_of_mem_countable_basis [second_countable_topology α] {s : set α}
(hs : s ∈ countable_basis α) : is_open s :=
(is_basis_countable_basis α).is_open hs
lemma nonempty_of_mem_countable_basis [second_countable_topology α] {s : set α}
(hs : s ∈ countable_basis α) : s.nonempty :=
ne_empty_iff_nonempty.1 $ ne_of_mem_of_not_mem hs $ empty_nmem_countable_basis α
variable (α)
@[priority 100] -- see Note [lower instance priority]
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
⟨λ x, has_countable_basis.is_countably_generated $
⟨(is_basis_countable_basis α).nhds_has_basis, (countable_countable_basis α).mono $
inter_subset_left _ _⟩⟩
/-- If `β` is a second-countable space, then its induced topology
via `f` on `α` is also second-countable. -/
lemma second_countable_topology_induced (β)
[t : topological_space β] [second_countable_topology β] (f : α → β) :
@second_countable_topology α (t.induced f) :=
begin
rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩,
refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ },
rw [eq, induced_generate_from_eq]
end
instance subtype.second_countable_topology (s : set α) [second_countable_topology α] :
second_countable_topology s :=
second_countable_topology_induced s α coe
/- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/
instance {β : Type*} [topological_space β]
[second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) :=
((is_basis_countable_basis α).prod (is_basis_countable_basis β)).second_countable_topology $
(countable_countable_basis α).image2 (countable_countable_basis β) _
instance second_countable_topology_encodable {ι : Type*} {π : ι → Type*}
[encodable ι] [t : ∀a, topological_space (π a)] [∀a, second_countable_topology (π a)] :
second_countable_topology (∀a, π a) :=
begin
have : t = (λa, generate_from (countable_basis (π a))),
from funext (assume a, (is_basis_countable_basis (π a)).eq_generate_from),
rw [this, pi_generate_from_eq],
constructor, refine ⟨_, _, rfl⟩,
have : countable {T : set (Π i, π i) | ∃ (I : finset ι) (s : Π i : I, set (π i)),
(∀ i, s i ∈ countable_basis (π i)) ∧ T = {f | ∀ i : I, f i ∈ s i}},
{ simp only [set_of_exists, ← exists_prop],
refine countable_Union (λ I, countable.bUnion _ (λ _ _, countable_singleton _)),
change countable {s : Π i : I, set (π i) | ∀ i, s i ∈ countable_basis (π i)},
exact countable_pi (λ i, countable_countable_basis _) },
convert this using 1, ext1 T, split,
{ rintro ⟨s, I, hs, rfl⟩,
refine ⟨I, λ i, s i, λ i, hs i i.2, _⟩,
simp only [set.pi, set_coe.forall'], refl },
{ rintro ⟨I, s, hs, rfl⟩,
rcases @subtype.surjective_restrict ι (λ i, set (π i)) _ (λ i, i ∈ I) s with ⟨s, rfl⟩,
exact ⟨s, I, λ i hi, hs ⟨i, hi⟩, set.ext $ λ f, subtype.forall⟩ }
end
instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*}
[fintype ι] [t : ∀a, topological_space (π a)] [∀a, second_countable_topology (π a)] :
second_countable_topology (∀a, π a) :=
by { letI := fintype.encodable ι, exact topological_space.second_countable_topology_encodable }
@[priority 100] -- see Note [lower instance priority]
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
begin
choose p hp using λ s : countable_basis α, nonempty_of_mem_countable_basis s.2,
exact ⟨⟨range p, countable_range _,
(is_basis_countable_basis α).dense_iff.2 $ λ o ho _, ⟨p ⟨o, ho⟩, hp _, mem_range_self _⟩⟩⟩
end
variables {α}
/-- A countable open cover induces a second-countable topology if all open covers
are themselves second countable. -/
lemma second_countable_topology_of_countable_cover {ι} [encodable ι] {U : ι → set α}
[∀ i, second_countable_topology (U i)] (Uo : ∀ i, is_open (U i)) (hc : (⋃ i, U i) = univ) :
second_countable_topology α :=
begin
have : is_topological_basis (⋃ i, image (coe : U i → α) '' (countable_basis (U i))),
from is_topological_basis_of_cover Uo hc (λ i, is_basis_countable_basis (U i)),
exact this.second_countable_topology
(countable_Union $ λ i, (countable_countable_basis _).image _)
end
/-- In a second-countable space, an open set, given as a union of open sets,
is equal to the union of countably many of those sets. -/
lemma is_open_Union_countable [second_countable_topology α]
{ι} (s : ι → set α) (H : ∀ i, is_open (s i)) :
∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i :=
begin
let B := {b ∈ countable_basis α | ∃ i, b ⊆ s i},
choose f hf using λ b : B, b.2.2,
haveI : encodable B := ((countable_countable_basis α).mono (sep_subset _ _)).to_encodable,
refine ⟨_, countable_range f,
subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩,
rintro _ ⟨i, rfl⟩ x xs,
rcases (is_basis_countable_basis α).exists_subset_of_mem_open xs (H _) with ⟨b, hb, xb, bs⟩,
exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩
end
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in
⟨subtype.val '' T, cT.image _,
image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs,
by rwa [sUnion_image, sUnion_eq_Union]⟩
/-- In a topological space with second countable topology, if `f` is a function that sends each
point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`,
`x ∈ s`, cover the whole space. -/
lemma countable_cover_nhds [second_countable_topology α] {f : α → set α}
(hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ :=
begin
rcases is_open_Union_countable (λ x, interior (f x)) (λ x, is_open_interior) with ⟨s, hsc, hsU⟩,
suffices : (⋃ x ∈ s, interior (f x)) = univ,
from ⟨s, hsc, flip eq_univ_of_subset this (bUnion_mono $ λ _ _, interior_subset)⟩,
simp only [hsU, eq_univ_iff_forall, mem_Union],
exact λ x, ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩
end
lemma countable_cover_nhds_within [second_countable_topology α] {f : α → set α} {s : set α}
(hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, countable t ∧ s ⊆ (⋃ x ∈ t, f x) :=
begin
have : ∀ x : s, coe ⁻¹' (f x) ∈ 𝓝 x, from λ x, preimage_coe_mem_nhds_subtype.2 (hf x x.2),
rcases countable_cover_nhds this with ⟨t, htc, htU⟩,
refine ⟨coe '' t, subtype.coe_image_subset _ _, htc.image _, λ x hx, _⟩,
simp only [bUnion_image, eq_univ_iff_forall, ← preimage_Union, mem_preimage] at htU ⊢,
exact htU ⟨x, hx⟩
end
end topological_space
open topological_space
variables {α β : Type*} [topological_space α] [topological_space β] {f : α → β}
protected lemma inducing.second_countable_topology [second_countable_topology β]
(hf : inducing f) : second_countable_topology α :=
by { rw hf.1, exact second_countable_topology_induced α β f }
protected lemma embedding.second_countable_topology [second_countable_topology β]
(hf : embedding f) : second_countable_topology α :=
hf.1.second_countable_topology
|
488fafe7d2cbb319a1f5b7e79334f19699fd4575 | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Lean/Parser/Basic.lean | 47ee936c8a649992a7573f35403433bc658aea7d | [
"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 | 76,393 | 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.Data.Trie
import Lean.Data.Position
import Lean.Syntax
import Lean.ToExpr
import Lean.Environment
import Lean.Attributes
import Lean.Message
import Lean.Compiler.InitAttr
import Lean.ResolveName
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these
parallel parsers apart from the first token, though we might change this in the future if the need arises.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
namespace Lean
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident info rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Maximal (and function application) precedence.
In the standard lean language, no parser has precedence higher than `maxPrec`.
Note that nothing prevents users from using a higher precedence, but we strongly
discourage them from doing it. -/
def maxPrec : Nat := eval_prec max
def argPrec : Nat := eval_prec arg
def leadPrec : Nat := eval_prec lead
def minPrec : Nat := eval_prec min
abbrev Token := String
structure TokenCacheEntry where
startPos : String.Pos := 0
stopPos : String.Pos := 0
token : Syntax := Syntax.missing
structure ParserCache where
tokenCache : TokenCacheEntry
def initCacheForInput (input : String) : ParserCache := {
tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/}
}
abbrev TokenTable := Trie Token
abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
Std.PersistentHashMap.insert s k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext where
input : String
fileName : String
fileMap : FileMap
deriving Inhabited
/-- Input context derived from elaboration of previous commands. -/
structure ParserModuleContext where
env : Environment
options : Options
-- for name lookup
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
structure ParserContext extends InputContext, ParserModuleContext where
prec : Nat
tokens : TokenTable
quotDepth : Nat := 0
suppressInsideQuot : Bool := false
savedPos? : Option String.Pos := none
forbiddenTk? : Option Token := none
def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) :=
ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id
structure Error where
unexpected : String := ""
expected : List String := []
deriving Inhabited, BEq
namespace Error
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected]
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e')
let expected := expected.toList.eraseReps
["expected " ++ expectedToString expected]
"; ".intercalate $ unexpected ++ expected
instance : ToString Error := ⟨Error.toString⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState where
stxStack : Array Syntax := #[]
/--
Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser`
for the use of `checkLhsPrec` in trailing parsers.
Note that with chaining, the preceding parser can be another trailing parser:
in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/
lhsPrec : Nat := 0
pos : String.Pos := 0
cache : ParserCache
errorMsg : Option Error := none
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos }
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ s with pos := pos }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ s with cache := cache }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ s with stxStack := s.stxStack.push n }
def popSyntax (s : ParserState) : ParserState :=
{ s with stxStack := s.stxStack.pop }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ s with pos := input.next pos }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos
mkErrorStringWithPos ctx.fileName pos (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, use `missing` instead.
-- Thus we ensure the property that an syntax tree contains (at least) one `missing` node
-- if (and only if) there was a parse error.
-- We should not create an actual node of kind `k` in this case because it would mean we
-- choose an "arbitrary" node (in practice the last one) in an alternative of the form
-- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we
-- instead return a less misleading single `missing` node without randomly selecting any `ki`.
let stack := stack.push Syntax.missing
⟨stack, lhsPrec, pos, cache, err⟩
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size)
let stack := stack.shrink iniStackSz
let stack := stack.push newNode
⟨stack, lhsPrec, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size)
let stack := stack.shrink (iniStackSz - 1)
let stack := stack.push newNode
⟨stack, lhsPrec, pos, cache, err⟩
def setError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩
def mkEOIError (s : ParserState) (expected : List String := []) : ParserState :=
s.mkUnexpectedError "unexpected end of input" expected
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState :=
match s, initStackSz? with
| ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
| ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState :=
match s, initStackSz? with
| ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩
| ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance : Inhabited ParserFn where
default := fun ctx s => s
inductive FirstTokens where
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List Token → FirstTokens
| optTokens : List Token → FirstTokens
deriving Inhabited
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : ToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo where
collectTokens : List Token → List Token := id
collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id
firstTokens : FirstTokens := FirstTokens.unknown
deriving Inhabited
structure Parser where
info : ParserInfo := {}
fn : ParserFn
deriving Inhabited
abbrev TrailingParser := Parser
def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn :=
fun c s =>
let sz := s.stxStack.size
let s' := p c s
dbg_trace "{label}
pos: {s'.pos}
err: {s'.errorMsg}
out: {s'.stxStack.extract sz s'.stxStack.size}" s'
def dbgTraceState (label : String) (p : Parser) : Parser where
fn := dbgTraceStateFn label p.fn
info := p.info
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
@[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := {
info := epsilonInfo,
fn := checkStackTopFn p msg
}
@[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens
}
@[inline] def andthen (p q : Parser) : Parser := {
info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn
}
instance : AndThen Parser := ⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens
}
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := {
info := nodeInfo n p.info,
fn := nodeFn n p.fn
}
def errorFn (msg : String) : ParserFn := fun _ s =>
s.mkUnexpectedError msg
@[inline] def error (msg : String) : Parser := {
info := epsilonInfo,
fn := errorFn msg
}
def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some pos =>
let pos := if delta then c.input.next pos else pos
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩
/- Generate an error at the position saved with the `withPosition` combinator.
If `delta == true`, then it reports at saved position+1.
This useful to make sure a parser consumed at least one character. -/
@[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := {
fn := errorAtSavedPosFn msg delta
}
/- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn := fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := checkPrecFn prec
}
/- Succeeds if `c.lhsPrec >= prec` -/
def checkLhsPrecFn (prec : Nat) : ParserFn := fun c s =>
if s.lhsPrec >= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := checkLhsPrecFn prec
}
def setLhsPrecFn (prec : Nat) : ParserFn := fun c s =>
if s.hasError then s
else { s with lhsPrec := prec }
@[inline] def setLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := setLhsPrecFn prec
}
def checkInsideQuotFn : ParserFn := fun c s =>
if c.quotDepth > 0 && !c.suppressInsideQuot then s
else s.mkUnexpectedError "unexpected syntax outside syntax quotation"
@[inline] def checkInsideQuot : Parser := {
info := epsilonInfo,
fn := checkInsideQuotFn
}
def checkOutsideQuotFn : ParserFn := fun c s =>
if !c.quotDepth == 0 || c.suppressInsideQuot then s
else s.mkUnexpectedError "unexpected syntax inside syntax quotation"
@[inline] def checkOutsideQuot : Parser := {
info := epsilonInfo,
fn := checkOutsideQuotFn
}
def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s =>
p { c with quotDepth := c.quotDepth + i |>.toNat } s
@[inline] def incQuotDepth (p : Parser) : Parser := {
info := p.info,
fn := addQuotDepthFn 1 p.fn
}
@[inline] def decQuotDepth (p : Parser) : Parser := {
info := p.info,
fn := addQuotDepthFn (-1) p.fn
}
def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s =>
p { c with suppressInsideQuot := true } s
@[inline] def suppressInsideQuot (p : Parser) : Parser := {
info := p.info,
fn := suppressInsideQuotFn p.fn
}
@[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p >> setLhsPrec prec
@[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := {
info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn
}
@[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩
else s
| other => other
def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors
else
s
| none => s
@[inline] def orelseFn (p q : ParserFn) : ParserFn :=
orelseFnCore p q true
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens
}
/--
Run `p`, falling back to `q` if `p` failed without consuming any input.
NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser
producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...`
is fine as well. -/
@[inline] def orelse (p q : Parser) : Parser := {
info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn
}
instance : OrElse Parser := ⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := {
collectTokens := info.collectTokens,
collectKinds := info.collectKinds
}
def atomicFn (p : ParserFn) : ParserFn := fun c s =>
let iniPos := s.pos
match p c s with
| ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩
| other => other
@[inline] def atomic (p : Parser) : Parser := {
info := p.info,
fn := atomicFn p.fn
}
def optionalFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional
}
@[inline] def optionalNoAntiquot (p : Parser) : Parser := {
info := optionaInfo p.info,
fn := optionalFn p.fn
}
def lookaheadFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser := {
info := p.info,
fn := lookaheadFn p.fn
}
def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos
s.mkUnexpectedError s!"unexpected {msg}"
@[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := {
fn := notFollowedByFn p.fn msg
}
partial def manyAux (p : ParserFn) : ParserFn := fun c s => do
let iniSz := s.stackSize
let iniPos := s.pos
let mut s := p c s
if s.hasError then
return if iniPos == s.pos then s.restore iniSz iniPos else s
if iniPos == s.pos then
return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
if s.stackSize > iniSz + 1 then
s := s.mkNode nullKind iniSz
manyAux p c s
@[inline] def manyFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := manyAux p c s
s.mkNode nullKind iniSz
@[inline] def manyNoAntiquot (p : Parser) : Parser := {
info := noFirstTokenInfo p.info,
fn := manyFn p.fn
}
@[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := andthenFn p (manyAux p) c s
s.mkNode nullKind iniSz
@[inline] def many1NoAntiquot (p : Parser) : Parser := {
info := p.info,
fn := many1Fn p.fn
}
private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn :=
let rec parse (pOpt : Bool) (c s) := do
let sz := s.stackSize
let pos := s.pos
let mut s := p c s
if s.hasError then
if s.pos > pos then
return s.mkNode nullKind iniSz
else if pOpt then
s := s.restore sz pos
return s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
s := s.pushSyntax Syntax.missing
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
let sz := s.stackSize
let pos := s.pos
s := sep c s
if s.hasError then
s := s.restore sz pos
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
parse allowTrailingSep c s
parse pOpt
def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz true c s
def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds
}
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens
}
@[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn
}
@[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn
}
/- Apply `f` to the syntax object produced by `p` -/
def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s
else
let stx := s.stxStack.back
s.popSyntax.pushSyntax (f stx)
@[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds
}
@[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := {
info := withResultOfInfo p.info,
fn := withResultOfFn p.fn f
}
@[inline] def many1Unbox (p : Parser) : Parser :=
withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx
partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn p c (s.next c.input i)
def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then eoi s
else
let curr := input.get i
let i := input.next i
if curr == '-' then
if input.atEnd i then eoi s
else
let curr := input.get i
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then eoi s
else
let curr := input.get i
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
where
eoi s := s.mkUnexpectedError "unterminated comment"
/- Consume whitespace and comments -/
partial def whitespace : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr == '\t' then
s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them"
else if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let startPos := i
let i := input.next i
let curr := input.get i
if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{ str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
if trailingWs then
let s := whitespace c s
let stopPos' := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s =>
let startPos := s.pos
let s := p c s
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let i := input.next i
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if isQuotable curr then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
s.pushSyntax (Syntax.mkLit n val info)
def charLitFnAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let s := s.setPos (input.next i)
let s := if curr == '\\' then quotedCharFn c s else s
if s.hasError then s
else
let i := s.pos
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos
else
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s
else strLitFnAux startPos c s
def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s =>
let s := takeWhileFn (fun c => c.isDigit) c s
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' || curr == 'e' || curr == 'E' then
let s := parseOptDot s
let s := parseOptExp s
mkNodeToken scientificLitKind startPos c s
else
mkNodeToken numLitKind startPos c s
where
parseOptDot s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
let curr := input.get i
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else
s.setPos i
else
s
parseOptExp s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == 'e' || curr == 'E' then
let i := input.next i
let i := if input.get i == '-' then input.next i else i
let curr := input.get i
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else
s.setPos i
else
s
def binNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn := fun c s =>
let input := c.input
let startPos := s.pos
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos
if curr == '0' then
let i := input.next startPos
let curr := input.get i
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool := fun input s =>
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
if input.atEnd i then
false
else
let curr := input.get i
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
if c.forbiddenTk? == some tk then
s.mkErrorAt "forbidden token" startPos
else
let input := c.input
let leading := mkEmptySubstringAt input startPos
let stopPos := startPos + tk.bsize
let s := s.setPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s =>
let stopPos := s.pos
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring }
let s := whitespace c s
let trailingStopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
let atom := mkIdent info rawVal val
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn :=
let rec parse (r : Name) (c s) := do
let input := c.input
let i := s.pos
if input.atEnd i then
return s.mkEOIError
let curr := input.get i
if isIdBeginEscape curr then
let startPart := input.next i
let s := takeUntilFn isIdEndEscape c (s.setPos startPart)
if input.atEnd s.pos then
return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart
let stopPart := s.pos
let s := s.next c.input s.pos
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i
let s := takeWhileFn isIdRest c (s.next input i)
let stopPart := s.pos
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
parse r
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let s := identFnAux startPos none Name.anonymous c (s.next input startPos)
if s.hasError then
s
else
let stx := s.stxStack.back
match stx with
| Syntax.ident info rawStr _ _ =>
let s := s.popSyntax
s.pushSyntax (Syntax.mkNameLit rawStr.toString info)
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn := fun c s =>
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
-- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache`
match s with
| ⟨stack, lhsPrec, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back
⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn (expected : List String := []) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError expected
else
let tkc := s.cache.tokenCache
if tkc.startPos == i then
let s := s.pushSyntax tkc.token
s.setPos tkc.stopPos
else
let s := tokenFnAux c s
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let iniSz := s.stackSize
let iniPos := s.pos
let s := tokenFn [] c s
if let some e := s.errorMsg then (s.restore iniSz iniPos, Except.error s)
else
let stx := s.stxStack.back
(s.restore iniSz iniPos, Except.ok stx)
def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let tkc := s.cache.tokenCache
if tkc.startPos == s.pos then
(s, Except.ok tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn expected c s
if s.hasError then
s
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz
| _ => s.mkErrorsAt expected startPos initStackSz
def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo := {
collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ]
}
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbolNoAntiquot (sym : String) : Parser :=
let sym := sym.trim
{ info := symbolInfo sym,
fn := symbolFn sym }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.stopPos == trailing.startPos
| _ => false
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universe (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn [errorMsg] c s
if s.hasError then s
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos initStackSz
| _ => s.mkErrorAt errorMsg startPos initStackSz
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := {
firstTokens :=
if includeIdent then
FirstTokens.tokens [ sym, "ident" ]
else
FirstTokens.tokens [ sym ]
}
@[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn :=
let rec parse (j c s) :=
if sym.atEnd j then s
else
let i := s.pos
let input := c.input
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else parse (sym.next j) c (s.next input i)
parse j
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s =>
let prev := s.stxStack.back
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String := "space before") : Parser := {
info := epsilonInfo,
fn := checkWsBeforeFn errorMsg
}
def checkTailLinebreak (prev : Syntax) : Bool :=
match prev.getTailInfo with
| SourceInfo.original _ _ trailing _ => trailing.contains '\n'
| _ => false
def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun c s =>
let prev := s.stxStack.back
if checkTailLinebreak prev then s else s.mkError errorMsg
def checkLinebreakBefore (errorMsg : String := "line break") : Parser := {
info := epsilonInfo
fn := checkLinebreakBeforeFn errorMsg
}
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s =>
let prev := pickNonNone s.stxStack
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String := "no space before") : Parser := {
info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg
}
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := {
collectTokens := fun tks => sym :: asciiSym :: tks,
firstTokens := FirstTokens.tokens [ sym, asciiSym ]
}
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser :=
let sym := sym.trim
let asciiSym := asciiSym.trim
{ info := unicodeSymbolInfo sym asciiSym,
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn :=
fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["numeral"] c s
if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s
@[inline] def numLitNoAntiquot : Parser := {
fn := numLitFn,
info := mkAtomicInfo "numLit"
}
def scientificLitFn : ParserFn :=
fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["scientific number"] c s
if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s
@[inline] def scientificLitNoAntiquot : Parser := {
fn := scientificLitFn,
info := mkAtomicInfo "scientificLit"
}
def strLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["string literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s
@[inline] def strLitNoAntiquot : Parser := {
fn := strLitFn,
info := mkAtomicInfo "strLit"
}
def charLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["char literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s
@[inline] def charLitNoAntiquot : Parser := {
fn := charLitFn,
info := mkAtomicInfo "charLit"
}
def nameLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["Name literal"] c s
if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s
@[inline] def nameLitNoAntiquot : Parser := {
fn := nameLitFn,
info := mkAtomicInfo "nameLit"
}
def identFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["identifier"] c s
if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s
@[inline] def identNoAntiquot : Parser := {
fn := identFn,
info := mkAtomicInfo "ident"
}
@[inline] def rawIdentNoAntiquot : Parser := {
fn := rawIdentFn
}
def identEqFn (id : Name) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["identifier"] c s
if s.hasError then
s
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s
| _ => s.mkErrorAt "identifier" iniPos initStackSz
@[inline] def identEq (id : Name) : Parser := {
fn := identEqFn id,
info := mkAtomicInfo "ident"
}
namespace ParserState
def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax :=
let node := s.back
s.shrink startStackSize |>.push node
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩
| other => other
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState :=
s.keepLatest startStackSize
end ParserState
def invalidLongestMatchParser (s : ParserState) : ParserState :=
s.mkError "longestMatch parsers must generate exactly one Syntax node"
/--
Auxiliary function used to execute parsers provided to `longestMatchFn`.
Push `left?` into the stack if it is not `none`, and execute `p`.
Remark: `p` must produce exactly one syntax node.
Remark: the `left?` is not none when we are processing trailing parsers. -/
def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => do
/-
We assume any registered parser `p` has one of two forms:
* a direct call to `leadingParser` or `trailingParser`
* a direct call to a (leading) token parser
In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser`
set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere.
In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience
of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec`
will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field
to `maxPrec` in the leading case. -/
let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec }
let startSize := s.stackSize
if let some left := left? then
s := s.pushSyntax left
s := p c s
-- stack contains `[..., result ]`
if s.stackSize == startSize + 1 then
s -- success or error with the expected number of nodes
else if s.hasError then
-- error with an unexpected number of nodes.
s.shrinkStack startSize |>.pushSyntax Syntax.missing
else
-- parser succeded with incorrect number of nodes
invalidLongestMatchParser s
def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn)
: ParserContext → ParserState → ParserState × Nat := fun c s =>
let prevErrorMsg := s.errorMsg
let prevStopPos := s.pos
let prevSize := s.stackSize
let prevLhsPrec := s.lhsPrec
let s := s.restore prevSize startPos
let s := runLongestMatchParser left? startLhsPrec p c s
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev
-- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum
else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio)
| none, some _ => -- prev succeeded, current failed
({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio)
| some oldError, some _ => -- both failed
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio)
else (s.mergeErrors prevSize oldError, prio)
| some _, none => -- prev failed, current succeeded
let successNode := s.stxStack.back
let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack
(s.pushSyntax successNode, prio) -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn :=
let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) :=
match ps with
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s
parse prevPrio ps c s
parse prevPrio ps
def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s
| p::ps => fun c s =>
let startSize := s.stackSize
let startLhsPrec := s.lhsPrec
let startPos := s.pos
let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s
longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column ≥ savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser :=
{ fn := checkColGeFn errorMsg }
@[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column > savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser :=
{ fn := checkColGtFn errorMsg }
@[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.line == savedPos.line then s
else s.mkError errorMsg
@[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser :=
{ fn := checkLineEqFn errorMsg }
@[inline] def withPosition (p : Parser) : Parser := {
info := p.info,
fn := fun c s =>
p.fn { c with savedPos? := s.pos } s
}
@[inline] def withoutPosition (p : Parser) : Parser := {
info := p.info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos
p.fn { c with savedPos? := none } s
}
@[inline] def withForbidden (tk : Token) (p : Parser) : Parser := {
info := p.info,
fn := fun c s => p.fn { c with forbiddenTk? := tk } s
}
@[inline] def withoutForbidden (p : Parser) : Parser := {
info := p.info,
fn := fun c s => p.fn { c with forbiddenTk? := none } s
}
def eoiFn : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else s.mkError "expected end of file"
@[inline] def eoi : Parser :=
{ fn := eoiFn }
open Std (RBMap RBMap.empty)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp
namespace TokenMap
def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => Std.RBMap.insert map k [v]
| some vs => Std.RBMap.insert map k (v::vs)
instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables where
leadingTable : TokenMap (Parser × Nat) := {}
leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token
trailingTable : TokenMap (Parser × Nat) := {}
trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application
instance : Inhabited PrattParsingTables := ⟨{}⟩
/-
The type `leadingIdentBehavior` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers.
- `LeadingIdentBehavior.default`: if the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident".
- `LeadingIdentBehavior.symbol`: if the leading token is
an identifier `<foo>`, and there are parsers `P` associated with
the toek `<foo>`, then it executes `P`. Otherwise, it executes
only the parsers associated with the auxiliary token "ident".
- `LeadingIdentBehavior.both`: if the leading token
an identifier `<foo>`, the it executes the parsers associated
with token `<foo>` and parsers associated with the auxiliary
token "ident".
We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both`
and `nonReservedSymbol` parser to implement the `tactic` parsers.
The idea is to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function).
-/
inductive LeadingIdentBehavior where
| default
| symbol
| both
deriving Inhabited, BEq
/--
Each parser category is implemented using a Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The method
```
categoryParser `term prec
```
executes the Pratt's parser for category `term` with precedence `prec`.
That is, only parsers with precedence at least `prec` are considered.
The method `termParser prec` is equivalent to the method above.
-/
structure ParserCategory where
tables : PrattParsingTables
behavior : LeadingIdentBehavior
deriving Inhabited
abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α :=
let (s, stx) := peekToken c s
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, [])
match stx with
| Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym)
| Except.ok (Syntax.ident _ _ val _) =>
match behavior with
| LeadingIdentBehavior.default => find identKind
| LeadingIdentBehavior.symbol =>
match map.find? val with
| some as => (s, as)
| none => find identKind
| LeadingIdentBehavior.both =>
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
| Except.ok (Syntax.node k _) => find k
| Except.ok _ => (s, [])
| Except.error s' => (s', [])
abbrev CategoryParserFn := Name → ParserFn
builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace
builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get
def categoryParserFn (catName : Name) : ParserFn := fun ctx s =>
categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (prec : Nat) : Parser := {
fn := fun c s => categoryParserFn catName { c with prec := prec } s
}
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (prec : Nat := 0) : Parser :=
categoryParser `term prec
/- ============== -/
/- Antiquotations -/
/- ============== -/
/-- Fail if previous token is immediately followed by ':'. -/
def checkNoImmediateColon : Parser := {
fn := fun c s =>
let prev := s.stxStack.back
if checkTailNoWs prev then
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s =>
match p c s with
| s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")")
def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
@[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do
let s := p c s
if s.hasError || c.quotDepth == 0 then
return s
let iniSz := s.stackSize
let iniPos := s.pos
let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s
if s.hasError then
return s.restore iniSz iniPos
s.mkNode (`token_antiquot) (iniSz - 1)
@[inline] def tokenWithAntiquot (p : Parser) : Parser where
fn := tokenWithAntiquotFn p.fn
info := p.info
@[inline] def symbol (sym : String) : Parser :=
tokenWithAntiquot (symbolNoAntiquot sym)
instance : Coe String Parser := ⟨fun s => symbol s ⟩
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent)
@[inline] def unicodeSymbol (sym asciiSym : String) : Parser :=
tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym)
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot
let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
leadingNode kind maxPrec $ atomic $
setExpected [] "$" >>
manyNoAntiquot (checkNoWsBefore "" >> "$") >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP
def tryAnti (c : ParserContext) (s : ParserState) : Bool := do
if c.quotDepth == 0 then
return false
let (s, stx) := peekToken c s
match stx with
| Except.ok stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s =>
if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser := {
fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info
}
def withoutInfo (p : Parser) : Parser :=
{ fn := p.fn }
/-- Parse `$[p]suffix`, e.g. `$[p],*`. -/
def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser :=
let kind := kind ++ `antiquot_scope
leadingNode kind maxPrec $ atomic $
setExpected [] "$" >>
manyNoAntiquot (checkNoWsBefore "" >> "$") >>
checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >>
suffix
@[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do
let s := p c s
if s.hasError || c.quotDepth == 0 || !s.stxStack.back.isAntiquot then
return s
let iniSz := s.stackSize
let iniPos := s.pos
let s := suffix c s
if s.hasError then
return s.restore iniSz iniPos
s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2)
/-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/
@[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := {
info := andthenInfo p.info suffix.info,
fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn
}
def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) :=
-- prevent `p`'s info from being collected twice
withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix)
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser :=
withAntiquot (mkAntiquot name kind anonymous) $ node kind p
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def sepByElemParser (p : Parser) (sep : String) : Parser :=
withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*"))
def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=
sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep
def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=
sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep
def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s =>
let stack := s.stxStack
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s }
unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s =>
match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|>
ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with
| Except.ok p => p.fn ctx s
| Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}"
@[implementedBy evalParserConstUnsafe]
constant evalParserConst (declName : Name) : ParserFn
unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s =>
let stack := s.stxStack
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident (val := parserName) .. =>
match ctx.resolveName parserName with
| [(parserName, [])] =>
let iniSz := s.stackSize
let s := evalParserConst parserName ctx s
if !s.hasError && s.stackSize != iniSz + 1 then
s.mkUnexpectedError "expected parser to return exactly one syntax object"
else
s
| _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}"
| _ => s.mkUnexpectedError s!"unknown parser {parserName}"
| _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier")
@[implementedBy parserOfStackFnUnsafe]
constant parserOfStackFn (offset : Nat) : ParserFn
def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => parserOfStackFn offset { c with prec := prec } s }
register_builtin_option internal.parseQuotWithCurrentStage : Bool := {
defValue := false
group := "internal"
descr := "(Lean bootstrapping) use parsers from the current stage inside quotations"
}
/-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/
def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with
fn := fun c s =>
if c.quotDepth > 0 && !c.suppressInsideQuot && internal.parseQuotWithCurrentStage.get c.options && c.env.contains declName then
evalParserConst declName c s
else
p.fn c s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => do
let iniSz := s.stackSize
let (s, ps) := indexed tables.leadingTable c s behavior
if s.hasError then
return s
let ps := tables.leadingParsers ++ ps
if ps.isEmpty then
return s.mkError (toString kind)
let s := longestMatchFn none ps c s
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables behavior)
def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s =>
longestMatchFn left (ps ++ tables.trailingParsers) c s
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := do
let iniSz := s.stackSize
let iniPos := s.pos
let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default
if s.hasError then
-- Discard token parse errors and break the trailing loop instead.
-- The error will be flagged when the next leading position is parsed, unless the token
-- is in fact valid there (e.g. EOI at command level, no-longer forbidden token)
return s.restore iniSz iniPos
if ps.isEmpty && tables.trailingParsers.isEmpty then
return s -- no available trailing parser
let left := s.stxStack.back
let s := s.popSyntax
let s := trailingLoopStep tables left ps c s
if s.hasError then
-- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`.
-- This is necessary for fallback parsers like `app` that pretend to be always applicable.
return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s
trailingLoop tables c s
/--
Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power.
In our implementation, parsers have precedence instead. This method selects a parser (or more, via
`longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers
are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example:
```
syntax term:51 "≤" ident "<" term "|" term : index
```
Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set
is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`.
After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence
at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`.
Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our
implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible,
modular and easier to understand.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := leadingParser kind tables behavior antiquotParser c s
if s.hasError then
s
else
trailingLoop tables c s
def fieldIdxFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let curr := c.input.get iniPos
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos initStackSz
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) {
fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx"
}
@[inline] def skip : Parser := {
fn := fun c s => s,
info := epsilonInfo
}
end Parser
namespace Syntax
section
variable {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
end
end Syntax
end Lean
|
7c90c70a4dd9f51835c7d9c7adb5924a6f212233 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /stage0/src/Lean/Parser/Basic.lean | efa1d8135421de2feec13d000a6b76ab23982939 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 62,393 | 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
-/
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `parser! p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these
parallel parsers apart from the first token, though we might change this in the future if the need arises.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
import Lean.Data.Trie
import Lean.Data.Position
import Lean.Syntax
import Lean.ToExpr
import Lean.Environment
import Lean.Attributes
import Lean.Message
import Lean.Compiler.InitAttr
namespace Lean
def quotedSymbolKind := `quotedSymbol
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident info rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Maximal (and function application) precedence.
In the standard lean language, no parser has precedence higher than `maxPrec`.
Note that nothing prevents users from using a higher precedence, but we strongly
discourage them from doing it. -/
def maxPrec : Nat := 1024
abbrev Token := String
structure TokenCacheEntry :=
(startPos stopPos : String.Pos := 0)
(token : Syntax := Syntax.missing)
structure ParserCache :=
(tokenCache : TokenCacheEntry)
def initCacheForInput (input : String) : ParserCache :=
{ tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} }
abbrev TokenTable := Trie Token
abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
s.insert k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext :=
(input : String)
(fileName : String)
(fileMap : FileMap)
instance InputContext.inhabited : Inhabited InputContext :=
⟨{ input := "", fileName := "", fileMap := arbitrary _ }⟩
structure ParserContext extends InputContext :=
(prec : Nat)
(env : Environment)
(tokens : TokenTable)
(insideQuot : Bool := false)
structure Error :=
(unexpected : String := "")
(expected : List String := [])
namespace Error
instance : Inhabited Error := ⟨{}⟩
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected];
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e');
let expected := expected.toList.eraseReps;
["expected " ++ expectedToString expected];
"; ".intercalate $ unexpected ++ expected
instance : HasToString Error := ⟨Error.toString⟩
protected def beq (e₁ e₂ : Error) : Bool :=
e₁.unexpected == e₂.unexpected && e₁.expected == e₂.expected
instance : HasBeq Error := ⟨Error.beq⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState :=
(stxStack : Array Syntax := #[])
(pos : String.Pos := 0)
(cache : ParserCache)
(errorMsg : Option Error := none)
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos }
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ s with pos := pos }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ s with cache := cache }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ s with stxStack := s.stxStack.push n }
def popSyntax (s : ParserState) : ParserState :=
{ s with stxStack := s.stxStack.pop }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ s with pos := input.next pos }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos;
mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `s`
s
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
def mkEOIError (s : ParserState) : ParserState :=
s.mkUnexpectedError "end of input"
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance ParserFn.inhabited : Inhabited ParserFn := ⟨fun _ => id⟩
inductive FirstTokens
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List Token → FirstTokens
| optTokens : List Token → FirstTokens
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : HasToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo :=
(collectTokens : List Token → List Token := id)
(collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id)
(firstTokens : FirstTokens := FirstTokens.unknown)
structure Parser :=
(info : ParserInfo := {})
(fn : ParserFn)
instance Parser.inhabited : Inhabited Parser :=
⟨{ fn := fun _ s => s }⟩
abbrev TrailingParser := Parser
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn :=
fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
@[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser :=
{ info := epsilonInfo,
fn := checkStackTopFn p msg }
@[inline] def andthenFn (p q : ParserFn) : ParserFn :=
fun c s =>
let s := p c s;
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens }
@[inline] def andthen (p q : Parser) : Parser :=
{ info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn }
instance hasAndthen : HasAndthen Parser :=
⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens }
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser :=
{ info := nodeInfo n p.info,
fn := nodeFn n p.fn }
/- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn :=
fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkPrec (prec : Nat) : Parser :=
{ info := epsilonInfo,
fn := checkPrecFn prec }
def checkInsideQuotFn : ParserFn :=
fun c s =>
if c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax outside syntax quotation"
@[inline] def checkInsideQuot : Parser :=
{ info := epsilonInfo,
fn := checkInsideQuotFn }
def checkOutsideQuotFn : ParserFn :=
fun c s =>
if !c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax inside syntax quotation"
@[inline] def checkOutsideQuot : Parser :=
{ info := epsilonInfo,
fn := checkOutsideQuotFn }
def toggleInsideQuotFn (p : ParserFn) : ParserFn :=
fun c s => p { c with insideQuot := !c.insideQuot } s
@[inline] def toggleInsideQuot (p : Parser) : Parser :=
{ info := epsilonInfo,
fn := toggleInsideQuotFn p.fn }
@[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p
@[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser :=
{ info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn }
@[inline] def trailingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> trailingNodeAux n p
@[inline] def group (p : Parser) : Parser :=
node nullKind p
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, pos, cache, some (error1.merge error2)⟩
else s
| other => other
@[inline] def orelseFn (p q : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos
else
s
| none => s
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens }
@[inline] def orelse (p q : Parser) : Parser :=
{ info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn }
instance hashOrelse : HasOrelse Parser :=
⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ collectTokens := info.collectTokens,
collectKinds := info.collectKinds }
@[inline] def tryFn (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
match p c s with
| ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other => other
@[inline] def try (p : Parser) : Parser :=
{ info := p.info,
fn := tryFn p.fn }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s;
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional }
@[inline] def optional (p : Parser) : Parser :=
{ info := optionaInfo p.info,
fn := optionalFn p.fn }
@[inline] def lookaheadFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser :=
{ info := p.info,
fn := lookaheadFn p.fn }
@[inline] def notFollowedByFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos;
s.mkError "notFollowedBy"
@[inline] def notFollowedBy (p : Parser) : Parser :=
{ info := p.info,
fn := notFollowedByFn p.fn }
@[specialize] partial def manyAux (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
if iniPos == s.pos then s.restore iniSz iniPos else s
else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux c s
@[inline] def manyFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := manyAux p c s;
s.mkNode nullKind iniSz
@[inline] def many (p : Parser) : Parser :=
{ info := noFirstTokenInfo p.info,
fn := manyFn p.fn }
@[inline] def many1Fn (p : ParserFn) (unboxSingleton : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := andthenFn p (manyAux p) c s;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
@[inline] def many1 (p : Parser) (unboxSingleton := false) : Parser :=
{ info := p.info,
fn := many1Fn p.fn unboxSingleton }
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool)
(iniSz : Nat) (unboxSingleton : Bool) : Bool → ParserFn
| pOpt, c, s =>
let sz := s.stackSize;
let pos := s.pos;
let s := p c s;
if s.hasError then
if s.pos > pos then s
else if pOpt then
let s := s.restore sz pos;
if s.stackSize - iniSz == 2 && unboxSingleton then
s.popSyntax
else
s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let s := s.pushSyntax Syntax.missing;
s.mkNode nullKind iniSz
else
let sz := s.stackSize;
let pos := s.pos;
let s := sep c s;
if s.hasError then
let s := s.restore sz pos;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep c s
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz false true c s
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) (unboxSingleton : Bool) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz unboxSingleton false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens }
@[inline] def sepBy (p sep : Parser) (allowTrailingSep : Bool := false) : Parser :=
{ info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn }
@[inline] def sepBy1 (p sep : Parser) (allowTrailingSep : Bool := false) (unboxSingleton := false) : Parser :=
{ info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn unboxSingleton }
@[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
@[specialize] partial def takeUntilFn (p : Char → Bool) : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn c (s.next c.input i)
@[specialize] def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat → ParserFn
| nesting, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr == '-' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then s -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| c, s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
if trailingWs then
let s := whitespace c s;
let stopPos' := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| c, s =>
let startPos := s.pos;
let s := p c s;
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '\\' || curr == '\"' || curr == '\'' || curr == 'r' || curr == 'n' || curr == 't' then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn :=
fun c s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring };
let info := { leading := leading, pos := startPos, trailing := trailing : SourceInfo };
s.pushSyntax (mkStxLit n val info)
def charLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
let s := if curr == '\\' then quotedCharFn c s else s;
if s.hasError then s
else
let i := s.pos;
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn strLitFnAux c s
else strLitFnAux c s
def decimalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhileFn (fun c => c.isDigit) c s;
let input := c.input;
let i := s.pos;
let curr := input.get i;
let s :=
/- TODO(Leo): should we use a different kind for numerals containing decimal points? -/
if curr == '.' then
let i := input.next i;
let curr := input.get i;
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else s
else s;
mkNodeToken numLitKind startPos c s
def binNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s;
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s;
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s;
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn :=
fun c s =>
let input := c.input;
let startPos := s.pos;
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos;
if curr == '0' then
let i := input.next startPos;
let curr := input.get i;
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool
| input, s =>
let i := s.pos;
let curr := input.get i;
if curr == '.' then
let i := input.next i;
if input.atEnd i then
false
else
let curr := input.get i;
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn :=
fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
let input := c.input;
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + tk.bsize;
let s := s.setPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } tk;
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn :=
fun c s =>
let stopPos := s.pos;
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input;
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring };
let s := whitespace c s;
let trailingStopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring };
let info := { leading := leading, trailing := trailing, pos := startPos : SourceInfo };
let atom := mkIdent info rawVal val;
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option Token) : Name → ParserFn
| r, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if isIdBeginEscape curr then
let startPart := input.next i;
let s := takeUntilFn isIdEndEscape c (s.setPos startPart);
let stopPart := s.pos;
let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s;
if s.hasError then s
else
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i;
let s := takeWhileFn isIdRest c (s.next input i);
let stopPart := s.pos;
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let s := identFnAux startPos none Name.anonymous c (s.next input startPos);
if s.hasError then
s.mkErrorAt "invalid Name literal" startPos
else
let stx := s.stxStack.back;
match stx with
| Syntax.ident _ rawStr _ _ =>
let s := s.popSyntax;
s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString])
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
let curr := input.get i;
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i;
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
match s with
| ⟨stack, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back;
⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let tkc := s.cache.tokenCache;
if tkc.startPos == i then
let s := s.pushSyntax tkc.token;
s.setPos tkc.stopPos
else
let s := tokenFnAux c s;
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then (s.restore iniSz iniPos, none)
else
let stx := s.stxStack.back;
(s.restore iniSz iniPos, some stx)
@[inline] def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let tkc := s.cache.tokenCache;
if tkc.startPos == s.pos then
(s, some tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorsAt expected startPos
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos
| _ => s.mkErrorsAt expected startPos
@[inline] def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ] }
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbol (sym : String) : Parser :=
let sym := sym.trim;
{ info := symbolInfo sym,
fn := symbolFn sym }
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then s.mkErrorAt errorMsg startPos
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax;
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos
| _ => s.mkErrorAt errorMsg startPos
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo :=
{ firstTokens :=
if includeIdent then
FirstTokens.tokens [ sym, "ident" ]
else
FirstTokens.tokens [ sym ] }
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim;
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) : Nat → ParserFn
| j, c, s =>
if sym.atEnd j then s
else
let i := s.pos;
let input := c.input;
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else strAux (sym.next j) c (s.next input i)
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := s.stxStack.back;
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkWsBeforeFn errorMsg }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos == trailing.startPos
| _ => false
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := pickNonNone s.stxStack;
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg }
def symbolNoWsInfo (sym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ] }
@[inline] def symbolNoWsFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
if checkTailNoWs left then
let startPos := s.pos;
let input := c.input;
let s := strAux sym errorMsg 0 c s;
if s.hasError then s
else
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + sym.bsize;
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } sym;
s.pushSyntax atom
else
s.mkError errorMsg
@[inline] def symbolNoWsFn (sym : String) : ParserFn :=
symbolNoWsFnAux sym ("'" ++ sym ++ "' without whitespace around it")
/- Similar to `symbol`, but succeeds only if there is no space whitespace after leading term and after `sym`. -/
@[inline] def symbolNoWs (sym : String) : Parser :=
let sym := sym.trim;
{ info := symbolNoWsInfo sym,
fn := symbolNoWsFn sym }
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: asciiSym :: tks,
firstTokens := FirstTokens.tokens [ sym, asciiSym ] }
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbol (sym asciiSym : String) : Parser :=
let sym := sym.trim;
let asciiSym := asciiSym.trim;
{ info := unicodeSymbolInfo sym asciiSym,
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s
@[inline] def numLitNoAntiquot : Parser :=
{ fn := numLitFn,
info := mkAtomicInfo "numLit" }
def strLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s
@[inline] def strLitNoAntiquot : Parser :=
{ fn := strLitFn,
info := mkAtomicInfo "strLit" }
def charLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s
@[inline] def charLitNoAntiquot : Parser :=
{ fn := charLitFn,
info := mkAtomicInfo "charLit" }
def nameLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s
@[inline] def nameLitNoAntiquot : Parser :=
{ fn := nameLitFn,
info := mkAtomicInfo "nameLit" }
def identFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s
@[inline] def identNoAntiquot : Parser :=
{ fn := identFn,
info := mkAtomicInfo "ident" }
@[inline] def rawIdentNoAntiquot : Parser :=
{ fn := rawIdentFn }
def identEqFn (id : Name) : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorAt "identifier" iniPos
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s
| _ => s.mkErrorAt "identifier" iniPos
@[inline] def identEq (id : Name) : Parser :=
{ fn := identEqFn id,
info := mkAtomicInfo "ident" }
def quotedSymbolFn : ParserFn :=
nodeFn quotedSymbolKind (andthenFn (andthenFn (chFn '`') (rawFn (takeUntilFn (fun c => c == '`')))) (chFn '`' true))
-- TODO: remove after old frontend is gone
def quotedSymbol : Parser :=
{ fn := quotedSymbolFn }
def unquotedSymbolFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || s.stxStack.back.isIdent || isLitKind s.stxStack.back.getKind then
s.mkErrorAt "symbol" iniPos
else
s
def unquotedSymbol : Parser :=
{ fn := unquotedSymbolFn }
instance stringToParserCoe : HasCoe String Parser :=
⟨fun s => symbol s ⟩
namespace ParserState
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩
| other => other
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
let node := stack.back;
let stack := stack.shrink startStackSize;
let stack := stack.push node;
⟨stack, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState :=
s.keepLatest startStackSize
end ParserState
def invalidLongestMatchParser (s : ParserState) : ParserState :=
s.mkError "longestMatch parsers must generate exactly one Syntax node"
/--
Auxiliary function used to execute parsers provided to `longestMatchFn`.
Push `left?` into the stack if it is not `none`, and execute `p`.
After executing `p`, remove `left`.
Remark: `p` must produce exactly one syntax node.
Remark: the `left?` is not none when we are processing trailing parsers. -/
@[inline] def runLongestMatchParser (left? : Option Syntax) (p : ParserFn) : ParserFn :=
fun c s =>
let startSize := s.stackSize;
match left? with
| none =>
let s := p c s;
if s.hasError then s
else
-- stack contains `[..., result ]`
if s.stackSize == startSize + 1 then
s
else
invalidLongestMatchParser s
| some left =>
let s := s.pushSyntax left;
let s := p c s;
if s.hasError then s
else
-- stack contains `[..., left, result ]` we must remove `left`
if s.stackSize == startSize + 2 then
-- `p` created one node, then we just remove `left` and keep it
let r := s.stxStack.back;
let s := s.shrinkStack startSize; -- remove `r` and `left`
s.pushSyntax r -- add `r` back
else
invalidLongestMatchParser s
def longestMatchStep (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (p : ParserFn) : ParserFn :=
fun c s =>
let prevErrorMsg := s.errorMsg;
let prevStopPos := s.pos;
let prevSize := s.stackSize;
let s := s.restore prevSize startPos;
let s := runLongestMatchParser left? p c s;
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos then s.replaceLongest startSize
else if s.pos < prevStopPos then s.restore prevSize prevStopPos -- keep prev
else s
| none, some _ => -- prev succeeded, current failed
s.restore prevSize prevStopPos
| some oldError, some _ => -- both failed
if s.pos > prevStopPos then s.keepNewError prevSize
else if s.pos < prevStopPos then s.keepPrevError prevSize prevStopPos prevErrorMsg
else s.mergeErrors prevSize oldError
| some _, none => -- prev failed, current succeeded
let successNode := s.stxStack.back;
let s := s.shrinkStack startSize; -- restore stack to initial size to make sure (failure) nodes are removed from the stack
s.pushSyntax successNode -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) : List Parser → ParserFn
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let s := longestMatchStep left? startSize startPos p.fn c s;
longestMatchFnAux ps c s
def longestMatchFn (left? : Option Syntax) : List Parser → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => runLongestMatchParser left? p.fn
| p::ps => fun c s =>
let startSize := s.stackSize;
let startPos := s.pos;
let s := runLongestMatchParser left? p.fn c s;
if s.hasError then
let s := s.shrinkStack startSize;
longestMatchFnAux left? startSize startPos ps c s
else
longestMatchFnAux left? startSize startPos ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (col : Nat) (errorMsg : String) : ParserFn :=
fun c s =>
let pos := c.fileMap.toPosition s.pos;
if pos.column ≥ col then s
else s.mkError errorMsg
@[inline] def checkColGe (col : Nat) (errorMsg : String) : Parser :=
{ fn := checkColGeFn col errorMsg }
@[inline] def withPosition (p : Position → Parser) : Parser :=
{ info := (p { line := 1, column := 0 }).info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos;
(p pos).fn c s }
@[inline] def many1Indent (p : Parser) (errorMsg : String) : Parser :=
withPosition $ fun pos => many1 (checkColGe pos.column errorMsg >> p)
open Std (RBMap RBMap.empty)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => map.insert k [v]
| some vs => map.insert k (v::vs)
instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance {α : Type} : HasEmptyc (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables :=
(leadingTable : TokenMap Parser := {})
(leadingParsers : List Parser := []) -- for supporting parsers we cannot obtain first token
(trailingTable : TokenMap TrailingParser := {})
(trailingParsers : List TrailingParser := []) -- for supporting parsers such as function application
instance PrattParsingTables.inhabited : Inhabited PrattParsingTables := ⟨{}⟩
/--
Each parser category is implemented using a Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The field `leadingIdentAsSymbol` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers. If `leadingIdentAsSymbol == false` and the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". If
`leadingIdentAsSymbol == true` and the leading token is an
identifier `<foo>`, then `prattParser` combines the parsers
associated with the token `<foo>` with the parsers associated with
the auxiliary token "ident". We use this feature and the
`nonReservedSymbol` parser to implement the `tactic` parsers. We
use this approach to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function).
The method
```
categoryParser `term prec
```
executes the Pratt's parser for category `term` with precedence `prec`.
That is, only parsers with precedence at least `prec` are considered.
The method `termParser prec` is equivalent to the method above.
-/
structure ParserCategory :=
(tables : PrattParsingTables) (leadingIdentAsSymbol : Bool)
instance ParserCategory.inhabited : Inhabited ParserCategory := ⟨{ tables := {}, leadingIdentAsSymbol := false }⟩
abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (leadingIdentAsSymbol : Bool) : ParserState × List α :=
let (s, stx) := peekToken c s;
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, []);
match stx with
| some (Syntax.atom _ sym) => find (mkNameSimple sym)
| some (Syntax.ident _ _ val _) =>
if leadingIdentAsSymbol then
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
else
find identKind
| some (Syntax.node k _) => find k
| _ => (s, [])
abbrev CategoryParserFn := Name → ParserFn
def mkCategoryParserFnRef : IO (IO.Ref CategoryParserFn) :=
IO.mkRef $ fun _ => whitespace
@[init mkCategoryParserFnRef]
constant categoryParserFnRef : IO.Ref CategoryParserFn := arbitrary _
def mkCategoryParserFnExtension : IO (EnvExtension CategoryParserFn) :=
registerEnvExtension $ categoryParserFnRef.get
@[init mkCategoryParserFnExtension]
def categoryParserFnExtension : EnvExtension CategoryParserFn := arbitrary _
def categoryParserFn (catName : Name) : ParserFn :=
fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (prec : Nat) : Parser :=
{ fn := fun c s => categoryParserFn catName { c with prec := prec } s }
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (prec : Nat := 0) : Parser :=
categoryParser `term prec
/- ============== -/
/- Antiquotations -/
/- ============== -/
def dollarSymbol : Parser := symbol "$"
/-- Fail if previous token is immediately followed by ':'. -/
def checkNoImmediateColon : Parser :=
{ fn := fun c s =>
let prev := s.stxStack.back;
if checkTailNoWs prev then
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn :=
fun c s => match p c s with
| s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbol "(" >> toggleInsideQuot termParser >> ")")
def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot;
let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name;
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP;
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
node kind $ try $
setExpected [] dollarSymbol >>
many (checkNoWsBefore "" >> dollarSymbol) >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP >>
optional (checkNoWsBefore "" >> symbol "*")
def tryAnti (c : ParserContext) (s : ParserState) : Bool :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn :=
fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser :=
{ fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info }
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) : Parser :=
withAntiquot (mkAntiquot name kind false) $ node kind p
def ident : Parser :=
withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot
-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name
def rawIdent : Parser :=
withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot
def numLit : Parser :=
withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot
def strLit : Parser :=
withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot
def charLit : Parser :=
withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot
def nameLit : Parser :=
withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot
def categoryParserOfStackFn (offset : Nat) : ParserFn :=
fun ctx s =>
let stack := s.stxStack;
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let (s, ps) := indexed tables.leadingTable c s leadingIdentAsSymbol;
let ps := tables.leadingParsers ++ ps;
if ps.isEmpty then
s.mkError (toString kind)
else
let s := longestMatchFn none ps c s;
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables leadingIdentAsSymbol)
def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List Parser) : ParserFn :=
fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s
private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState :=
let s := mkResult s iniSz;
-- Stack contains `[..., left, result]`
-- We must remove `left`
let result := s.stxStack.back;
let s := s.popSyntax.popSyntax;
s.pushSyntax result
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) : ParserState → ParserState
| s =>
let identAsSymbol := false;
let (s, ps) := indexed tables.trailingTable c s identAsSymbol;
if ps.isEmpty && tables.trailingParsers.isEmpty then
s -- no available trailing parser
else
let left := s.stxStack.back;
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := trailingLoopStep tables left ps c s;
if s.hasError then
if s.pos == iniPos then s.restore iniSz iniPos else s
else
let s := mkTrailingResult s iniSz;
trailingLoop s
/--
Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power.
In our implementation, parsers have precedence instead. This method selects a parser (or more, via
`longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers
are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example:
```
syntax term:51 "≤" ident "<" term "|" term : index
```
Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set
is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`.
After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence
at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`.
Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our
implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible,
modular and easier to understand.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := leadingParser kind tables leadingIdentAsSymbol antiquotParser c s;
if s.hasError then
s
else
trailingLoop tables c s
def fieldIdxFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let curr := c.input.get iniPos;
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s;
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx)
{ fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx" }
end Parser
namespace Syntax
section
variables {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
@[inline] def foldSepArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlStepM (flip f) b 2
@[inline] def foldSepArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldSepArgsM f b)
@[inline] def forSepArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldSepArgsM (fun s _ => f s) ()
@[inline] def foldSepRevArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := do
let args := foldSepArgs s (fun arg (args : Array Syntax) => args.push arg) #[];
args.foldrM f b
@[inline] def foldSepRevArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := do
Id.run $ foldSepRevArgsM s f b
end
end Syntax
end Lean
section
variables {β : Type} {m : Type → Type} [Monad m]
open Lean
open Lean.Syntax
@[inline] def Array.foldSepByM (args : Array Syntax) (f : Syntax → β → m β) (b : β) : m β :=
args.foldlStepM (flip f) b 2
@[inline] def Array.foldSepBy (args : Array Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run $ args.foldSepByM f b
end
|
617b6929e3287efd02c00fec27226d826ceb3957 | e953c38599905267210b87fb5d82dcc3e52a4214 | /hott/hit/torus.hlean | 2668855728c322e673c5dd77785de7687c97e627 | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 3,547 | 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 torus
-/
import .two_quotient
open two_quotient eq bool unit relation
namespace torus
definition torus_R (x y : unit) := bool
local infix `⬝r`:75 := @e_closure.trans unit torus_R star star star
local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm unit torus_R star star
local notation `[`:max a `]`:0 := @e_closure.of_rel unit torus_R star star a
inductive torus_Q : Π⦃x y : unit⦄, e_closure torus_R x y → e_closure torus_R x y → Type :=
| Qmk : torus_Q ([ff] ⬝r [tt]) ([tt] ⬝r [ff])
definition torus := two_quotient torus_R torus_Q
definition base : torus := incl0 _ _ star
definition loop1 : base = base := incl1 _ _ ff
definition loop2 : base = base := incl1 _ _ tt
definition surf : loop1 ⬝ loop2 = loop2 ⬝ loop1 :=
incl2 _ _ torus_Q.Qmk
-- protected definition rec {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb)
-- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2)
-- (x : torus) : P x :=
-- sorry
-- example {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) (Pl2 : Pb =[loop2] Pb)
-- (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) : torus.rec Pb Pl1 Pl2 Pf base = Pb := idp
-- definition rec_loop1 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb)
-- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2)
-- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop1 = Pl1 :=
-- sorry
-- definition rec_loop2 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb)
-- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2)
-- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop2 = Pl2 :=
-- sorry
-- definition rec_surf {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb)
-- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2)
-- : cubeover P rfl1 (apds (torus.rec Pb Pl1 Pl2 Pf) fill) Pf
-- (vdeg_squareover !rec_loop2) (vdeg_squareover !rec_loop2)
-- (vdeg_squareover !rec_loop1) (vdeg_squareover !rec_loop1) :=
-- sorry
protected definition elim {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb)
(Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) (x : torus) : P :=
begin
induction x,
{ exact Pb},
{ induction s,
{ exact Pl1},
{ exact Pl2}},
{ induction q, exact Ps},
end
protected definition elim_on [reducible] {P : Type} (x : torus) (Pb : P)
(Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : P :=
torus.elim Pb Pl1 Pl2 Ps x
definition elim_loop1 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb)
(Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop1 = Pl1 :=
!elim_incl1
definition elim_loop2 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb)
(Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop2 = Pl2 :=
!elim_incl1
definition elim_surf {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb)
(Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1)
: square (ap02 (torus.elim Pb Pl1 Pl2 Ps) surf)
Ps
(!ap_con ⬝ (!elim_loop1 ◾ !elim_loop2))
(!ap_con ⬝ (!elim_loop2 ◾ !elim_loop1)) :=
!elim_incl2
end torus
attribute torus.base [constructor]
attribute /-torus.rec-/ torus.elim [unfold 6] [recursor 6]
--attribute torus.elim_type [unfold 9]
attribute /-torus.rec_on-/ torus.elim_on [unfold 2]
--attribute torus.elim_type_on [unfold 6]
|
d39ab2e8455b9e94e5e21d0440f17850b4305e41 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/CasesOn.lean | 7646455f9e2d326e7e3c81eabeef907b0d321c2a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 5,347 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.KAbstract
import Lean.Meta.Check
namespace Lean.Meta
structure CasesOnApp where
declName : Name
us : List Level
params : Array Expr
motive : Expr
indices : Array Expr
major : Expr
alts : Array Expr
altNumParams : Array Nat
remaining : Array Expr
/-- `true` if the `casesOn` can only eliminate into `Prop` -/
propOnly : Bool
/-- Return `some c` if `e` is a `casesOn` application. -/
def toCasesOnApp? (e : Expr) : MetaM (Option CasesOnApp) := do
let f := e.getAppFn
let .const declName us := f | return none
unless isCasesOnRecursor (← getEnv) declName do return none
let indName := declName.getPrefix
let .inductInfo info ← getConstInfo indName | return none
let args := e.getAppArgs
unless args.size >= info.numParams + 1 /- motive -/ + info.numIndices + 1 /- major -/ + info.numCtors do return none
let params := args[:info.numParams]
let motive := args[info.numParams]!
let indices := args[info.numParams + 1 : info.numParams + 1 + info.numIndices]
let major := args[info.numParams + 1 + info.numIndices]!
let alts := args[info.numParams + 1 + info.numIndices + 1 : info.numParams + 1 + info.numIndices + 1 + info.numCtors]
let remaining := args[info.numParams + 1 + info.numIndices + 1 + info.numCtors :]
let propOnly := info.levelParams.length == us.length
let mut altNumParams := #[]
for ctor in info.ctors do
let .ctorInfo ctorInfo ← getConstInfo ctor | unreachable!
altNumParams := altNumParams.push ctorInfo.numFields
return some { declName, us, params, motive, indices, major, alts, remaining, propOnly, altNumParams }
/-- Convert `c` back to `Expr` -/
def CasesOnApp.toExpr (c : CasesOnApp) : Expr :=
mkAppN (mkAppN (mkApp (mkAppN (mkApp (mkAppN (mkConst c.declName c.us) c.params) c.motive) c.indices) c.major) c.alts) c.remaining
/--
Given a `casesOn` application `c` of the form
```
casesOn As (fun is x => motive[i, xs]) is major (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining
```
and an expression `e : B[is, major]`, construct the term
```
casesOn As (fun is x => B[is, x] → motive[i, xs]) is major (fun ys_1 (y : B[C_1[ys_1]]) => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n (y : B[C_n[ys_n]]) => (alt_n : motive (C_n[ys_n]) e remaining
```
We use `kabstract` to abstract the `is` and `major` from `B[is, major]`.
-/
def CasesOnApp.addArg (c : CasesOnApp) (arg : Expr) (checkIfRefined : Bool := false) : MetaM CasesOnApp := do
lambdaTelescope c.motive fun motiveArgs motiveBody => do
unless motiveArgs.size == c.indices.size + 1 do
throwError "failed to add argument to `casesOn` application, motive must be lambda expression with #{c.indices.size + 1} binders"
let argType ← inferType arg
let discrs := c.indices ++ #[c.major]
let mut argTypeAbst := argType
for motiveArg in motiveArgs.reverse, discr in discrs.reverse do
argTypeAbst := (← kabstract argTypeAbst discr).instantiate1 motiveArg
let motiveBody ← mkArrow argTypeAbst motiveBody
let us ← if c.propOnly then pure c.us else pure ((← getLevel motiveBody) :: c.us.tail!)
let motive ← mkLambdaFVars motiveArgs motiveBody
let remaining := #[arg] ++ c.remaining
let aux := mkAppN (mkConst c.declName us) c.params
let aux := mkApp aux motive
let aux := mkAppN aux discrs
check aux
unless (← isTypeCorrect aux) do
throwError "failed to add argument to `casesOn` application, type error when constructing the new motive{indentExpr aux}"
let auxType ← inferType aux
let alts ← updateAlts argType auxType
return { c with us, motive, alts, remaining }
where
updateAlts (argType : Expr) (auxType : Expr) : MetaM (Array Expr) := do
let mut auxType := auxType
let mut altsNew := #[]
let mut refined := false
for alt in c.alts, numParams in c.altNumParams do
auxType ← whnfD auxType
match auxType with
| .forallE _ d b _ =>
let (altNew, refinedAt) ← forallBoundedTelescope d (some numParams) fun xs d => do
forallBoundedTelescope d (some 1) fun x _ => do
let alt := alt.beta xs
let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative
if checkIfRefined then
return (← mkLambdaFVars xs alt, !(← isDefEq argType (← inferType x[0]!)))
else
return (← mkLambdaFVars xs alt, true)
if refinedAt then
refined := true
auxType := b.instantiate1 altNew
altsNew := altsNew.push altNew
| _ => throwError "unexpected type at `casesOnAddArg`"
unless refined do
throwError "failed to add argument to `casesOn` application, argument type was not refined by `casesOn`"
return altsNew
/-- Similar `CasesOnApp.addArg`, but returns `none` on failure. -/
def CasesOnApp.addArg? (c : CasesOnApp) (arg : Expr) (checkIfRefined : Bool := false) : MetaM (Option CasesOnApp) :=
try
return some (← c.addArg arg checkIfRefined)
catch _ =>
return none
end Lean.Meta
|
4b6b43b6fc7b5cd7388aec1e9fc7638ef0d2127e | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world10/level5.lean | 0c090d2378aad627d12604a510e14da759ce56aa | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/natural_number_game | 05c39e1586408cfb563d1a12e1085a90726ab655 | f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd | refs/heads/master | 1,688,570,964,990 | 1,636,908,242,000 | 1,636,908,242,000 | 195,403,790 | 277 | 84 | Apache-2.0 | 1,694,547,955,000 | 1,562,328,792,000 | Lean | UTF-8 | Lean | false | false | 618 | lean | import game.world10.level4 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 5: `le_trans`
Another straightforward one.
-/
/- Lemma
≤ is transitive. In other words, if $a\leq b$ and $b\leq c$ then $a\leq c$.
-/
theorem le_trans (a b c : mynat) (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
begin [nat_num_game]
cases hab with d hd,
cases hbc with e he,
use (d + e),
rw ←add_assoc,
rw ←hd,
assumption,
end
/-
Congratulations -- you just got a collectible. You proved that the
natural numbers are a preorder.
-/
instance : preorder mynat := by structure_helper
end mynat -- hide
|
199d53e20525db724e856e52c3796f7cae856b34 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/char_p/basic.lean | d61b127560e052b00487ad61ee3cc92437e624f3 | [
"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 | 15,201 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kenny Lau, Joey van Langen, Casper Putz
-/
import data.fintype.basic
import data.nat.choose
import data.int.modeq
import algebra.module.basic
import algebra.iterate_hom
import group_theory.order_of_element
import algebra.group.type_tags
/-!
# Characteristic of semirings
-/
universes u v
/-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/
class char_p (α : Type u) [semiring α] (p : ℕ) : Prop :=
(cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 :=
(char_p.cast_eq_zero_iff α p p).2 (dvd_refl p)
@[simp] lemma char_p.cast_card_eq_zero (R : Type*) [ring R] [fintype R] :
(fintype.card R : R) = 0 :=
begin
have : fintype.card R •ℕ (1 : R) = 0 :=
@pow_card_eq_one (multiplicative R) _ _ (multiplicative.of_add 1),
simpa only [mul_one, nsmul_eq_mul]
end
lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) :
(a : R) = 0 ↔ (p:ℤ) ∣ a :=
begin
rcases lt_trichotomy a 0 with h|rfl|h,
{ rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg],
lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] },
{ simp only [int.cast_zero, eq_self_iff_true, dvd_zero] },
{ lift a to ℕ using (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }
end
lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = (b : R) ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p :=
by letI := classical.dec_eq α; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec
(not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p :=
let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩
theorem char_p.congr {R : Type u} [semiring R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) :
char_p R p :=
h ▸ hq
/-- Noncomputable function that outputs the unique characteristic of a semiring. -/
noncomputable def ring_char (α : Type u) [semiring α] : ℕ :=
classical.some (char_p.exists_unique α)
namespace ring_char
variables (R : Type u) [semiring R]
theorem spec : ∀ x:ℕ, (x:R) = 0 ↔ ring_char R ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique R)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff R (ring_char R)
theorem eq {p : ℕ} (C : char_p R p) : p = ring_char R :=
(classical.some_spec (char_p.exists_unique R)).2 p C
instance char_p : char_p R (ring_char R) :=
⟨spec R⟩
variables {R}
theorem of_eq {p : ℕ} (h : ring_char R = p) : char_p R p :=
char_p.congr (ring_char R) h
theorem eq_iff {p : ℕ} : ring_char R = p ↔ char_p R p :=
⟨of_eq, eq.symm ∘ eq R⟩
theorem dvd {x : ℕ} (hx : (x : R) = 0) : ring_char R ∣ x :=
(spec R x).1 hx
end ring_char
theorem add_pow_char_of_commute (R : Type u) [semiring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) (h : commute x y) :
(x + y)^p = x^p + y^p :=
begin
rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self],
rw [nat.cast_one, mul_one, mul_one], congr' 1,
convert finset.sum_eq_single 0 _ _, { simp },
swap, { intro h1, contrapose! h1, rw finset.mem_range, apply nat.prime.pos, assumption },
intros b h1 h2,
suffices : (p.choose b : R) = 0, { rw this, simp },
rw char_p.cast_eq_zero_iff R p,
refine nat.prime.dvd_choose_self (pos_iff_ne_zero.mpr h2) _ (by assumption),
rwa ← finset.mem_range
end
theorem add_pow_char_pow_of_commute (R : Type u) [semiring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) (h : commute x y) :
(x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) :=
begin
induction n, { simp, },
rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih],
apply add_pow_char_of_commute, apply commute.pow_pow h,
end
theorem sub_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) (h : commute x y) :
(x - y)^p = x^p - y^p :=
begin
rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)],
simp, repeat {apply_instance},
end
theorem sub_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) (h : commute x y) :
(x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) :=
begin
induction n, { simp, },
rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih],
apply sub_pow_char_of_commute, apply commute.pow_pow h,
end
theorem add_pow_char (α : Type u) [comm_semiring α] {p : ℕ} [fact p.prime]
[char_p α p] (x y : α) : (x + y)^p = x^p + y^p :=
add_pow_char_of_commute _ _ _ (commute.all _ _)
theorem add_pow_char_pow (R : Type u) [comm_semiring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) :
(x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) :=
add_pow_char_pow_of_commute _ _ _ (commute.all _ _)
theorem sub_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime]
[char_p α p] (x y : α) : (x - y)^p = x^p - y^p :=
sub_pow_char_of_commute _ _ _ (commute.all _ _)
theorem sub_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) :
(x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) :=
sub_pow_char_pow_of_commute _ _ _ (commute.all _ _)
lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = b ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] :
(-1 : R) ≠ (1 : R) :=
begin
suffices : (2 : R) ≠ 0,
{ symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this },
assume h,
rw [show (2 : R) = (2 : ℕ), by norm_cast] at h,
have := (char_p.cast_eq_zero_iff R p 2).mp h,
have := nat.le_of_dvd dec_trivial this,
rw fact at *, linarith,
end
lemma ring_hom.char_p_iff_char_p {K L : Type*} [field K] [field L] (f : K →+* L) (p : ℕ) :
char_p K p ↔ char_p L p :=
begin
split;
{ introI _c, constructor, intro n,
rw [← @char_p.cast_eq_zero_iff _ _ p _c n, ← f.injective.eq_iff, f.map_nat_cast, f.map_zero] }
end
section frobenius
section comm_semiring
variables (R : Type u) [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S)
(p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R)
/-- The frobenius map that sends x to x^p -/
def frobenius : R →+* R :=
{ to_fun := λ x, x^p,
map_one' := one_pow p,
map_mul' := λ x y, mul_pow x y p,
map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt),
map_add' := add_pow_char R }
variable {R}
theorem frobenius_def : frobenius R p x = x ^ p := rfl
theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n :=
begin
induction n, {simp},
rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih]
end
theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y :=
(frobenius R p).map_mul x y
theorem frobenius_one : frobenius R p 1 = 1 := one_pow _
variable {R}
theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) :=
f.map_pow x p
theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) :=
g.map_pow x p
theorem monoid_hom.map_iterate_frobenius (n : ℕ) :
f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) :=
function.semiconj.iterate_right (f.map_frobenius p) n x
theorem ring_hom.map_iterate_frobenius (n : ℕ) :
g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) :=
g.to_monoid_hom.map_iterate_frobenius p x n
theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
variable (R)
theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero
theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y :=
(frobenius R p).map_add x y
theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n
end comm_semiring
section comm_ring
variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S)
(p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R)
theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x
theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y :=
(frobenius R p).map_sub x y
end comm_ring
end frobenius
theorem frobenius_inj (α : Type u) [comm_ring α] [no_zero_divisors α]
(p : ℕ) [fact p.prime] [char_p α p] :
function.injective (frobenius α p) :=
λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H }
namespace char_p
section
variables (α : Type u) [ring α]
lemma char_p_to_char_zero [char_p α 0] : char_zero α :=
char_zero_of_inj_zero $
λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0)
lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) :=
calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div]
... = ↑(k % p) : by simp[cast_eq_zero]
theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 :=
assume h : p = 0,
have char_zero α := @char_p_to_char_zero α _ (h ▸ hc),
absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe)
end
section integral_domain
open nat
variables (α : Type u) [integral_domain α]
theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 :=
assume hp : p = 1,
have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p),
absurd this one_ne_zero
theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p α p] (hp : 2 ≤ p) : nat.prime p :=
suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩,
assume (d : ℕ) (hdvd : ∃ e, p = d * e),
let ⟨e, hmul⟩ := hdvd in
have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p),
have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this),
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this)
(assume hd : (d : α) = 0,
have p ∣ d, from (cast_eq_zero_iff α p d).mp hd,
show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this))
(assume he : (e : α) = 0,
have p ∣ e, from (cast_eq_zero_iff α p e).mp he,
have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul),
have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›,
have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1),
have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul,
show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this))
theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 :=
match p, hc with
| 0, _ := or.inr rfl
| 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc)
| (m+2), hc := or.inl (@char_is_prime_of_two_le α _ (m+2) hc (nat.le_add_left 2 m))
end
lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime :=
(char_p.char_is_prime_or_zero α _).resolve_right (pos_iff_ne_zero.1 h)
theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime :=
or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p)
end integral_domain
section char_one
variables {R : Type*}
@[priority 100] -- see Note [lower instance priority]
instance [semiring R] [char_p R 1] : subsingleton R :=
subsingleton.intro $
suffices ∀ (r : R), r = 0,
from assume a b, show a = b, by rw [this a, this b],
assume r,
calc r = 1 * r : by rw one_mul
... = (1 : ℕ) * r : by rw nat.cast_one
... = 0 * r : by rw char_p.cast_eq_zero
... = 0 : by rw zero_mul
lemma false_of_nontrivial_of_char_one [semiring R] [nontrivial R] [char_p R 1] : false :=
false_of_nontrivial_of_subsingleton R
lemma ring_char_ne_one [semiring R] [nontrivial R] : ring_char R ≠ 1 :=
by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], }
lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) {R : Type*} [semiring R] [hr : char_p R v] :
nontrivial R :=
⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩
end char_one
end char_p
section
variables (n : ℕ) (R : Type*) [comm_ring R] [fintype R]
lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) :
char_p R n :=
{ cast_eq_zero_iff :=
begin
have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] },
intro k,
split,
{ intro h,
rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h,
rw nat.dvd_iff_mod_eq_zero,
apply hR _ (nat.mod_lt _ _) h,
rw [← hn, gt, fintype.card_pos_iff],
exact ⟨0⟩, },
{ rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] }
end }
lemma char_p_of_prime_pow_injective (p : ℕ) [hp : fact p.prime] (n : ℕ)
(hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) :
char_p R (p ^ n) :=
begin
obtain ⟨c, hc⟩ := char_p.exists R, resetI,
have hcpn : c ∣ p ^ n,
{ rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], },
obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp at hcpn,
obtain rfl : i = n,
{ apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] },
rwa ← hc
end
end
|
524a73111a366a7808c81af114ecba7436bee9fc | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/calculus/fderiv.lean | dc31bbd55f581fd4dceb62baa45a9981d7951152 | [
"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 | 130,235 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov
-/
import analysis.asymptotics.asymptotic_equivalent
import analysis.calculus.tangent_cone
import analysis.normed_space.bounded_linear_maps
import analysis.normed_space.units
/-!
# The Fréchet derivative
Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a
continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then
`has_fderiv_within_at f f' s x`
says that `f` has derivative `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`has_fderiv_at f f' x := has_fderiv_within_at f f' x univ`
Finally,
`has_strict_fderiv_at f f' x`
means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability,
i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse
function theorem, and is defined here only to avoid proving theorems like
`is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for
`has_strict_fderiv_at`.
## Main results
In addition to the definition and basic properties of the derivative, this file contains the
usual formulas (and existence assertions) for the derivative of
* constants
* the identity
* bounded linear maps
* bounded bilinear maps
* sum of two functions
* sum of finitely many functions
* multiplication of a function by a scalar constant
* negative of a function
* subtraction of two functions
* multiplication of a function by a scalar function
* multiplication of two scalar functions
* composition of functions (the chain rule)
* inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying
a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are
translated to this more elementary point of view on the derivative in the file `deriv.lean`. The
derivative of polynomials is handled there, as it is naturally one-dimensional.
The simplifier is set up to prove automatically that some functions are differentiable, or
differentiable at a point (but not differentiable on a set or within a set at a point, as checking
automatically that the good domains are mapped one to the other when using composition is not
something the simplifier can easily do). This means that one can write
`example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`.
If there are divisions, one needs to supply to the simplifier proofs that the denominators do
not vanish, as in
```lean
example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x :=
by simp [h]
```
Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be
differentiable, in `analysis.special_functions.trigonometric`.
The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general
complicated multidimensional linear maps), but it will compute one-dimensional derivatives,
see `deriv.lean`.
## Implementation details
The derivative is defined in terms of the `is_o` relation, but also
characterized in terms of the `tendsto` relation.
We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field,
`f` the function to be differentiated, `x` the point at which the derivative is asserted to exist,
and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`,
`differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative.
To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x`
for some choice of a derivative if it exists, and the zero function otherwise. This choice only
behaves well along sets for which the derivative is unique, i.e., those for which the tangent
directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and
`unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed
they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular
for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very
beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever.
To make sure that the simplifier can prove automatically that functions are differentiable, we tag
many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable
functions is differentiable, as well as their product, their cartesian product, and so on. A notable
exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are
differentiable, then their composition also is: `simp` would always be able to match this lemma,
by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`),
we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding
some boilerplate lemmas, but these can also be useful in their own right.
Tests for this ability of the simplifier (with more examples) are provided in
`tests/differentiable.lean`.
## Tags
derivative, differentiable, Fréchet, calculus
-/
open filter asymptotics continuous_linear_map set metric
open_locale topological_space classical nnreal filter asymptotics ennreal
noncomputable theory
section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space 𝕜 G]
variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G']
/-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition
is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion
of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to
the notion of Fréchet derivative along the set `s`. -/
def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) :=
is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L
/-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/
def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) :=
has_fderiv_at_filter f f' x (𝓝[s] x)
/-- A function `f` has the continuous linear map `f'` as derivative at `x` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/
def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
has_fderiv_at_filter f f' x (𝓝 x)
/-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability*
if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required,
e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly
differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/
def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x))
variables (𝕜)
/-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative
there (possibly non-unique). -/
def differentiable_within_at (f : E → F) (s : set E) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x
/-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly
non-unique). -/
def differentiable_at (f : E → F) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_at f f' x
/-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative.
Otherwise, it is set to `0`. -/
def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0
/-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is
set to `0`. -/
def fderiv (f : E → F) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_at f f' x then classical.some h else 0
/-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/
def differentiable_on (f : E → F) (s : set E) :=
∀x ∈ s, differentiable_within_at 𝕜 f s x
/-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/
def differentiable (f : E → F) :=
∀x, differentiable_at 𝕜 f x
variables {𝕜}
variables {f f₀ f₁ g : E → F}
variables {f' f₀' f₁' g' : E →L[𝕜] F}
variables (e : E →L[𝕜] F)
variables {x : E}
variables {s t : set E}
variables {L L₁ L₂ : filter E}
lemma fderiv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 :=
have ¬ ∃ f', has_fderiv_within_at f f' s x, from h,
by simp [fderiv_within, this]
lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 :=
have ¬ ∃ f', has_fderiv_at f f' x, from h,
by simp [fderiv, this]
section derivative_uniqueness
/- In this section, we discuss the uniqueness of the derivative.
We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the
uniqueness of the derivative. -/
/-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f',
i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity
and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses
this fact, for functions having a derivative within a set. Its specific formulation is useful for
tangent cone related discussions. -/
theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α)
{c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s)
(clim : tendsto (λ n, ∥c n∥) l at_top)
(cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) :
tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) :=
begin
have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x),
{ conv in (𝓝[s] x) { rw ← add_zero x },
rw [nhds_within, tendsto_inf],
split,
{ apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) },
{ rwa tendsto_principal } },
have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h,
have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l :=
this.comp_tendsto tendsto_arg,
have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'],
have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l :=
(is_O_refl c l).smul_is_o this,
have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l :=
this.trans_is_O (is_O_one_of_tendsto ℝ cdlim),
have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) :=
(is_o_one_iff ℝ).1 this,
have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) :=
tendsto.comp f'.cont.continuous_at cdlim,
have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
l (𝓝 (0 + f' v)) :=
L1.add L2,
have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
= (λn, c n • (f (x + d n) - f x)),
by { ext n, simp [smul_add, smul_sub] },
rwa [this, zero_add] at L3
end
/-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the
tangent cone to `s` at `x` -/
theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at f f₁' s x) :
eq_on f' f₁' (tangent_cone_at 𝕜 s x) :=
λ y ⟨c, d, dtop, clim, cdlim⟩,
tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim)
/-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x)
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
continuous_linear_map.ext_on H.1 (hf.unique_on hg)
theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
(H x hx).eq h h₁
end derivative_uniqueness
section fderiv_properties
/-! ### Basic properties of the derivative -/
theorem has_fderiv_at_filter_iff_tendsto :
has_fderiv_at_filter f f' x L ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) :=
have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx',
by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp },
begin
unfold has_fderiv_at_filter,
rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h],
exact tendsto_congr (λ _, div_eq_inv_mul),
end
theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔
is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map],
simp [(∘)]
end
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/
lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C :=
begin
refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _),
exact add_nonneg C.coe_nonneg ε0.le,
have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs',
filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys,
have := hlip.norm_sub_le hys (mem_of_mem_nhds hs), rw add_sub_cancel' at this,
calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _
... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy
... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm
end
theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_fderiv_at_filter f f' x L₁ :=
h.mono hst
theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) :
has_fderiv_within_at f f' s x :=
h.mono (nhds_within_mono _ hst)
theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) :
has_fderiv_at_filter f f' x L :=
h.mono hL
theorem has_fderiv_at.has_fderiv_within_at
(h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x :=
h.has_fderiv_at_filter inf_le_left
lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
⟨f', h⟩
lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x :=
⟨f', h⟩
@[simp] lemma has_fderiv_within_at_univ :
has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x :=
by { simp only [has_fderiv_within_at, nhds_within_univ], refl }
lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) :
is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) :=
hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _)
lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
h.is_O.congr_of_sub.2 (f'.is_O_sub _ _)
protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) :
has_fderiv_at f f' x :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff],
exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc))
end
protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) :
differentiable_at 𝕜 f x :=
hf.has_fderiv_at.differentiable_at
/-- If `f` is strictly differentiable at `x` with derivative `f'` and `K > ∥f'∥₊`, then `f` is
`K`-Lipschitz in a neighborhood of `x`. -/
lemma has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt (hf : has_strict_fderiv_at f f' x)
(K : ℝ≥0) (hK : ∥f'∥₊ < K) : ∃ s ∈ 𝓝 x, lipschitz_on_with K f s :=
begin
have := hf.add_is_O_with (f'.is_O_with_comp _ _) hK,
simp only [sub_add_cancel, is_O_with] at this,
rcases exists_nhds_square this with ⟨U, Uo, xU, hU⟩,
exact ⟨U, Uo.mem_nhds xU, lipschitz_on_with_iff_norm_sub_le.2 $
λ x hx y hy, hU (mk_mem_prod hx hy)⟩
end
/-- If `f` is strictly differentiable at `x` with derivative `f'`, then `f` is Lipschitz in a
neighborhood of `x`. See also `has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt` for a
more precise statement. -/
lemma has_strict_fderiv_at.exists_lipschitz_on_with (hf : has_strict_fderiv_at f f' x) :
∃ K (s ∈ 𝓝 x), lipschitz_on_with K f s :=
(no_top _).imp hf.exists_lipschitz_on_with_of_nnnorm_lt
/-- Directional derivative agrees with `has_fderiv`. -/
lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜}
{l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) :
tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) :=
begin
refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem' (λ _, trivial)) hc _,
assume U hU,
refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _),
convert mem_of_mem_nhds hU,
dsimp only,
rw [← mul_smul, mul_inv_cancel hy, one_smul]
end
theorem has_fderiv_at.unique
(h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' :=
begin
rw ← has_fderiv_within_at_univ at h₀ h₁,
exact unique_diff_within_at_univ.eq h₀ h₁
end
lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict'' s h]
lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict' s h]
lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x)
(ht : has_fderiv_within_at f f' t x) :
has_fderiv_within_at f f' (s ∪ t) x :=
begin
simp only [has_fderiv_within_at, nhds_within_union],
exact hs.join ht,
end
lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x :=
(has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_fderiv_at f f' x :=
by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h
lemma differentiable_within_at.differentiable_at
(h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x :=
h.imp (λ f' hf', hf'.has_fderiv_at hs)
lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x :=
begin
dunfold fderiv_within,
dunfold differentiable_within_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
begin
dunfold fderiv,
dunfold differentiable_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_on.has_fderiv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
((h x (mem_of_mem_nhds hs)).differentiable_at hs).has_fderiv_at
lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' :=
by { ext, rw h.unique h.differentiable_at.has_fderiv_at }
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`.
Version using `fderiv`. -/
lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C :=
hf.has_fderiv_at.le_of_lip hs hlip
lemma has_fderiv_within_at.fderiv_within
(h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = f' :=
(hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm
/-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`,
as this statement is empty. -/
lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) :
has_fderiv_within_at f f' s x :=
begin
simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h,
simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with],
end
lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) :
differentiable_within_at 𝕜 f s x :=
begin
rcases h with ⟨f', hf'⟩,
exact ⟨f', hf'.mono st⟩
end
lemma differentiable_within_at_univ :
differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x :=
by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at]
lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict' s ht]
lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict'' s ht]
lemma differentiable_at.differentiable_within_at
(h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x :=
(differentiable_within_at_univ.2 h).mono (subset_univ _)
lemma differentiable.differentiable_at (h : differentiable 𝕜 f) :
differentiable_at 𝕜 f x :=
h x
lemma differentiable_at.fderiv_within
(h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact h.has_fderiv_at.has_fderiv_within_at
end
lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) :
differentiable_on 𝕜 f s :=
λx hx, (h x (st hx)).mono st
lemma differentiable_on_univ :
differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f :=
by { simp [differentiable_on, differentiable_within_at_univ], refl }
lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s :=
(differentiable_on_univ.2 h).mono (subset_univ _)
lemma differentiable_on_of_locally_differentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩)
end
lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht
@[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f :=
begin
ext x : 1,
by_cases h : differentiable_at 𝕜 f x,
{ apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ,
rw has_fderiv_within_at_univ,
apply h.has_fderiv_at },
{ have : ¬ differentiable_within_at 𝕜 f univ x,
by contrapose! h; rwa ← differentiable_within_at_univ,
rw [fderiv_zero_of_not_differentiable_at h,
fderiv_within_zero_of_not_differentiable_within_at this] }
end
lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x :=
begin
by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x,
{ apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h),
apply hs.inter ht },
{ have : ¬ differentiable_within_at 𝕜 f s x,
by contrapose! h; rw differentiable_within_at_inter; assumption,
rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at this] }
end
lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
have : s = univ ∩ s, by simp only [univ_inter],
rw [this, ← fderiv_within_univ],
exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _))
end
lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
fderiv_within_of_mem_nhds (is_open.mem_nhds hs hx)
lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
rw ← fderiv_within_univ,
exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at
end
lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} :
fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨
(0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x :=
begin
split,
{ intro hfx,
by_cases hx : differentiable_at 𝕜 f x,
{ exact or.inl ⟨hx, hfx⟩ },
{ rw [fderiv_zero_of_not_differentiable_at hx] at hfx,
exact or.inr ⟨hfx, hx⟩ } },
{ rintro (⟨hf, hf'⟩|⟨h₀, hx⟩),
{ exact hf' },
{ rwa [fderiv_zero_of_not_differentiable_at hx] } }
end
end fderiv_properties
section continuous
/-! ### Deducing continuity from differentiability -/
theorem has_fderiv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
begin
have : tendsto (λ x', f x' - f x) L (𝓝 0),
{ refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL),
rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds },
have := tendsto.add this tendsto_const_nhds,
rw zero_add (f x) at this,
exact this.congr (by simp)
end
theorem has_fderiv_within_at.continuous_within_at
(h : has_fderiv_within_at f f' s x) : continuous_within_at f s x :=
has_fderiv_at_filter.tendsto_nhds inf_le_left h
theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) :
continuous_at f x :=
has_fderiv_at_filter.tendsto_nhds (le_refl _) h
lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) :
continuous_within_at f s x :=
let ⟨f', hf'⟩ := h in hf'.continuous_within_at
lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x :=
let ⟨f', hf'⟩ := h in hf'.continuous_at
lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) :
continuous_at f x :=
hf.has_fderiv_at.continuous_at
lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F}
(hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) :
is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) :=
((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr
(λ _, rfl) (λ _, sub_add_cancel _ _)
lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F}
(hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) :
is_O (λ x', x' - x) (λ x', f x' - f x) L :=
((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr
(λ _, rfl) (λ _, sub_add_cancel _ _)
end continuous
section congr
/-! ### congr properties of the derivative -/
theorem filter.eventually_eq.has_strict_fderiv_at_iff
(h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) :
has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x :=
begin
refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl),
rintros p ⟨hp₁, hp₂⟩,
simp only [*]
end
theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x)
(h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x :=
(h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h
theorem filter.eventually_eq.has_fderiv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl)
lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
(hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h
lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x :=
has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_of_right ht) hx
lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_fderiv_within_at.congr' (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : x ∈ s) : has_fderiv_within_at f₁ f' s x :=
h.congr hs (hs x hx)
lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _)
lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at
lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
differentiable_within_at.congr_mono h ht hx (subset.refl _)
lemma differentiable_within_at.congr_of_eventually_eq
(h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f)
(hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
(h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at
lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s :=
λ x hx, (h x hx).congr h' (h' x hx)
lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s :=
⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm),
λ h, differentiable_on.congr h h'⟩
lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) :
differentiable_at 𝕜 f₁ x :=
has_fderiv_at.differentiable_at
(has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_mem_nhds hL : _))
lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x)
(hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) :
fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt
lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
if h : differentiable_within_at 𝕜 f s x
then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs
else
have h' : ¬ differentiable_within_at 𝕜 f₁ s x,
from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h,
by rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at h']
lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
begin
apply filter.eventually_eq.fderiv_within_eq hs _ hx,
apply mem_of_superset self_mem_nhds_within,
exact hL
end
lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) :
fderiv 𝕜 f₁ x = fderiv 𝕜 f x :=
begin
have A : f₁ x = f x := hL.eq_of_nhds,
rw [← fderiv_within_univ, ← fderiv_within_univ],
rw ← nhds_within_univ at hL,
exact hL.fderiv_within_eq unique_diff_within_at_univ A
end
protected lemma filter.eventually_eq.fderiv (h : f₁ =ᶠ[𝓝 x] f) :
fderiv 𝕜 f₁ =ᶠ[𝓝 x] fderiv 𝕜 f :=
h.eventually_eq_nhds.mono $ λ x h, h.fderiv_eq
end congr
section id
/-! ### Derivative of the identity -/
theorem has_strict_fderiv_at_id (x : E) :
has_strict_fderiv_at id (id 𝕜 E) x :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id 𝕜 E) x L :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_within_at_id (x : E) (s : set E) :
has_fderiv_within_at id (id 𝕜 E) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x :=
has_fderiv_at_filter_id _ _
@[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x :=
(has_fderiv_at_id x).differentiable_at
@[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x :=
(has_fderiv_at_id x).differentiable_at
lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x :=
differentiable_at_id.differentiable_within_at
@[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) :=
λx, differentiable_at_id
@[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on 𝕜 id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
@[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E :=
fderiv_id
lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 id s x = id 𝕜 E :=
begin
rw differentiable_at.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E :=
fderiv_within_id hxs
end id
section const
/-! ### derivative of a constant function -/
theorem has_strict_fderiv_at_const (c : F) (x : E) :
has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) :
has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) :
has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x :=
has_fderiv_at_filter_const _ _ _
theorem has_fderiv_at_const (c : F) (x : E) :
has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x :=
has_fderiv_at_filter_const _ _ _
@[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x :=
⟨0, has_fderiv_at_const c x⟩
lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x :=
differentiable_at.differentiable_within_at (differentiable_at_const _)
lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
@[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 :=
by { ext m, rw fderiv_const_apply, refl }
lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, c) s x = 0 :=
begin
rw differentiable_at.fderiv_within (differentiable_at_const _) hxs,
exact fderiv_const_apply _
end
@[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) :=
λx, differentiable_at_const _
lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s :=
(differentiable_const _).differentiable_on
lemma has_fderiv_at_of_subsingleton {R X Y : Type*} [nondiscrete_normed_field R]
[normed_group X] [normed_group Y] [normed_space R X] [normed_space R Y] [h : subsingleton X]
(f : X → Y) (x : X) :
has_fderiv_at f (0 : X →L[R] Y) x :=
begin
rw subsingleton_iff at h,
have key : function.const X (f 0) = f := by ext x'; rw h x' 0,
exact key ▸ (has_fderiv_at_const (f 0) _),
end
end const
section continuous_linear_map
/-!
### Continuous linear maps
There are currently two variants of these in mathlib, the bundled version
(named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a
predicate `is_bounded_linear_map`). We give statements for both versions. -/
protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} :
has_strict_fderiv_at e e x :=
(is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self]
protected lemma continuous_linear_map.has_fderiv_at_filter :
has_fderiv_at_filter e e x L :=
(is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self]
protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x :=
e.has_fderiv_at_filter
protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x :=
e.has_fderiv_at_filter
@[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x :=
e.has_fderiv_at.differentiable_at
protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x :=
e.differentiable_at.differentiable_within_at
@[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e :=
e.has_fderiv_at.fderiv
protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 e s x = e :=
begin
rw differentiable_at.fderiv_within e.differentiable_at hxs,
exact e.fderiv
end
@[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e :=
λx, e.differentiable_at
protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s :=
e.differentiable.differentiable_on
lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at_filter f h.to_continuous_linear_map x L :=
h.to_continuous_linear_map.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_within_at f h.to_continuous_linear_map s x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at f h.to_continuous_linear_map x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) :
fderiv 𝕜 f x = h.to_continuous_linear_map :=
has_fderiv_at.fderiv (h.has_fderiv_at)
lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f)
(hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map :=
begin
rw differentiable_at.fderiv_within h.differentiable_at hxs,
exact h.fderiv
end
lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) :
differentiable 𝕜 f :=
λx, h.differentiable_at
lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) :
differentiable_on 𝕜 f s :=
h.differentiable.differentiable_on
end continuous_linear_map
section composition
/-!
### Derivative of the composition of two functions
For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in
let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in
by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp }
/- A readable version of the previous theorem,
a general form of the chain rule. -/
example {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
begin
unfold has_fderiv_at_filter at hg,
have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L,
from hg.comp_tendsto (le_refl _),
have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L,
from this.trans_is_O hf.is_O_sub,
have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L,
from hf,
have : is_O
(λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L,
from g'.is_O_comp _ _,
have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L,
from this.trans_is_o eq₂,
have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L,
by { refine this.congr_left _, simp},
exact eq₁.triangle eq₃
end
theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F}
(hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : s ⊆ f ⁻¹' t) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf,
calc map f (𝓝[s] x)
≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image
... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst)
end
/-- The chain rule. -/
theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (g ∘ f) (g'.comp f') x :=
(hg.mono hf.continuous_at).comp x hf
theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
rw ← has_fderiv_within_at_univ at hg,
exact has_fderiv_within_at.comp x hg hf subset_preimage_univ
end
lemma differentiable_within_at.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x :=
begin
rcases hf with ⟨f', hf'⟩,
rcases hg with ⟨g', hg'⟩,
exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩
end
lemma differentiable_within_at.comp' {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x :=
hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma differentiable_at.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (g ∘ f) x :=
(hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at
lemma differentiable_at.comp_differentiable_within_at {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (g ∘ f) s x :=
(differentiable_within_at_univ.2 hg).comp x hf (by simp)
lemma fderiv_within.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h
end
lemma fderiv.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) :=
begin
apply has_fderiv_at.fderiv,
exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at
end
lemma fderiv.comp_fderiv_within {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at)
end
lemma differentiable_on.comp {g : F → G} {t : set F}
(hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) :
differentiable_on 𝕜 (g ∘ f) s :=
λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st
lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (g ∘ f) :=
λx, differentiable_at.comp x (hg (f x)) (hf x)
lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g)
(hf : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (g ∘ f) s :=
(differentiable_on_univ.2 hg).comp hf (by simp)
/-- The chain rule for derivatives in the sense of strict differentiability. -/
protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x :=
((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $
by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf
protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) :
differentiable 𝕜 (f^[n]) :=
nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf)
protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s)
(hs : maps_to f s s) (n : ℕ) :
differentiable_on 𝕜 (f^[n]) s :=
nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs)
variable {x}
protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_fderiv_at_filter (f^[n]) (f'^n) x L :=
begin
induction n with n ihn,
{ exact has_fderiv_at_filter_id x L },
{ change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L,
rw [pow_succ'],
refine has_fderiv_at_filter.comp x _ hf,
rw hx,
exact ihn.mono hL }
end
protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) :
has_fderiv_at (f^[n]) (f'^n) x :=
begin
refine hf.iterate _ hx n,
convert hf.continuous_at,
exact hx.symm
end
protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_fderiv_within_at (f^[n]) (f'^n) s x :=
begin
refine hf.iterate _ hx n,
convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩,
exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right]
end
protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_fderiv_at (f^[n]) (f'^n) x :=
begin
induction n with n ihn,
{ exact has_strict_fderiv_at_id x },
{ change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x,
rw [pow_succ'],
refine has_strict_fderiv_at.comp x _ hf,
rwa hx }
end
protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x)
(hx : f x = x) (n : ℕ) :
differentiable_at 𝕜 (f^[n]) x :=
exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at
protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x)
(hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
differentiable_within_at 𝕜 (f^[n]) s x :=
exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at
end composition
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
section prod
variables {f₂ : E → G} {f₂' : E →L[𝕜] G}
protected lemma has_strict_fderiv_at.prod
(hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x :=
hf₁.prod_left hf₂
lemma has_fderiv_at_filter.prod
(hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L :=
hf₁.prod_left hf₂
lemma has_fderiv_within_at.prod
(hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x :=
hf₁.prod hf₂
lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x :=
hf₁.prod hf₂
lemma differentiable_within_at.prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x :=
(hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at
@[simp]
lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at
lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s :=
λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx)
@[simp]
lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) :
differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) :=
λ x, differentiable_at.prod (hf₁ x) (hf₂ x)
lemma differentiable_at.fderiv_prod
(hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv
lemma differentiable_at.fderiv_within_prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x)
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x =
(fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at
end
end prod
section fst
variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F}
lemma has_strict_fderiv_at_fst : has_strict_fderiv_at (@prod.fst E F) (fst 𝕜 E F) p :=
(fst 𝕜 E F).has_strict_fderiv_at
protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x :=
has_strict_fderiv_at_fst.comp x h
lemma has_fderiv_at_filter_fst {L : filter (E × F)} :
has_fderiv_at_filter (@prod.fst E F) (fst 𝕜 E F) p L :=
(fst 𝕜 E F).has_fderiv_at_filter
protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L :=
has_fderiv_at_filter_fst.comp x h
lemma has_fderiv_at_fst : has_fderiv_at (@prod.fst E F) (fst 𝕜 E F) p :=
has_fderiv_at_filter_fst
protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x :=
h.fst
lemma has_fderiv_within_at_fst {s : set (E × F)} :
has_fderiv_within_at (@prod.fst E F) (fst 𝕜 E F) s p :=
has_fderiv_at_filter_fst
protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x :=
h.fst
lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p :=
has_fderiv_at_fst.differentiable_at
@[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λ x, (f₂ x).1) x :=
differentiable_at_fst.comp x h
lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) :=
λ x, differentiable_at_fst
@[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) :
differentiable 𝕜 (λ x, (f₂ x).1) :=
differentiable_fst.comp h
lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p :=
differentiable_at_fst.differentiable_within_at
protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x :=
differentiable_at_fst.comp_differentiable_within_at x h
lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s :=
differentiable_fst.differentiable_on
protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λ x, (f₂ x).1) s :=
differentiable_fst.comp_differentiable_on h
lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv
lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) :=
h.has_fderiv_at.fst.fderiv
lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) :
fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F :=
has_fderiv_within_at_fst.fderiv_within hs
lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) :
fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) :=
h.has_fderiv_within_at.fst.fderiv_within hs
end fst
section snd
variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F}
lemma has_strict_fderiv_at_snd : has_strict_fderiv_at (@prod.snd E F) (snd 𝕜 E F) p :=
(snd 𝕜 E F).has_strict_fderiv_at
protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x :=
has_strict_fderiv_at_snd.comp x h
lemma has_fderiv_at_filter_snd {L : filter (E × F)} :
has_fderiv_at_filter (@prod.snd E F) (snd 𝕜 E F) p L :=
(snd 𝕜 E F).has_fderiv_at_filter
protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L :=
has_fderiv_at_filter_snd.comp x h
lemma has_fderiv_at_snd : has_fderiv_at (@prod.snd E F) (snd 𝕜 E F) p :=
has_fderiv_at_filter_snd
protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x :=
h.snd
lemma has_fderiv_within_at_snd {s : set (E × F)} :
has_fderiv_within_at (@prod.snd E F) (snd 𝕜 E F) s p :=
has_fderiv_at_filter_snd
protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x :=
h.snd
lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p :=
has_fderiv_at_snd.differentiable_at
@[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λ x, (f₂ x).2) x :=
differentiable_at_snd.comp x h
lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) :=
λ x, differentiable_at_snd
@[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) :
differentiable 𝕜 (λ x, (f₂ x).2) :=
differentiable_snd.comp h
lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p :=
differentiable_at_snd.differentiable_within_at
protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x :=
differentiable_at_snd.comp_differentiable_within_at x h
lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s :=
differentiable_snd.differentiable_on
protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λ x, (f₂ x).2) s :=
differentiable_snd.comp_differentiable_on h
lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv
lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) :=
h.has_fderiv_at.snd.fderiv
lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) :
fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F :=
has_fderiv_within_at_snd.fderiv_within hs
lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) :
fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) :=
h.has_fderiv_within_at.snd.fderiv_within hs
end snd
section prod_map
variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G)
protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1)
(hf₂ : has_strict_fderiv_at f₂ f₂' p.2) :
has_strict_fderiv_at (prod.map f f₂) (f'.prod_map f₂') p :=
(hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd)
protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1)
(hf₂ : has_fderiv_at f₂ f₂' p.2) :
has_fderiv_at (prod.map f f₂) (f'.prod_map f₂') p :=
(hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd)
@[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1)
(hf₂ : differentiable_at 𝕜 f₂ p.2) :
differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p :=
(hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd)
end prod_map
end cartesian_product
section const_smul
variables {R : Type*} [semiring R] [module R F] [topological_space R] [smul_comm_class 𝕜 R F]
[has_continuous_smul R F]
/-! ### Derivative of a function multiplied by a constant -/
theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : R) :
has_strict_fderiv_at (λ x, c • f x) (c • f') x :=
(c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h
theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : R) :
has_fderiv_at_filter (λ x, c • f x) (c • f') x L :=
(c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h
theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : R) :
has_fderiv_within_at (λ x, c • f x) (c • f') s x :=
h.const_smul c
theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : R) :
has_fderiv_at (λ x, c • f x) (c • f') x :=
h.const_smul c
lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : R) :
differentiable_within_at 𝕜 (λy, c • f y) s x :=
(h.has_fderiv_within_at.const_smul c).differentiable_within_at
lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : R) :
differentiable_at 𝕜 (λy, c • f y) x :=
(h.has_fderiv_at.const_smul c).differentiable_at
lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : R) :
differentiable_on 𝕜 (λy, c • f y) s :=
λx hx, (h x hx).const_smul c
lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : R) :
differentiable 𝕜 (λy, c • f y) :=
λx, (h x).const_smul c
lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) (c : R) :
fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x :=
(h.has_fderiv_within_at.const_smul c).fderiv_within hxs
lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : R) :
fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x :=
(h.has_fderiv_at.const_smul c).fderiv
end const_smul
section add
/-! ### Derivative of the sum of two functions -/
theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x)
(hg : has_strict_fderiv_at g g' x) :
has_strict_fderiv_at (λ y, f y + g y) (f' + g') x :=
(hf.add hg).congr_left $ λ y, by simp; abel
theorem has_fderiv_at_filter.add
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L :=
(hf.add hg).congr_left $ λ _, by simp; abel
theorem has_fderiv_within_at.add
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_fderiv_at.add
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma differentiable_within_at.add
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y + g y) s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y + g y) x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at
lemma differentiable_on.add
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y + g y) s :=
λx hx, (hf x hx).add (hg x hx)
@[simp] lemma differentiable.add
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y + g y) :=
λx, (hf x).add (hg x)
lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ y, f y + c) f' x :=
add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _)
theorem has_fderiv_at_filter.add_const
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _)
theorem has_fderiv_within_at.add_const
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F):
has_fderiv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma differentiable_within_at.add_const
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, f y + c) s x :=
(hf.has_fderiv_within_at.add_const c).differentiable_within_at
@[simp] lemma differentiable_within_at_add_const_iff (c : F) :
differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable_at.add_const
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, f y + c) x :=
(hf.has_fderiv_at.add_const c).differentiable_at
@[simp] lemma differentiable_at_add_const_iff (c : F) :
differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable_on.add_const
(hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, f y + c) s :=
λx hx, (hf x hx).add_const c
@[simp] lemma differentiable_on_add_const_iff (c : F) :
differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable.add_const
(hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, f y + c) :=
λx, (hf x).add_const c
@[simp] lemma differentiable_add_const_iff (c : F) :
differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x :=
if hf : differentiable_within_at 𝕜 f s x
then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf,
fderiv_within_zero_of_not_differentiable_within_at], simpa }
lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ]
theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ y, c + f y) f' x :=
zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf
theorem has_fderiv_at_filter.const_add
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf
theorem has_fderiv_within_at.const_add
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_fderiv_at.const_add
(hf : has_fderiv_at f f' x) (c : F):
has_fderiv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma differentiable_within_at.const_add
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, c + f y) s x :=
(hf.has_fderiv_within_at.const_add c).differentiable_within_at
@[simp] lemma differentiable_within_at_const_add_iff (c : F) :
differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable_at.const_add
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, c + f y) x :=
(hf.has_fderiv_at.const_add c).differentiable_at
@[simp] lemma differentiable_at_const_add_iff (c : F) :
differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, c + f y) s :=
λx hx, (hf x hx).const_add c
@[simp] lemma differentiable_on_const_add_iff (c : F) :
differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, c + f y) :=
λx, (hf x).const_add c
@[simp] lemma differentiable_const_add_iff (c : F) :
differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x :=
by simpa only [add_comm] using fderiv_within_add_const hxs c
lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x :=
by simp only [add_comm c, fderiv_add_const]
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)}
theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) :
has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
begin
dsimp [has_strict_fderiv_at] at *,
convert is_o.sum h,
simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply]
end
theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) :
has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
begin
dsimp [has_fderiv_at_filter] at *,
convert is_o.sum h,
simp [continuous_linear_map.sum_apply]
end
theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) :
has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_fderiv_at_filter.sum h
theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) :
has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_fderiv_at_filter.sum h
theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x :=
has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $
λ i hi, (h i hi).has_fderiv_within_at
@[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x :=
has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at
theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) :
differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s :=
λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx
@[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) :
differentiable 𝕜 (λ y, ∑ i in u, A i y) :=
λ x, differentiable_at.sum $ λ i hi, h i hi x
theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) :=
(has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs
theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) :=
(has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv
end sum
section pi
/-!
### Derivatives of functions `f : E → Π i, F' i`
In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each
theorem:
* the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i`
and is designed to deduce differentiability of `λ x i, φ i x` from differentiability
of each `φ i`;
* the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i`
and is designed to deduce differentiability of the components `λ x, Φ x i` from
differentiability of `Φ`.
-/
variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)]
[Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i}
{Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i}
@[simp] lemma has_strict_fderiv_at_pi' :
has_strict_fderiv_at Φ Φ' x ↔
∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x :=
begin
simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi],
exact is_o_pi
end
@[simp] lemma has_strict_fderiv_at_pi :
has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔
∀ i, has_strict_fderiv_at (φ i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_fderiv_at_filter_pi' :
has_fderiv_at_filter Φ Φ' x L ↔
∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L :=
begin
simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi],
exact is_o_pi
end
lemma has_fderiv_at_filter_pi :
has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔
∀ i, has_fderiv_at_filter (φ i) (φ' i) x L :=
has_fderiv_at_filter_pi'
@[simp] lemma has_fderiv_at_pi' :
has_fderiv_at Φ Φ' x ↔
∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x :=
has_fderiv_at_filter_pi'
lemma has_fderiv_at_pi :
has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔
∀ i, has_fderiv_at (φ i) (φ' i) x :=
has_fderiv_at_filter_pi
@[simp] lemma has_fderiv_within_at_pi' :
has_fderiv_within_at Φ Φ' s x ↔
∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x :=
has_fderiv_at_filter_pi'
lemma has_fderiv_within_at_pi :
has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔
∀ i, has_fderiv_within_at (φ i) (φ' i) s x :=
has_fderiv_at_filter_pi
@[simp] lemma differentiable_within_at_pi :
differentiable_within_at 𝕜 Φ s x ↔
∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x :=
⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at,
λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩
@[simp] lemma differentiable_at_pi :
differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x :=
⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at,
λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩
lemma differentiable_on_pi :
differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s :=
⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i,
λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩
lemma differentiable_pi :
differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) :=
⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩
-- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp`
lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) :=
(has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs
lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) :
fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) :=
(has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv
end pi
section neg
/-! ### Derivative of the negative of a function -/
theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, -f x) (-f') x :=
(-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h
theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (λ x, -f x) (-f') x L :=
(-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h
theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) :
has_fderiv_at (λ x, -f x) (-f') x :=
h.neg
lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λy, -f y) s x :=
h.has_fderiv_within_at.neg.differentiable_within_at
@[simp] lemma differentiable_within_at_neg_iff :
differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λy, -f y) x :=
h.has_fderiv_at.neg.differentiable_at
@[simp] lemma differentiable_at_neg_iff :
differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λy, -f y) s :=
λx hx, (h x hx).neg
@[simp] lemma differentiable_on_neg_iff :
differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable.neg (h : differentiable 𝕜 f) :
differentiable 𝕜 (λy, -f y) :=
λx, (h x).neg
@[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x :=
if h : differentiable_within_at 𝕜 f s x
then h.has_fderiv_within_at.neg.fderiv_within hxs
else by { rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa }
@[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ]
end neg
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_strict_fderiv_at.sub
(hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) :
has_strict_fderiv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_fderiv_at_filter.sub
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_fderiv_within_at.sub
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_fderiv_at.sub
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
lemma differentiable_within_at.sub
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y - g y) s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y - g y) x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at
lemma differentiable_on.sub
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y - g y) s :=
λx hx, (hf x hx).sub (hg x hx)
@[simp] lemma differentiable.sub
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y - g y) :=
λx, (hf x).sub (hg x)
lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.sub_const
(hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ x, f x - c) f' x :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_fderiv_at_filter.sub_const
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_fderiv_within_at.sub_const
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_fderiv_at.sub_const
(hf : has_fderiv_at f f' x) (c : F) :
has_fderiv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma differentiable_within_at.sub_const
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, f y - c) s x :=
(hf.has_fderiv_within_at.sub_const c).differentiable_within_at
@[simp] lemma differentiable_within_at_sub_const_iff (c : F) :
differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff]
lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, f y - c) x :=
(hf.has_fderiv_at.sub_const c).differentiable_at
@[simp] lemma differentiable_at_sub_const_iff (c : F) :
differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x :=
by simp only [sub_eq_add_neg, differentiable_at_add_const_iff]
lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, f y - c) s :=
λx hx, (hf x hx).sub_const c
@[simp] lemma differentiable_on_sub_const_iff (c : F) :
differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s :=
by simp only [sub_eq_add_neg, differentiable_on_add_const_iff]
lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, f y - c) :=
λx, (hf x).sub_const c
@[simp] lemma differentiable_sub_const_iff (c : F) :
differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f :=
by simp only [sub_eq_add_neg, differentiable_add_const_iff]
lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x :=
by simp only [sub_eq_add_neg, fderiv_within_add_const hxs]
lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x :=
by simp only [sub_eq_add_neg, fderiv_add_const]
theorem has_strict_fderiv_at.const_sub
(hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_fderiv_at_filter.const_sub
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_fderiv_within_at.const_sub
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_fderiv_at.const_sub
(hf : has_fderiv_at f f' x) (c : F) :
has_fderiv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma differentiable_within_at.const_sub
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, c - f y) s x :=
(hf.has_fderiv_within_at.const_sub c).differentiable_within_at
@[simp] lemma differentiable_within_at_const_sub_iff (c : F) :
differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x :=
by simp [sub_eq_add_neg]
lemma differentiable_at.const_sub
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, c - f y) x :=
(hf.has_fderiv_at.const_sub c).differentiable_at
@[simp] lemma differentiable_at_const_sub_iff (c : F) :
differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x :=
by simp [sub_eq_add_neg]
lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, c - f y) s :=
λx hx, (hf x hx).const_sub c
@[simp] lemma differentiable_on_const_sub_iff (c : F) :
differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s :=
by simp [sub_eq_add_neg]
lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, c - f y) :=
λx, (hf x).const_sub c
@[simp] lemma differentiable_const_sub_iff (c : F) :
differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f :=
by simp [sub_eq_add_neg]
lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x :=
by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs]
lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ]
end sub
section bilinear_map
/-! ### Derivative of a bounded bilinear map -/
variables {b : E × F → G} {u : set (E × F) }
open normed_field
lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_strict_fderiv_at b (h.deriv p) p :=
begin
rw has_strict_fderiv_at,
set T := (E × F) × (E × F),
have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)),
{ refine (h.is_O'.comp_tendsto le_top).trans_is_o _,
simp only [(∘)],
refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _),
rw [← sub_self p],
exact continuous_at_fst.sub continuous_at_snd },
simp only [mul_one, is_o_norm_right] at this,
refine (is_o.congr_of_sub _).1 this, clear this,
convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)),
{ ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩,
simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right],
abel },
have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)),
from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd),
apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o,
refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right,
refine is_o.mul_is_O _ (is_O_refl _ _),
exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o
this).norm_left
end
lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_at b (h.deriv p) p :=
(h.has_strict_fderiv_at p).has_fderiv_at
lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_within_at b (h.deriv p) u p :=
(h.has_fderiv_at p).has_fderiv_within_at
lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
differentiable_at 𝕜 b p :=
(h.has_fderiv_at p).differentiable_at
lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b)
(p : E × F) :
differentiable_within_at 𝕜 b u p :=
(h.differentiable_at p).differentiable_within_at
lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
fderiv 𝕜 b p = h.deriv p :=
has_fderiv_at.fderiv (h.has_fderiv_at p)
lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F)
(hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p :=
begin
rw differentiable_at.fderiv_within (h.differentiable_at p) hxs,
exact h.fderiv p
end
lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) :
differentiable 𝕜 b :=
λx, h.differentiable_at x
lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) :
differentiable_on 𝕜 b u :=
h.differentiable.differentiable_on
end bilinear_map
section clm_comp_apply
/-! ### Derivative of the pointwise composition/application of continuous linear maps -/
variables {H : Type*} [normed_group H] [normed_space 𝕜 H] {c : E → G →L[𝕜] H}
{c' : E →L[𝕜] G →L[𝕜] H} {d : E → F →L[𝕜] G} {d' : E →L[𝕜] F →L[𝕜] G} {u : E → G}
{u' : E →L[𝕜] G}
lemma has_strict_fderiv_at.clm_comp (hc : has_strict_fderiv_at c c' x)
(hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, (c y).comp (d y))
((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x :=
begin
rw add_comm,
exact (is_bounded_bilinear_map_comp.has_strict_fderiv_at (d x, c x)).comp x (hd.prod hc)
end
lemma has_fderiv_within_at.clm_comp (hc : has_fderiv_within_at c c' s x)
(hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, (c y).comp (d y))
((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') s x :=
begin
rw add_comm,
exact (is_bounded_bilinear_map_comp.has_fderiv_at (d x, c x)).comp_has_fderiv_within_at x
(hd.prod hc)
end
lemma has_fderiv_at.clm_comp (hc : has_fderiv_at c c' x)
(hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, (c y).comp (d y))
((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x :=
begin
rw add_comm,
exact (is_bounded_bilinear_map_comp.has_fderiv_at (d x, c x)).comp x (hd.prod hc)
end
lemma differentiable_within_at.clm_comp
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
differentiable_within_at 𝕜 (λ y, (c y).comp (d y)) s x :=
(hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.clm_comp (hc : differentiable_at 𝕜 c x)
(hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, (c y).comp (d y)) x :=
(hc.has_fderiv_at.clm_comp hd.has_fderiv_at).differentiable_at
lemma differentiable_on.clm_comp (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) :
differentiable_on 𝕜 (λ y, (c y).comp (d y)) s :=
λx hx, (hc x hx).clm_comp (hd x hx)
lemma differentiable.clm_comp (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) :
differentiable 𝕜 (λ y, (c y).comp (d y)) :=
λx, (hc x).clm_comp (hd x)
lemma fderiv_within_clm_comp (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
fderiv_within 𝕜 (λ y, (c y).comp (d y)) s x =
(compL 𝕜 F G H (c x)).comp (fderiv_within 𝕜 d s x) +
((compL 𝕜 F G H).flip (d x)).comp (fderiv_within 𝕜 c s x) :=
(hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
fderiv 𝕜 (λ y, (c y).comp (d y)) x =
(compL 𝕜 F G H (c x)).comp (fderiv 𝕜 d x) +
((compL 𝕜 F G H).flip (d x)).comp (fderiv 𝕜 c x) :=
(hc.has_fderiv_at.clm_comp hd.has_fderiv_at).fderiv
lemma has_strict_fderiv_at.clm_apply (hc : has_strict_fderiv_at c c' x)
(hu : has_strict_fderiv_at u u' x) :
has_strict_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x :=
(is_bounded_bilinear_map_apply.has_strict_fderiv_at (c x, u x)).comp x (hc.prod hu)
lemma has_fderiv_within_at.clm_apply (hc : has_fderiv_within_at c c' s x)
(hu : has_fderiv_within_at u u' s x) :
has_fderiv_within_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) s x :=
(is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp_has_fderiv_within_at x (hc.prod hu)
lemma has_fderiv_at.clm_apply (hc : has_fderiv_at c c' x) (hu : has_fderiv_at u u' x) :
has_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x :=
(is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp x (hc.prod hu)
lemma differentiable_within_at.clm_apply
(hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) :
differentiable_within_at 𝕜 (λ y, (c y) (u y)) s x :=
(hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.clm_apply (hc : differentiable_at 𝕜 c x)
(hu : differentiable_at 𝕜 u x) : differentiable_at 𝕜 (λ y, (c y) (u y)) x :=
(hc.has_fderiv_at.clm_apply hu.has_fderiv_at).differentiable_at
lemma differentiable_on.clm_apply (hc : differentiable_on 𝕜 c s) (hu : differentiable_on 𝕜 u s) :
differentiable_on 𝕜 (λ y, (c y) (u y)) s :=
λx hx, (hc x hx).clm_apply (hu x hx)
lemma differentiable.clm_apply (hc : differentiable 𝕜 c) (hu : differentiable 𝕜 u) :
differentiable 𝕜 (λ y, (c y) (u y)) :=
λx, (hc x).clm_apply (hu x)
lemma fderiv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) :
fderiv_within 𝕜 (λ y, (c y) (u y)) s x =
((c x).comp (fderiv_within 𝕜 u s x) + (fderiv_within 𝕜 c s x).flip (u x)) :=
(hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) :
fderiv 𝕜 (λ y, (c y) (u y)) x = ((c x).comp (fderiv 𝕜 u x) + (fderiv 𝕜 c x).flip (u x)) :=
(hc.has_fderiv_at.clm_apply hu.has_fderiv_at).fderiv
end clm_comp_apply
section smul
/-! ### Derivative of the product of a scalar-valued function and a vector-valued function
If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued
function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for
function `c` taking values in the base field, as well as in a normed algebra over the base
field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex
normed vector space.
-/
variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F]
variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'}
theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x)
(hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x :=
(is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $
hc.prod hf
theorem has_fderiv_within_at.smul
(hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x :=
(is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $
hc.prod hf
theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x :=
(is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $
hc.prod hf
lemma differentiable_within_at.smul
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λ y, c y • f y) s x :=
(hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λ y, c y • f y) x :=
(hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at
lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λ y, c y • f y) s :=
λx hx, (hc x hx).smul (hf x hx)
@[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (λ y, c y • f y) :=
λx, (hc x).smul (hf x)
lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
fderiv_within 𝕜 (λ y, c y • f y) s x =
c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) :=
(hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (λ y, c y • f y) x =
c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) :=
(hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) :
has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x)
theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) :
has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s)
theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) :
has_fderiv_at (λ y, c y • f) (c'.smul_right f) x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x)
lemma differentiable_within_at.smul_const
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
differentiable_within_at 𝕜 (λ y, c y • f) s x :=
(hc.has_fderiv_within_at.smul_const f).differentiable_within_at
lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
differentiable_at 𝕜 (λ y, c y • f) x :=
(hc.has_fderiv_at.smul_const f).differentiable_at
lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) :
differentiable_on 𝕜 (λ y, c y • f) s :=
λx hx, (hc x hx).smul_const f
lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) :
differentiable 𝕜 (λ y, c y • f) :=
λx, (hc x).smul_const f
lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
fderiv_within 𝕜 (λ y, c y • f) s x =
(fderiv_within 𝕜 c s x).smul_right f :=
(hc.has_fderiv_within_at.smul_const f).fderiv_within hxs
lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f :=
(hc.has_fderiv_at.smul_const f).fderiv
end smul
section mul
/-! ### Derivative of the product of two functions -/
variables {𝔸 𝔸' : Type*} [normed_ring 𝔸] [normed_comm_ring 𝔸'] [normed_algebra 𝕜 𝔸]
[normed_algebra 𝕜 𝔸'] {a b : E → 𝔸} {a' b' : E →L[𝕜] 𝔸} {c d : E → 𝔸'} {c' d' : E →L[𝕜] 𝔸'}
theorem has_strict_fderiv_at.mul' {x : E} (ha : has_strict_fderiv_at a a' x)
(hb : has_strict_fderiv_at b b' x) :
has_strict_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x :=
((continuous_linear_map.lmul 𝕜 𝔸).is_bounded_bilinear_map.has_strict_fderiv_at (a x, b x)).comp x
(ha.prod hb)
theorem has_strict_fderiv_at.mul
(hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) :
has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
by { convert hc.mul' hd, ext z, apply mul_comm }
theorem has_fderiv_within_at.mul'
(ha : has_fderiv_within_at a a' s x) (hb : has_fderiv_within_at b b' s x) :
has_fderiv_within_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) s x :=
((continuous_linear_map.lmul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at
(a x, b x)).comp_has_fderiv_within_at x (ha.prod hb)
theorem has_fderiv_within_at.mul
(hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) :
has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x :=
by { convert hc.mul' hd, ext z, apply mul_comm }
theorem has_fderiv_at.mul'
(ha : has_fderiv_at a a' x) (hb : has_fderiv_at b b' x) :
has_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x :=
((continuous_linear_map.lmul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at (a x, b x)).comp x
(ha.prod hb)
theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) :
has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
by { convert hc.mul' hd, ext z, apply mul_comm }
lemma differentiable_within_at.mul
(ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) :
differentiable_within_at 𝕜 (λ y, a y * b y) s x :=
(ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.mul (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) :
differentiable_at 𝕜 (λ y, a y * b y) x :=
(ha.has_fderiv_at.mul' hb.has_fderiv_at).differentiable_at
lemma differentiable_on.mul (ha : differentiable_on 𝕜 a s) (hb : differentiable_on 𝕜 b s) :
differentiable_on 𝕜 (λ y, a y * b y) s :=
λx hx, (ha x hx).mul (hb x hx)
@[simp] lemma differentiable.mul (ha : differentiable 𝕜 a) (hb : differentiable 𝕜 b) :
differentiable 𝕜 (λ y, a y * b y) :=
λx, (ha x).mul (hb x)
lemma fderiv_within_mul' (hxs : unique_diff_within_at 𝕜 s x)
(ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) :
fderiv_within 𝕜 (λ y, a y * b y) s x =
a x • fderiv_within 𝕜 b s x + (fderiv_within 𝕜 a s x).smul_right (b x) :=
(ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
fderiv_within 𝕜 (λ y, c y * d y) s x =
c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_mul' (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) :
fderiv 𝕜 (λ y, a y * b y) x =
a x • fderiv 𝕜 b x + (fderiv 𝕜 a x).smul_right (b x) :=
(ha.has_fderiv_at.mul' hb.has_fderiv_at).fderiv
lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
fderiv 𝕜 (λ y, c y * d y) x =
c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.mul_const' (ha : has_strict_fderiv_at a a' x) (b : 𝔸) :
has_strict_fderiv_at (λ y, a y * b) (a'.smul_right b) x :=
(((continuous_linear_map.lmul 𝕜 𝔸).flip b).has_strict_fderiv_at).comp x ha
theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝔸') :
has_strict_fderiv_at (λ y, c y * d) (d • c') x :=
by { convert hc.mul_const' d, ext z, apply mul_comm }
theorem has_fderiv_within_at.mul_const' (ha : has_fderiv_within_at a a' s x) (b : 𝔸) :
has_fderiv_within_at (λ y, a y * b) (a'.smul_right b) s x :=
(((continuous_linear_map.lmul 𝕜 𝔸).flip b).has_fderiv_at).comp_has_fderiv_within_at x ha
theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝔸') :
has_fderiv_within_at (λ y, c y * d) (d • c') s x :=
by { convert hc.mul_const' d, ext z, apply mul_comm }
theorem has_fderiv_at.mul_const' (ha : has_fderiv_at a a' x) (b : 𝔸) :
has_fderiv_at (λ y, a y * b) (a'.smul_right b) x :=
(((continuous_linear_map.lmul 𝕜 𝔸).flip b).has_fderiv_at).comp x ha
theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝔸') :
has_fderiv_at (λ y, c y * d) (d • c') x :=
by { convert hc.mul_const' d, ext z, apply mul_comm }
lemma differentiable_within_at.mul_const
(ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) :
differentiable_within_at 𝕜 (λ y, a y * b) s x :=
(ha.has_fderiv_within_at.mul_const' b).differentiable_within_at
lemma differentiable_at.mul_const (ha : differentiable_at 𝕜 a x) (b : 𝔸) :
differentiable_at 𝕜 (λ y, a y * b) x :=
(ha.has_fderiv_at.mul_const' b).differentiable_at
lemma differentiable_on.mul_const (ha : differentiable_on 𝕜 a s) (b : 𝔸) :
differentiable_on 𝕜 (λ y, a y * b) s :=
λx hx, (ha x hx).mul_const b
lemma differentiable.mul_const (ha : differentiable 𝕜 a) (b : 𝔸) :
differentiable 𝕜 (λ y, a y * b) :=
λx, (ha x).mul_const b
lemma fderiv_within_mul_const' (hxs : unique_diff_within_at 𝕜 s x)
(ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) :
fderiv_within 𝕜 (λ y, a y * b) s x = (fderiv_within 𝕜 a s x).smul_right b :=
(ha.has_fderiv_within_at.mul_const' b).fderiv_within hxs
lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝔸') :
fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.mul_const d).fderiv_within hxs
lemma fderiv_mul_const' (ha : differentiable_at 𝕜 a x) (b : 𝔸) :
fderiv 𝕜 (λ y, a y * b) x = (fderiv 𝕜 a x).smul_right b :=
(ha.has_fderiv_at.mul_const' b).fderiv
lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸') :
fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x :=
(hc.has_fderiv_at.mul_const d).fderiv
theorem has_strict_fderiv_at.const_mul (ha : has_strict_fderiv_at a a' x) (b : 𝔸) :
has_strict_fderiv_at (λ y, b * a y) (b • a') x :=
(((continuous_linear_map.lmul 𝕜 𝔸) b).has_strict_fderiv_at).comp x ha
theorem has_fderiv_within_at.const_mul
(ha : has_fderiv_within_at a a' s x) (b : 𝔸) :
has_fderiv_within_at (λ y, b * a y) (b • a') s x :=
(((continuous_linear_map.lmul 𝕜 𝔸) b).has_fderiv_at).comp_has_fderiv_within_at x ha
theorem has_fderiv_at.const_mul (ha : has_fderiv_at a a' x) (b : 𝔸) :
has_fderiv_at (λ y, b * a y) (b • a') x :=
(((continuous_linear_map.lmul 𝕜 𝔸) b).has_fderiv_at).comp x ha
lemma differentiable_within_at.const_mul
(ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) :
differentiable_within_at 𝕜 (λ y, b * a y) s x :=
(ha.has_fderiv_within_at.const_mul b).differentiable_within_at
lemma differentiable_at.const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) :
differentiable_at 𝕜 (λ y, b * a y) x :=
(ha.has_fderiv_at.const_mul b).differentiable_at
lemma differentiable_on.const_mul (ha : differentiable_on 𝕜 a s) (b : 𝔸) :
differentiable_on 𝕜 (λ y, b * a y) s :=
λx hx, (ha x hx).const_mul b
lemma differentiable.const_mul (ha : differentiable 𝕜 a) (b : 𝔸) :
differentiable 𝕜 (λ y, b * a y) :=
λx, (ha x).const_mul b
lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) :
fderiv_within 𝕜 (λ y, b * a y) s x = b • fderiv_within 𝕜 a s x :=
(ha.has_fderiv_within_at.const_mul b).fderiv_within hxs
lemma fderiv_const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) :
fderiv 𝕜 (λ y, b * a y) x = b • fderiv 𝕜 a x :=
(ha.has_fderiv_at.const_mul b).fderiv
end mul
section algebra_inverse
variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R]
open normed_ring continuous_linear_map ring
/-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion
operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/
lemma has_fderiv_at_ring_inverse (x : units R) :
has_fderiv_at ring.inverse (-lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x :=
begin
have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹)
(λ (t : R), t) (𝓝 0),
{ refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _),
simp only [normed_field.norm_pow, norm_norm],
have h12 : 1 < 2 := by norm_num,
convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero,
ext, simp },
have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0),
{ refine tendsto_zero_iff_norm_tendsto_zero.mpr _,
exact tendsto_iff_norm_tendsto_zero.mp tendsto_id },
simp only [has_fderiv_at, has_fderiv_at_filter],
convert h_is_o.comp_tendsto h_lim,
ext y,
simp only [coe_comp', function.comp_app, lmul_left_right_apply, neg_apply, inverse_unit x,
units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add]
end
lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x :=
(has_fderiv_at_ring_inverse x).differentiable_at
lemma fderiv_inverse (x : units R) :
fderiv 𝕜 (@ring.inverse R _) x = - lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ :=
(has_fderiv_at_ring_inverse x).fderiv
end algebra_inverse
namespace continuous_linear_equiv
/-! ### Differentiability of linear equivs, and invariance of differentiability -/
variable (iso : E ≃L[𝕜] F)
protected lemma has_strict_fderiv_at :
has_strict_fderiv_at iso (iso : E →L[𝕜] F) x :=
iso.to_continuous_linear_map.has_strict_fderiv_at
protected lemma has_fderiv_within_at :
has_fderiv_within_at iso (iso : E →L[𝕜] F) s x :=
iso.to_continuous_linear_map.has_fderiv_within_at
protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x :=
iso.to_continuous_linear_map.has_fderiv_at_filter
protected lemma differentiable_at : differentiable_at 𝕜 iso x :=
iso.has_fderiv_at.differentiable_at
protected lemma differentiable_within_at :
differentiable_within_at 𝕜 iso s x :=
iso.differentiable_at.differentiable_within_at
protected lemma fderiv : fderiv 𝕜 iso x = iso :=
iso.has_fderiv_at.fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 iso s x = iso :=
iso.to_continuous_linear_map.fderiv_within hxs
protected lemma differentiable : differentiable 𝕜 iso :=
λx, iso.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 iso s :=
iso.differentiable.differentiable_on
lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} :
differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x :=
begin
refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩,
have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x :=
iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H,
rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this,
end
lemma comp_differentiable_at_iff {f : G → E} {x : G} :
differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x :=
by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ,
iso.comp_differentiable_within_at_iff]
lemma comp_differentiable_on_iff {f : G → E} {s : set G} :
differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s :=
begin
rw [differentiable_on, differentiable_on],
simp only [iso.comp_differentiable_within_at_iff],
end
lemma comp_differentiable_iff {f : G → E} :
differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f :=
begin
rw [← differentiable_on_univ, ← differentiable_on_univ],
exact iso.comp_differentiable_on_iff
end
lemma comp_has_fderiv_within_at_iff
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x :=
begin
refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩,
have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl },
have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'),
by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe,
continuous_linear_map.id_comp],
rw [A, B],
exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H
end
lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x :=
begin
refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩,
convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm
end
lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x :=
by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff]
lemma comp_has_fderiv_within_at_iff'
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_within_at (iso ∘ f) f' s x ↔
has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x :=
by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc,
iso.coe_comp_coe_symm, continuous_linear_map.id_comp]
lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x :=
by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff']
lemma comp_fderiv_within {f : G → E} {s : set G} {x : G}
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) :=
begin
by_cases h : differentiable_within_at 𝕜 f s x,
{ rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] },
{ have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x,
from mt iso.comp_differentiable_within_at_iff.1 h,
rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at this,
continuous_linear_map.comp_zero] }
end
lemma comp_fderiv {f : G → E} {x : G} :
fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) :=
begin
rw [← fderiv_within_univ, ← fderiv_within_univ],
exact iso.comp_fderiv_within unique_diff_within_at_univ,
end
end continuous_linear_equiv
namespace linear_isometry_equiv
/-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/
variable (iso : E ≃ₗᵢ[𝕜] F)
protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x :=
(iso : E ≃L[𝕜] F).has_strict_fderiv_at
protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x :=
(iso : E ≃L[𝕜] F).has_fderiv_within_at
protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x :=
(iso : E ≃L[𝕜] F).has_fderiv_at
protected lemma differentiable_at : differentiable_at 𝕜 iso x :=
iso.has_fderiv_at.differentiable_at
protected lemma differentiable_within_at :
differentiable_within_at 𝕜 iso s x :=
iso.differentiable_at.differentiable_within_at
protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 iso s x = iso :=
(iso : E ≃L[𝕜] F).fderiv_within hxs
protected lemma differentiable : differentiable 𝕜 iso :=
λx, iso.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 iso s :=
iso.differentiable.differentiable_on
lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} :
differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x :=
(iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff
lemma comp_differentiable_at_iff {f : G → E} {x : G} :
differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x :=
(iso : E ≃L[𝕜] F).comp_differentiable_at_iff
lemma comp_differentiable_on_iff {f : G → E} {s : set G} :
differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s :=
(iso : E ≃L[𝕜] F).comp_differentiable_on_iff
lemma comp_differentiable_iff {f : G → E} :
differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f :=
(iso : E ≃L[𝕜] F).comp_differentiable_iff
lemma comp_has_fderiv_within_at_iff
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff
lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x :=
(iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff
lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff
lemma comp_has_fderiv_within_at_iff'
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_within_at (iso ∘ f) f' s x ↔
has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff'
lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff'
lemma comp_fderiv_within {f : G → E} {s : set G} {x : G}
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) :=
(iso : E ≃L[𝕜] F).comp_fderiv_within hxs
lemma comp_fderiv {f : G → E} {x : G} :
fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) :=
(iso : E ≃L[𝕜] F).comp_fderiv
end linear_isometry_equiv
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a`
in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have an
inverse function. -/
theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F}
(hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a))
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a :=
begin
replace hg := hg.prod_map' hg,
replace hfg := hfg.prod_mk_nhds hfg,
have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2))
(λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)),
{ refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl),
simp },
refine this.trans_is_o _, clear this,
refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _)
(eventually_of_forall $ λ _, rfl)).trans_is_O _,
{ rintros p ⟨hp1, hp2⟩,
simp [hp1, hp2] },
{ refine (hf.is_O_sub_rev.comp_tendsto hg).congr'
(eventually_of_forall $ λ _, rfl) (hfg.mono _),
rintros p ⟨hp1, hp2⟩,
simp only [(∘), hp1, hp2] }
end
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F}
(hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a))
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_fderiv_at g (f'.symm : F →L[𝕜] E) a :=
begin
have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a),
{ refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl),
simp },
refine this.trans_is_o _, clear this,
refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _)
(eventually_of_forall $ λ _, rfl)).trans_is_O _,
{ rintros p hp,
simp [hp, hfg.self_of_nhds] },
{ refine (hf.is_O_sub_rev.comp_tendsto hg).congr'
(eventually_of_forall $ λ _, rfl) (hfg.mono _),
rintros p hp,
simp only [(∘), hp, hfg.self_of_nhds] }
end
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has
the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F}
(ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) :
has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha)
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F}
(ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) :
has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha)
lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x)
(hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) :
∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x :=
begin
rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal],
have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) :=
(is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _),
have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A,
simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp
end
lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) :
∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x :=
by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf'
end
section
/-
In the special case of a normed space over the reals,
we can use scalar multiplication in the `tendsto` characterization
of the Fréchet derivative.
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
variables {F : Type*} [normed_group F] [normed_space ℝ F]
variables {f : E → F} {f' : E →L[ℝ] F} {x : E}
theorem has_fderiv_at_filter_real_equiv {L : filter E} :
tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔
tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) :=
begin
symmetry,
rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _),
have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _),
simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this]
end
lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) :
tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) :=
begin
apply hf.lim v,
rw tendsto_at_top_at_top,
exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩
end
end
section tangent_cone
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{f : E → F} {s : set E} {f' : E →L[𝕜] F}
/-- The image of a tangent cone under the differential of a map is included in the tangent cone to
the image. -/
lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) :
maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) :=
begin
rintros v ⟨c, d, dtop, clim, cdlim⟩,
refine ⟨c, (λn, f (x + d n) - f x), mem_of_superset dtop _, clim,
h.lim at_top dtop clim cdlim⟩,
simp [-mem_image, mem_image_of_mem] {contextual := tt}
end
/-- If a set has the unique differentiability property at a point x, then the image of this set
under a map with onto derivative has also the unique differentiability property at the image point.
-/
lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x)
(hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') :
unique_diff_within_at 𝕜 (f '' s) (f x) :=
begin
refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _,
h.continuous_within_at.mem_closure_image hs.2⟩,
show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤
(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap ↑f',
rw [submodule.span_le],
exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span
end
lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s)
(hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) :
unique_diff_on 𝕜 (f '' s) :=
ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx)
lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv
{x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x)
(hs : unique_diff_within_at 𝕜 s x) :
unique_diff_within_at 𝕜 (f '' s) (f x) :=
h.unique_diff_within_at hs e'.surjective.dense_range
lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) :
unique_diff_on 𝕜 (e '' s) :=
h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range)
@[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) :
unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s :=
⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩
@[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) :
unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s :=
by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff]
end tangent_cone
section restrict_scalars
/-!
### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜`
If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph,
we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced
respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`.
-/
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E]
variables [is_scalar_tower 𝕜 𝕜' E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F]
variables [is_scalar_tower 𝕜 𝕜' F]
variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E}
lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h
lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) :
has_fderiv_at f (f'.restrict_scalars 𝕜) x := h
lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h
lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) :
differentiable_at 𝕜 f x :=
(h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at
lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) :
differentiable_within_at 𝕜 f s x :=
(h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at
lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) :
differentiable_on 𝕜 f s :=
λx hx, (h x hx).restrict_scalars 𝕜
lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) :
differentiable 𝕜 f :=
λx, (h x).restrict_scalars 𝕜
lemma has_fderiv_within_at_of_restrict_scalars
{g' : E →L[𝕜] F} (h : has_fderiv_within_at f g' s x)
(H : f'.restrict_scalars 𝕜 = g') : has_fderiv_within_at f f' s x :=
by { rw ← H at h, exact h }
lemma has_fderiv_at_of_restrict_scalars {g' : E →L[𝕜] F} (h : has_fderiv_at f g' x)
(H : f'.restrict_scalars 𝕜 = g') : has_fderiv_at f f' x :=
by { rw ← H at h, exact h }
lemma differentiable_at.fderiv_restrict_scalars (h : differentiable_at 𝕜' f x) :
fderiv 𝕜 f x = (fderiv 𝕜' f x).restrict_scalars 𝕜 :=
(h.has_fderiv_at.restrict_scalars 𝕜).fderiv
lemma differentiable_within_at_iff_restrict_scalars
(hf : differentiable_within_at 𝕜 f s x) (hs : unique_diff_within_at 𝕜 s x) :
differentiable_within_at 𝕜' f s x ↔
∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv_within 𝕜 f s x :=
begin
split,
{ rintros ⟨g', hg'⟩,
exact ⟨g', hs.eq (hg'.restrict_scalars 𝕜) hf.has_fderiv_within_at⟩, },
{ rintros ⟨f', hf'⟩,
exact ⟨f', has_fderiv_within_at_of_restrict_scalars 𝕜 hf.has_fderiv_within_at hf'⟩, },
end
lemma differentiable_at_iff_restrict_scalars (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜' f x ↔ ∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv 𝕜 f x :=
begin
rw [← differentiable_within_at_univ, ← fderiv_within_univ],
exact differentiable_within_at_iff_restrict_scalars 𝕜
hf.differentiable_within_at unique_diff_within_at_univ,
end
end restrict_scalars
|
ad11b8c231e0516bdee9a52e44c5a0c017caf042 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/geometry/manifold/algebra/smooth_functions.lean | dbd3907d820440bcfca671f2f756c022f21d9994 | [
"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 | 10,750 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.algebra.structures
/-!
# Algebraic structures over smooth functions
In this file, we define instances of algebraic structures over smooth functions.
-/
noncomputable theory
open_locale manifold
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{N : Type*} [topological_space N] [charted_space H N]
{E'' : Type*} [normed_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''}
{N' : Type*} [topological_space N'] [charted_space H'' N']
namespace smooth_map
@[to_additive]
instance has_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G]
[has_smooth_mul I' G] :
has_mul C^∞⟮I, N; I', G⟯ :=
⟨λ f g, ⟨f * g, f.smooth.mul g.smooth⟩⟩
@[simp, to_additive]
lemma coe_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G]
[has_smooth_mul I' G] (f g : C^∞⟮I, N; I', G⟯) :
⇑(f * g) = f * g := rfl
@[simp, to_additive] lemma mul_comp {G : Type*} [has_mul G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] (f g : C^∞⟮I'', N'; I', G⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(f * g).comp h = (f.comp h) * (g.comp h) :=
by ext; simp only [times_cont_mdiff_map.comp_apply, coe_mul, pi.mul_apply]
@[to_additive]
instance has_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] :
has_one C^∞⟮I, N; I', G⟯ :=
⟨times_cont_mdiff_map.const (1 : G)⟩
@[simp, to_additive]
lemma coe_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] :
⇑(1 : C^∞⟮I, N; I', G⟯) = 1 := rfl
section group_structure
/-!
### Group structure
In this section we show that smooth functions valued in a Lie group inherit a group structure
under pointwise multiplication.
-/
@[to_additive]
instance semigroup {G : Type*} [semigroup G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
semigroup C^∞⟮I, N; I', G⟯ :=
{ mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _,
..smooth_map.has_mul}
@[to_additive]
instance monoid {G : Type*} [monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
monoid C^∞⟮I, N; I', G⟯ :=
{ one_mul := λ a, by ext; exact one_mul _,
mul_one := λ a, by ext; exact mul_one _,
..smooth_map.semigroup,
..smooth_map.has_one }
/-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/
@[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.",
simps]
def coe_fn_monoid_hom {G : Type*} [monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] : C^∞⟮I, N; I', G⟯ →* (N → G) :=
{ to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul }
@[to_additive]
instance comm_monoid {G : Type*} [comm_monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
comm_monoid C^∞⟮I, N; I', G⟯ :=
{ mul_comm := λ a b, by ext; exact mul_comm _ _,
..smooth_map.monoid,
..smooth_map.has_one }
@[to_additive]
instance group {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] :
group C^∞⟮I, N; I', G⟯ :=
{ inv := λ f, ⟨λ x, (f x)⁻¹, f.smooth.inv⟩,
mul_left_inv := λ a, by ext; exact mul_left_inv _,
div := λ f g, ⟨f / g, f.smooth.div g.smooth⟩,
div_eq_mul_inv := λ f g, by ext; exact div_eq_mul_inv _ _,
.. smooth_map.monoid }
@[simp, to_additive]
lemma coe_inv {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] (f : C^∞⟮I, N; I', G⟯) :
⇑f⁻¹ = f⁻¹ := rfl
@[simp, to_additive]
lemma coe_div {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] (f g : C^∞⟮I, N; I', G⟯) :
⇑(f / g) = f / g :=
rfl
@[to_additive]
instance comm_group {G : Type*} [comm_group G] [topological_space G]
[charted_space H' G] [lie_group I' G] :
comm_group C^∞⟮I, N; I', G⟯ :=
{ ..smooth_map.group,
..smooth_map.comm_monoid }
end group_structure
section ring_structure
/-!
### Ring stucture
In this section we show that smooth functions valued in a smooth ring `R` inherit a ring structure
under pointwise multiplication.
-/
instance semiring {R : Type*} [semiring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
semiring C^∞⟮I, N; I', R⟯ :=
{ left_distrib := λ a b c, by ext; exact left_distrib _ _ _,
right_distrib := λ a b c, by ext; exact right_distrib _ _ _,
zero_mul := λ a, by ext; exact zero_mul _,
mul_zero := λ a, by ext; exact mul_zero _,
..smooth_map.add_comm_monoid,
..smooth_map.monoid }
instance ring {R : Type*} [ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map.semiring,
..smooth_map.add_comm_group, }
instance comm_ring {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
comm_ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map.semiring,
..smooth_map.add_comm_group,
..smooth_map.comm_monoid,}
/-- Coercion to a function as a `ring_hom`. -/
@[simps]
def coe_fn_ring_hom {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] : C^∞⟮I, N; I', R⟯ →+* (N → R) :=
{ to_fun := coe_fn,
..(coe_fn_monoid_hom : C^∞⟮I, N; I', R⟯ →* _),
..(coe_fn_add_monoid_hom : C^∞⟮I, N; I', R⟯ →+ _) }
/-- `function.eval` as a `ring_hom` on the ring of smooth functions. -/
def eval_ring_hom {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] (n : N) : C^∞⟮I, N; I', R⟯ →+* R :=
(pi.eval_ring_hom _ n : (N → R) →+* R).comp smooth_map.coe_fn_ring_hom
end ring_structure
section module_structure
/-!
### Semiodule stucture
In this section we show that smooth functions valued in a vector space `M` over a normed
field `𝕜` inherit a vector space structure.
-/
instance has_scalar {V : Type*} [normed_group V] [normed_space 𝕜 V] :
has_scalar 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ r f, ⟨r • f, smooth_const.smul f.smooth⟩⟩
@[simp]
lemma coe_smul {V : Type*} [normed_group V] [normed_space 𝕜 V]
(r : 𝕜) (f : C^∞⟮I, N; 𝓘(𝕜, V), V⟯) :
⇑(r • f) = r • f := rfl
@[simp] lemma smul_comp {V : Type*} [normed_group V] [normed_space 𝕜 V]
(r : 𝕜) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(r • g).comp h = r • (g.comp h) := rfl
instance module {V : Type*} [normed_group V] [normed_space 𝕜 V] :
module 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
module.of_core $
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add c (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul c₁ c₂ (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul c₁ c₂ (f x),
one_smul := λ f, by ext x; exact one_smul 𝕜 (f x), }
/-- Coercion to a function as a `linear_map`. -/
@[simps]
def coe_fn_linear_map {V : Type*} [normed_group V] [normed_space 𝕜 V] :
C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →ₗ[𝕜] (N → V) :=
{ to_fun := coe_fn,
map_smul' := coe_smul,
..(coe_fn_add_monoid_hom : C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →+ _) }
end module_structure
section algebra_structure
/-!
### Algebra structure
In this section we show that smooth functions valued in a normed algebra `A` over a normed field `𝕜`
inherit an algebra structure.
-/
variables {A : Type*} [normed_ring A] [normed_algebra 𝕜 A] [smooth_ring 𝓘(𝕜, A) A]
/-- Smooth constant functions as a `ring_hom`. -/
def C : 𝕜 →+* C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ to_fun := λ c : 𝕜, ⟨λ x, ((algebra_map 𝕜 A) c), smooth_const⟩,
map_one' := by ext x; exact (algebra_map 𝕜 A).map_one,
map_mul' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_mul _ _,
map_zero' := by ext x; exact (algebra_map 𝕜 A).map_zero,
map_add' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_add _ _ }
instance algebra : algebra 𝕜 C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ smul := λ r f,
⟨r • f, smooth_const.smul f.smooth⟩,
to_ring_hom := smooth_map.C,
commutes' := λ c f, by ext x; exact algebra.commutes' _ _,
smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _,
..smooth_map.semiring }
/-- A special case of `pi.algebra` for non-dependent types. Lean get stuck on the definition
below without this. -/
instance _root_.function.algebra (I : Type*) {R : Type*} (A : Type*) {r : comm_semiring R}
[semiring A] [algebra R A] : algebra R (I → A) :=
pi.algebra _ _
/-- Coercion to a function as an `alg_hom`. -/
@[simps]
def coe_fn_alg_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →ₐ[𝕜] (N → A) :=
{ to_fun := coe_fn,
commutes' := λ r, rfl,
-- `..(smooth_map.coe_fn_ring_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →+* _)` times out for some reason
map_zero' := smooth_map.coe_zero,
map_one' := smooth_map.coe_one,
map_add' := smooth_map.coe_add,
map_mul' := smooth_map.coe_mul }
end algebra_structure
section module_over_continuous_functions
/-!
### Structure as module over scalar functions
If `V` is a module over `𝕜`, then we show that the space of smooth functions from `N` to `V`
is naturally a vector space over the ring of smooth functions from `N` to `𝕜`. -/
instance has_scalar' {V : Type*} [normed_group V] [normed_space 𝕜 V] :
has_scalar C^∞⟮I, N; 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ f g, ⟨λ x, (f x) • (g x), (smooth.smul f.2 g.2)⟩⟩
@[simp] lemma smul_comp' {V : Type*} [normed_group V] [normed_space 𝕜 V]
(f : C^∞⟮I'', N'; 𝕜⟯) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(f • g).comp h = (f.comp h) • (g.comp h) := rfl
instance module' {V : Type*} [normed_group V] [normed_space 𝕜 V] :
module C^∞⟮I, N; 𝓘(𝕜), 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x),
one_smul := λ f, by ext x; exact one_smul 𝕜 (f x),
zero_smul := λ f, by ext x; exact zero_smul _ _,
smul_zero := λ r, by ext x; exact smul_zero _, }
end module_over_continuous_functions
end smooth_map
|
05c2fe31d66a540f2b557fe6e701c421f0ad21c5 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/topology/algebra/module.lean | 5c97a62e7379e5e81bc2f4c1c898cafbfa94f4c2 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 38,750 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov
-/
import topology.algebra.ring
import topology.uniform_space.uniform_embedding
import ring_theory.algebra
import linear_algebra.projection
/-!
# Theory of topological modules and continuous linear maps.
We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`,
as extensions of the corresponding algebraic classes where the algebraic operations are continuous.
We also define continuous linear maps, as linear maps between topological modules which are
continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is
denoted by `M →L[R] M₂`.
Continuous linear equivalences are denoted by `M ≃L[R] M₂`.
## Implementation notes
Topological vector spaces are defined as an `abbreviation` for topological modules,
if the base ring is a field. This has as advantage that topological vector spaces are completely
transparent for type class inference, which means that all instances for topological modules
are immediately picked up for vector spaces as well.
A cosmetic disadvantage is that one can not extend topological vector spaces.
The solution is to extend `topological_module` instead.
-/
open filter
open_locale topological_space big_operators
universes u v w u'
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological semimodule, over a semiring which is also a topological space, is a
semimodule in which scalar multiplication is continuous. In applications, R will be a topological
semiring and M a topological additive semigroup, but this is not needed for the definition -/
class topological_semimodule (R : Type u) (M : Type v)
[semiring R] [topological_space R]
[topological_space M] [add_comm_monoid M]
[semimodule R M] : Prop :=
(continuous_smul : continuous (λp : R × M, p.1 • p.2))
end prio
section
variables {R : Type u} {M : Type v}
[semiring R] [topological_space R]
[topological_space M] [add_comm_monoid M]
[semimodule R M] [topological_semimodule R M]
lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) :=
topological_semimodule.continuous_smul
lemma continuous.smul {α : Type*} [topological_space α] {f : α → R} {g : α → M}
(hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) :=
continuous_smul.comp (hf.prod_mk hg)
lemma tendsto_smul {c : R} {x : M} : tendsto (λp:R×M, p.fst • p.snd) (𝓝 (c, x)) (𝓝 (c • x)) :=
continuous_smul.tendsto _
lemma filter.tendsto.smul {α : Type*} {l : filter α} {f : α → R} {g : α → M} {c : R} {x : M}
(hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 x)) : tendsto (λ a, f a • g a) l (𝓝 (c • x)) :=
tendsto_smul.comp (hf.prod_mk_nhds hg)
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological module, over a ring which is also a topological space, is a module in which
scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a
topological additive group, but this is not needed for the definition -/
class topological_module (R : Type u) (M : Type v)
[ring R] [topological_space R]
[topological_space M] [add_comm_group M]
[module R M]
extends topological_semimodule R M : Prop
/-- A topological vector space is a topological module over a field. -/
abbreviation topological_vector_space (R : Type u) (M : Type v)
[field R] [topological_space R]
[topological_space M] [add_comm_group M] [module R M] :=
topological_module R M
end prio
section
variables {R : Type*} {M : Type*}
[ring R] [topological_space R]
[topological_space M] [add_comm_group M]
[module R M] [topological_module R M]
/-- Scalar multiplication by a unit is a homeomorphism from a
topological module onto itself. -/
protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M :=
{ to_fun := λ x, (a : R) • x,
inv_fun := λ x, ((a⁻¹ : units R) : R) • x,
right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x :
by rw [smul_smul, units.mul_inv, one_smul],
left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x :
by rw [smul_smul, units.inv_mul, one_smul],
continuous_to_fun := continuous_const.smul continuous_id,
continuous_inv_fun := continuous_const.smul continuous_id }
lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) :=
(homeomorph.smul_of_unit a).is_open_map
lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) :=
(homeomorph.smul_of_unit a).is_closed_map
/-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then
`⊤` is the only submodule of `M` with a nonempty interior. See also
`submodule.eq_top_of_nonempty_interior` for a `normed_space` version. -/
lemma submodule.eq_top_of_nonempty_interior' [topological_add_monoid M]
(h : nhds_within (0:R) {x | is_unit x} ≠ ⊥)
(s : submodule R M) (hs : (interior (s:set M)).nonempty) :
s = ⊤ :=
begin
rcases hs with ⟨y, hy⟩,
refine (submodule.eq_top_iff'.2 $ λ x, _),
rw [mem_interior_iff_mem_nhds] at hy,
have : tendsto (λ c:R, y + c • x) (nhds_within 0 {x | is_unit x}) (𝓝 (y + (0:R) • x)),
from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul
tendsto_const_nhds),
rw [zero_smul, add_zero] at this,
rcases nonempty_of_mem_sets h (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within)
with ⟨_, hu, u, rfl⟩,
have hy' : y ∈ ↑s := mem_of_nhds hy,
exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu)
end
end
section
variables {R : Type*} {M : Type*} {a : R}
[field R] [topological_space R]
[topological_space M] [add_comm_group M]
[vector_space R M] [topological_vector_space R M]
/-- Scalar multiplication by a non-zero field element is a
homeomorphism from a topological vector space onto itself. -/
protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M :=
{.. homeomorph.smul_of_unit (units.mk0 a ha)}
lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_open_map
lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_closed_map
end
/-- Continuous linear maps between modules. We only put the type classes that are necessary for the
definition, although in applications `M` and `M₂` will be topological modules over the topological
ring `R`. -/
structure continuous_linear_map
(R : Type*) [semiring R]
(M : Type*) [topological_space M] [add_comm_monoid M]
(M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂]
[semimodule R M] [semimodule R M₂]
extends linear_map R M M₂ :=
(cont : continuous to_fun)
notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂
/-- Continuous linear equivalences between modules. We only put the type classes that are necessary
for the definition, although in applications `M` and `M₂` will be topological modules over the
topological ring `R`. -/
@[nolint has_inhabited_instance]
structure continuous_linear_equiv
(R : Type*) [semiring R]
(M : Type*) [topological_space M] [add_comm_monoid M]
(M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂]
[semimodule R M] [semimodule R M₂]
extends linear_equiv R M M₂ :=
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂
namespace continuous_linear_map
section semiring
/- Properties that hold for non-necessarily commutative semirings. -/
variables
{R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_monoid M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄]
[semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄]
/-- Coerce continuous linear maps to linear maps. -/
instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
/-- Coerce continuous linear maps to functions. -/
-- see Note [function coercion]
instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨λ _, M → M₂, λ f, f⟩
protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2
@[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr' 1; ext x; apply h
theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, by rw h, by ext⟩
variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M)
-- make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero
@[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _
@[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _
@[simp, norm_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl
/-- The continuous map that is constantly zero. -/
instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_const⟩⟩
instance : inhabited (M →L[R] M₂) := ⟨0⟩
@[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl
/- no simp attribute on the next line as simp does not always simplify `0 x` to `0`
when `0` is the zero function, while it does for the zero continuous linear map,
and this is the most important property we care about. -/
@[norm_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl
section
variables (R M)
/-- the identity map as a continuous linear map. -/
def id : M →L[R] M :=
⟨linear_map.id, continuous_id⟩
end
instance : has_one (M →L[R] M) := ⟨id R M⟩
lemma id_apply : id R M x = x := rfl
@[simp, norm_cast] lemma coe_id : (id R M : M →ₗ[R] M) = linear_map.id := rfl
@[simp, norm_cast] lemma coe_id' : (id R M : M → M) = _root_.id := rfl
@[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl
section add
variables [topological_add_monoid M₂]
instance : has_add (M →L[R] M₂) :=
⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
@[simp] lemma add_apply : (f + g) x = f x + g x := rfl
@[simp, norm_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl
@[norm_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl
instance : add_comm_monoid (M →L[R] M₂) :=
by { refine {zero := 0, add := (+), ..}; intros; ext;
apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] }
lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) (b : M) :
(∑ d in t, f d) b = ∑ d in t, f d b :=
begin
haveI : is_add_monoid_hom (λ (g : M →L[R] M₂), g b) :=
{ map_add := λ f g, continuous_linear_map.add_apply f g b, map_zero := by simp },
exact (finset.sum_hom t (λ g : M →L[R] M₂, g b)).symm
end
end add
/-- Composition of bounded linear maps. -/
def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ :=
⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩
@[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl
@[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl
@[simp] theorem comp_id : f.comp (id R M) = f :=
ext $ λ x, rfl
@[simp] theorem id_comp : (id R M₂).comp f = f :=
ext $ λ x, rfl
@[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 :=
by { ext, simp }
@[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 :=
by { ext, simp }
@[simp] lemma comp_add [topological_add_monoid M₂] [topological_add_monoid M₃]
(g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) :
g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ :=
by { ext, simp }
@[simp] lemma add_comp [topological_add_monoid M₃]
(g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(g₁ + g₂).comp f = g₁.comp f + g₂.comp f :=
by { ext, simp }
theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(h.comp g).comp f = h.comp (g.comp f) :=
rfl
instance : has_mul (M →L[R] M) := ⟨comp⟩
lemma mul_def (f g : M →L[R] M) : f * g = f.comp g := rfl
@[simp] lemma coe_mul (f g : M →L[R] M) : ⇑(f * g) = f ∘ g := rfl
lemma mul_apply (f g : M →L[R] M) (x : M) : (f * g) x = f (g x) := rfl
/-- The cartesian product of two bounded linear maps, as a bounded linear map. -/
protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) :=
{ cont := f₁.2.prod_mk f₂.2,
..f₁.to_linear_map.prod f₂.to_linear_map }
@[simp, norm_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) :
(f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ :=
rfl
@[simp, norm_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) :
f₁.prod f₂ x = (f₁ x, f₂ x) :=
rfl
/-- Kernel of a continuous linear map. -/
def ker (f : M →L[R] M₂) : submodule R M := (f : M →ₗ[R] M₂).ker
@[norm_cast] lemma ker_coe : (f : M →ₗ[R] M₂).ker = f.ker := rfl
@[simp] lemma mem_ker {f : M →L[R] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker
lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M) :=
continuous_iff_is_closed.1 f.cont _ is_closed_singleton
@[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2
lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M']
[semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) :
is_complete (f.ker : set M') :=
is_complete_of_is_closed f.is_closed_ker
instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M']
[semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) :
complete_space f.ker :=
f.is_closed_ker.complete_space_coe
@[simp] lemma ker_prod (f : M →L[R] M₂) (g : M →L[R] M₃) :
ker (f.prod g) = ker f ⊓ ker g :=
linear_map.ker_prod f g
/-- Range of a continuous linear map. -/
def range (f : M →L[R] M₂) : submodule R M₂ := (f : M →ₗ[R] M₂).range
lemma range_coe : (f.range : set M₂) = set.range f := linear_map.range_coe _
lemma mem_range {f : M →L[R] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range
lemma range_prod_le (f : M →L[R] M₂) (g : M →L[R] M₃) :
range (f.prod g) ≤ (range f).prod (range g) :=
(f : M →ₗ[R] M₂).range_prod_le g
/-- Restrict codomain of a continuous linear map. -/
def cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
M →L[R] p :=
{ cont := continuous_subtype_mk h f.continuous,
to_linear_map := (f : M →ₗ[R] M₂).cod_restrict p h}
@[norm_cast] lemma coe_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
(f.cod_restrict p h : M →ₗ[R] p) = (f : M →ₗ[R] M₂).cod_restrict p h :=
rfl
@[simp] lemma coe_cod_restrict_apply (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) (x) :
(f.cod_restrict p h x : M₂) = f x :=
rfl
@[simp] lemma ker_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
ker (f.cod_restrict p h) = ker f :=
(f : M →ₗ[R] M₂).ker_cod_restrict p h
/-- Embedding of a submodule into the ambient space as a continuous linear map. -/
def subtype_val (p : submodule R M) : p →L[R] M :=
{ cont := continuous_subtype_val,
to_linear_map := p.subtype }
@[simp, norm_cast] lemma coe_subtype_val (p : submodule R M) :
(subtype_val p : p →ₗ[R] M) = p.subtype :=
rfl
@[simp, norm_cast] lemma subtype_val_apply (p : submodule R M) (x : p) :
(subtype_val p : p → M) x = x :=
rfl
variables (R M M₂)
/-- `prod.fst` as a `continuous_linear_map`. -/
def fst : M × M₂ →L[R] M :=
{ cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ }
/-- `prod.snd` as a `continuous_linear_map`. -/
def snd : M × M₂ →L[R] M₂ :=
{ cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ }
variables {R M M₂}
@[simp, norm_cast] lemma coe_fst : (fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ := rfl
@[simp, norm_cast] lemma coe_fst' : (fst R M M₂ : M × M₂ → M) = prod.fst := rfl
@[simp, norm_cast] lemma coe_snd : (snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ := rfl
@[simp, norm_cast] lemma coe_snd' : (snd R M M₂ : M × M₂ → M₂) = prod.snd := rfl
@[simp] lemma fst_prod_snd : (fst R M M₂).prod (snd R M M₂) = id R (M × M₂) := ext $ λ ⟨x, y⟩, rfl
/-- `prod.map` of two continuous linear maps. -/
def prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (M × M₃) →L[R] (M₂ × M₄) :=
(f₁.comp (fst R M M₃)).prod (f₂.comp (snd R M M₃))
@[simp, norm_cast] lemma coe_prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) :
(f₁.prod_map f₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = ((f₁ : M →ₗ[R] M₂).prod_map (f₂ : M₃ →ₗ[R] M₄)) :=
rfl
@[simp, norm_cast] lemma coe_prod_map' (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) :
⇑(f₁.prod_map f₂) = prod.map f₁ f₂ :=
rfl
/-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/
def coprod [topological_add_monoid M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) :
(M × M₂) →L[R] M₃ :=
⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩
@[norm_cast, simp] lemma coe_coprod [topological_add_monoid M₃]
(f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) :
(f₁.coprod f₂ : (M × M₂) →ₗ[R] M₃) = linear_map.coprod f₁ f₂ :=
rfl
@[simp] lemma coprod_apply [topological_add_monoid M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) (x) :
f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl
variables [topological_space R] [topological_semimodule R M₂]
/-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of
`M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/
def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ :=
{ cont := c.2.smul continuous_const,
..c.to_linear_map.smul_right f }
@[simp]
lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} :
(smul_right c f : M → M₂) x = (c : M → R) x • f :=
rfl
@[simp]
lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c :=
by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm]
@[simp]
lemma smul_right_one_eq_iff {f f' : M₂} :
smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' :=
⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1,
by rw h,
by simp at this; assumption,
by cc⟩
lemma smul_right_comp [topological_semimodule R R] {x : M₂} {c : R} :
(smul_right 1 x : R →L[R] M₂).comp (smul_right 1 c : R →L[R] R) = smul_right 1 (c • x) :=
by { ext, simp [mul_smul] }
end semiring
section ring
variables
{R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_group M₄]
[semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄]
variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M)
@[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _
@[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _
@[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl
lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) :
range (f.prod g) = (range f).prod (range g) :=
linear_map.range_prod_eq h
section
variables [topological_add_group M₂]
instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
@[simp] lemma neg_apply : (-f) x = - (f x) := rfl
@[simp, norm_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl
@[norm_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl
instance : add_comm_group (M →L[R] M₂) :=
by { refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext;
apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] }
lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
@[simp, norm_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl
@[simp, norm_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl
end
instance [topological_add_group M] : ring (M →L[R] M) :=
{ mul := (*),
one := 1,
mul_one := λ _, ext $ λ _, rfl,
one_mul := λ _, ext $ λ _, rfl,
mul_assoc := λ _ _ _, ext $ λ _, rfl,
left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _,
right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _,
..continuous_linear_map.add_comm_group }
lemma smul_right_one_pow [topological_space R]
[topological_add_group R] [topological_semimodule R R] (c : R) (n : ℕ) :
(smul_right 1 c : R →L[R] R)^n = smul_right 1 (c^n) :=
begin
induction n with n ihn,
{ ext, simp },
{ rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] }
end
/-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`,
`proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/
def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) :
M →L[R] f₁.ker :=
(id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)]
@[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) :
(f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) :=
rfl
@[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) :
f₁.proj_ker_of_right_inverse f₂ h x = x :=
subtype.coe_ext.2 $ by simp
@[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂) :
f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 :=
subtype.coe_ext.2 $ by simp [h y]
end ring
section comm_ring
variables
{R : Type*} [comm_ring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃] [topological_module R M₃]
instance : has_scalar R (M →L[R] M₃) :=
⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩
variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M)
@[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl
variable [topological_module R M₂]
@[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl
@[simp, norm_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl
@[norm_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl
@[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp }
variable [topological_add_group M₂]
instance : module R (M →L[R] M₂) :=
{ smul_zero := λ _, ext $ λ _, smul_zero _,
zero_smul := λ _, ext $ λ _, zero_smul _ _,
one_smul := λ _, ext $ λ _, one_smul _ _,
mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _,
add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _,
smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ }
instance : algebra R (M₂ →L[R] M₂) :=
algebra.of_semimodule' (λ c f, ext $ λ x, rfl) (λ c f, ext $ λ x, f.map_smul c x)
end comm_ring
end continuous_linear_map
namespace continuous_linear_equiv
section add_comm_monoid
variables {R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_monoid M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄]
[semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄]
/-- A continuous linear equivalence induces a continuous linear map. -/
def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ :=
{ cont := e.continuous_to_fun,
..e.to_linear_equiv.to_linear_map }
/-- Coerce continuous linear equivs to continuous linear maps. -/
instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩
/-- Coerce continuous linear equivs to maps. -/
-- see Note [function coercion]
instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨λ _, M → M₂, λ f, f⟩
@[simp] theorem coe_def_rev (e : M ≃L[R] M₂) : e.to_continuous_linear_map = e := rfl
@[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl
@[norm_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl
@[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g :=
begin
cases f; cases g,
simp only [],
ext x,
induction h,
refl
end
/-- A continuous linear equivalence induces a homeomorphism. -/
def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e }
-- Make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero
@[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y :=
(e : M →L[R] M₂).map_add x y
@[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) :=
(e : M →L[R] M₂).map_smul c x
@[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 :=
e.to_linear_equiv.map_eq_zero_iff
protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) :=
e.continuous_to_fun
protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s :=
e.continuous.continuous_on
protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x :=
e.continuous.continuous_at
protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} :
continuous_within_at (e : M → M₂) s x :=
e.continuous.continuous_within_at
lemma comp_continuous_on_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) (s : set α) :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.to_homeomorph.comp_continuous_on_iff _ _
lemma comp_continuous_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) :
continuous (e ∘ f) ↔ continuous f :=
e.to_homeomorph.comp_continuous_iff _
/-- An extensionality lemma for `R ≃L[R] M`. -/
lemma ext₁ [topological_space R] {f g : R ≃L[R] M} (h : f 1 = g 1) : f = g :=
ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul]
section
variables (R M)
/-- The identity map as a continuous linear equivalence. -/
@[refl] protected def refl : M ≃L[R] M :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
.. linear_equiv.refl R M }
end
@[simp, norm_cast] lemma coe_refl :
(continuous_linear_equiv.refl R M : M →L[R] M) = continuous_linear_map.id R M := rfl
@[simp, norm_cast] lemma coe_refl' :
(continuous_linear_equiv.refl R M : M → M) = id := rfl
/-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/
@[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M :=
{ continuous_to_fun := e.continuous_inv_fun,
continuous_inv_fun := e.continuous_to_fun,
.. e.to_linear_equiv.symm }
@[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) :
e.symm.to_linear_equiv = e.to_linear_equiv.symm :=
by { ext, refl }
/-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/
@[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ :=
{ continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun,
continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun,
.. e₁.to_linear_equiv.trans e₂.to_linear_equiv }
@[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) :
(e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv :=
by { ext, refl }
/-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/
def prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (M × M₃) ≃L[R] (M₂ × M₄) :=
{ continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun,
continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun,
.. e.to_linear_equiv.prod e'.to_linear_equiv }
@[simp, norm_cast] lemma prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (x) :
e.prod e' x = (e x.1, e' x.2) := rfl
@[simp, norm_cast] lemma coe_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) :
(e.prod e' : (M × M₃) →L[R] (M₂ × M₄)) = (e : M →L[R] M₂).prod_map (e' : M₃ →L[R] M₄) :=
rfl
theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective
theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective
theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective
@[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c
@[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b
@[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) :
(e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id R M₂ :=
continuous_linear_map.ext e.apply_symm_apply
@[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) :
(e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id R M :=
continuous_linear_map.ext e.symm_apply_apply
lemma symm_comp_self (e : M ≃L[R] M₂) :
(e.symm : M₂ → M) ∘ (e : M → M₂) = id :=
by{ ext x, exact symm_apply_apply e x }
lemma self_comp_symm (e : M ≃L[R] M₂) :
(e : M → M₂) ∘ (e.symm : M₂ → M) = id :=
by{ ext x, exact apply_symm_apply e x }
@[simp] lemma symm_comp_self' (e : M ≃L[R] M₂) :
((e.symm : M₂ →L[R] M) : M₂ → M) ∘ ((e : M →L[R] M₂) : M → M₂) = id :=
symm_comp_self e
@[simp] lemma self_comp_symm' (e : M ≃L[R] M₂) :
((e : M →L[R] M₂) : M → M₂) ∘ ((e.symm : M₂ →L[R] M) : M₂ → M) = id :=
self_comp_symm e
@[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e :=
by { ext x, refl }
theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x :=
rfl
lemma symm_apply_eq (e : M ≃L[R] M₂) {x y} : e.symm x = y ↔ x = e y :=
e.to_linear_equiv.symm_apply_eq
lemma eq_symm_apply (e : M ≃L[R] M₂) {x y} : y = e.symm x ↔ e y = x :=
e.to_linear_equiv.eq_symm_apply
/-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are
inverse of each other. -/
def equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h₁ : function.left_inverse f₂ f₁)
(h₂ : function.right_inverse f₂ f₁) :
M ≃L[R] M₂ :=
{ to_fun := f₁,
continuous_to_fun := f₁.continuous,
inv_fun := f₂,
continuous_inv_fun := f₂.continuous,
left_inv := h₁,
right_inv := h₂,
.. f₁ }
@[simp] lemma equiv_of_inverse_apply (f₁ : M →L[R] M₂) (f₂ h₁ h₂ x) :
equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x :=
rfl
@[simp] lemma symm_equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ h₁ h₂) :
(equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ :=
rfl
end add_comm_monoid
section add_comm_group
variables {R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_group M₄]
[semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄]
variables [topological_add_group M₄]
/-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks,
and `f` is a rectangular block below the diagonal. -/
def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) :
(M × M₃) ≃L[R] M₂ × M₄ :=
{ continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk
((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst),
continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk
(e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $
e.continuous_inv_fun.comp continuous_fst),
.. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f }
@[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) :
e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl
@[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) :
(e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl
end add_comm_group
section ring
variables {R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M] [semimodule R M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [semimodule R M₂]
@[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y :=
(e : M →L[R] M₂).map_sub x y
@[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x
section
variables (R) [topological_space R] [topological_module R R]
/-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/
def units_equiv_aut : units R ≃ (R ≃L[R] R) :=
{ to_fun := λ u, equiv_of_inverse
(continuous_linear_map.smul_right 1 ↑u)
(continuous_linear_map.smul_right 1 ↑u⁻¹)
(λ x, by simp) (λ x, by simp),
inv_fun := λ e, ⟨e 1, e.symm 1,
by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply],
by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩,
left_inv := λ u, units.ext $ by simp,
right_inv := λ e, ext₁ $ by simp }
variable {R}
@[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl
@[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) :
(units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl
@[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) :
↑((units_equiv_aut R).symm e) = e 1 :=
rfl
end
variables [topological_add_group M]
open continuous_linear_map (id fst snd subtype_val mem_ker)
/-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous
linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`,
`(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/
def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) :
M ≃L[R] M₂ × f₁.ker :=
equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker))
(λ x, by simp)
(λ ⟨x, y⟩, by simp [h x])
@[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (x : M) :
(equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl
@[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (x : M) :
((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl
@[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) :
(equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl
end ring
end continuous_linear_equiv
namespace submodule
variables
{R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M] [module R M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂]
open continuous_linear_map
/-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/
def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x
lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p]
(h : closed_complemented p) :
∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q :=
exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩
protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M]
{p : submodule R M} (h : closed_complemented p) :
is_closed (p : set M) :=
begin
rcases h with ⟨f, hf⟩,
have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf,
exact this ▸ (is_closed_ker _)
end
@[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) :=
⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩
@[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) :=
⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.coe_ext.2 $ by simp⟩
end submodule
lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂]
[topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) :
f₁.ker.closed_complemented :=
⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
|
5b321d4e41cacb21a2f5934b8c8878fa5d2acd51 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/stream/basic.lean | 2da1070cbaa1b02b6eec1b81309fc56646938743 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,136 | lean | /-
Copyright (c) 2020 Gabriel Ebner, Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.ext
import Mathlib.Lean3Lib.data.stream
import Mathlib.data.list.basic
import Mathlib.data.list.range
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Additional instances and attributes for streams
-/
protected instance stream.inhabited {α : Type u_1} [Inhabited α] : Inhabited (stream α) :=
{ default := stream.const Inhabited.default }
namespace stream
/-- `take s n` returns a list of the `n` first elements of stream `s` -/
def take {α : Type u_1} (s : stream α) (n : ℕ) : List α :=
list.map s (list.range n)
theorem length_take {α : Type u_1} (s : stream α) (n : ℕ) : list.length (take s n) = n := sorry
/-- Use a state monad to generate a stream through corecursion -/
def corec_state {σ : Type u_1} {α : Type u_1} (cmd : state σ α) (s : σ) : stream α :=
corec prod.fst (state_t.run cmd ∘ prod.snd) (state_t.run cmd s)
|
92ec18b5f81a4dbb2f08d45957ef20d2b9229709 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/analysis/special_functions/exp_log.lean | 173245000765e88a9677cb132f416431771252cd | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 22,032 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import data.complex.exponential
import analysis.complex.basic
import analysis.calculus.mean_value
/-!
# Complex and real exponential, real logarithm
## Main statements
This file establishes the basic analytical properties of the complex and real exponential functions
(continuity, differentiability, computation of the derivative).
It also contains the definition of the real logarithm function (as the inverse of the
exponential on `(0, +∞)`, extended to `ℝ` by setting `log (-x) = log x`) and its basic
properties (continuity, differentiability, formula for the derivative).
The complex logarithm is *not* defined in this file as it relies on trigonometric functions. See
instead `trigonometric.lean`.
## Tags
exp, log
-/
noncomputable theory
open finset filter metric asymptotics
open_locale classical topological_space
namespace complex
/-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/
lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x :=
begin
rw has_deriv_at_iff_is_o_nhds_zero,
have : (1 : ℕ) < 2 := by norm_num,
refine (is_O.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this),
have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one,
apply filter.mem_sets_of_superset this (λz hz, _),
simp only [metric.mem_ball, dist_zero_right] at hz,
simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow,
zero_add, set.mem_set_of_eq],
calc ∥exp (x + z) - exp x - z * exp x∥
= ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring }
... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _
... ≤ ∥exp x∥ * ∥z∥^2 :
mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _)
end
lemma differentiable_exp : differentiable ℂ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
end complex
section
variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x :=
(complex.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x :=
(complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.exp (f x)) s x :=
hf.has_deriv_within_at.cexp.differentiable_within_at
@[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.exp (f x)) x :=
hc.has_deriv_at.cexp.differentiable_at
lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.exp (f x)) s :=
λx h, (hc x h).cexp
@[simp] lemma differentiable.cexp (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.exp (f x)) :=
λx, (hc x).cexp
lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cexp.deriv_within hxs
@[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) :
deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) :=
hc.has_deriv_at.cexp.deriv
end
namespace real
variables {x y z : ℝ}
lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_exp x)
lemma differentiable_exp : differentiable ℝ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp : differentiable_at ℝ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
end real
section
/-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`,
`real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with
`simp`. -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
/-! `real.exp`-/
lemma has_deriv_at.exp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x :=
(real.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x :=
(real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.exp (f x)) s x :=
hf.has_deriv_within_at.exp.differentiable_within_at
@[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.exp (f x)) x :=
hc.has_deriv_at.exp.differentiable_at
lemma differentiable_on.exp (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.exp (f x)) s :=
λx h, (hc x h).exp
@[simp] lemma differentiable.exp (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.exp (f x)) :=
λx, (hc x).exp
lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.exp.deriv_within hxs
@[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) :
deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) :=
hc.has_deriv_at.exp.deriv
end
namespace real
variables {x y z : ℝ}
lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x :=
have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp,
from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp
⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩,
match le_total x 1 with
| (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in
⟨-y, by rw [exp_neg, hy, inv_inv']⟩
| (or.inr hx1) := this hx1
end
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
noncomputable def log (x : ℝ) : ℝ :=
if hx : x ≠ 0 then classical.some (exists_exp_eq_of_pos (abs_pos_iff.mpr hx)) else 0
lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = abs x :=
by { rw [log, dif_pos hx], exact classical.some_spec (exists_exp_eq_of_pos ((abs_pos_iff.mpr hx))) }
lemma exp_log (hx : 0 < x) : exp (log x) = x :=
by { rw exp_log_eq_abs (ne_of_gt hx), exact abs_of_pos hx }
lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x :=
by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx }
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
@[simp] lemma log_zero : log 0 = 0 :=
by simp [log]
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
@[simp] lemma log_abs (x : ℝ) : log (abs x) = log x :=
begin
by_cases h : x = 0,
{ simp [h] },
{ apply exp_injective,
rw [exp_log_eq_abs h, exp_log_eq_abs, abs_abs],
simp [h] }
end
@[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x :=
by rw [← log_abs x, ← log_abs (-x), abs_neg]
lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective $
by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
@[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x :=
begin
by_cases hx : x = 0, { simp [hx] },
apply eq_neg_of_add_eq_zero,
rw [← log_mul (inv_ne_zero hx) hx, inv_mul_cancel hx, log_one]
end
lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y :=
⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂,
(real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x :=
by { rw ← log_one, exact log_lt_log_iff (by norm_num) hx }
lemma log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx)).2 hx
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h (by norm_num) }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg : 1 ≤ x → 0 ≤ log x :=
by { intro, rwa [← log_one, log_le_log], norm_num, linarith }
lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
begin
by_cases x_zero : x = 0,
{ simp [x_zero] },
{ rwa [← log_one, log_le_log (lt_of_le_of_ne hx (ne.symm x_zero))], norm_num }
end
section prove_log_is_continuous
lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) :=
begin
rw tendsto_nhds_nhds, assume ε ε0,
let δ := min (exp ε - 1) (1 - exp (-ε)),
have : 0 < δ,
refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _),
by { rw exp_lt_one_iff, linarith },
use [δ, this], assume x h,
cases le_total 1 x with hx hx,
{ have h : x < exp ε,
rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h,
linarith [(min_le_left _ _ : δ ≤ exp ε - 1)],
calc abs (log x - 0) = abs (log x) : by simp
... = log x : abs_of_nonneg $ log_nonneg hx
... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }},
{ have h : exp (-ε) < x,
rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h,
linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))],
have : 0 < x := lt_trans (exp_pos _) h,
calc abs (log x - 0) = abs (log x) : by simp
... = -log x : abs_of_nonpos $ log_nonpos (le_of_lt this) hx
... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } }
end
lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) :=
continuous_iff_continuous_at.2 $ λ x,
begin
rw continuous_at,
let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1),
let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2),
have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))),
have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1,
ext h, rw ← log_mul (ne_of_gt x.2) (ne_of_gt h.2),
simp only [this, log_mul (ne_of_gt x.2) one_ne_zero, log_one],
exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_coe),
have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩),
rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_coe,
suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)),
begin
convert h, ext y,
have : x.val * (x.val⁻¹ * y.val) = y.val,
rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul],
show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this
end,
exact tendsto.comp (by rwa mul_one at H1)
(by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption })
end
lemma continuous_at_log (hx : 0 < x) : continuous_at log x :=
continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx)
(mem_nhds_sets (is_open_lt' _) hx)
/--
Three forms of the continuity of `real.log` are provided.
For the other two forms, see `real.continuous_log'` and `real.continuous_at_log`
-/
lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a)
(hf : continuous f) : continuous (λa, log (f a)) :=
show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩),
from continuous_log'.comp (continuous_subtype_mk _ hf)
end prove_log_is_continuous
lemma has_deriv_at_log_of_pos (hx : 0 < x) : has_deriv_at log x⁻¹ x :=
have has_deriv_at log (exp $ log x)⁻¹ x,
from (has_deriv_at_exp $ log x).of_local_left_inverse (continuous_at_log hx)
(ne_of_gt $ exp_pos _) $ eventually.mono (mem_nhds_sets is_open_Ioi hx) @exp_log,
by rwa [exp_log hx] at this
lemma has_deriv_at_log (hx : x ≠ 0) : has_deriv_at log x⁻¹ x :=
begin
by_cases h : 0 < x, { exact has_deriv_at_log_of_pos h },
push_neg at h,
convert ((has_deriv_at_log_of_pos (neg_pos.mpr (lt_of_le_of_ne h hx)))
.comp x (has_deriv_at_id x).neg),
{ ext y, exact (log_neg_eq_log y).symm },
{ field_simp [hx] }
end
end real
section log_differentiable
open real
variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ}
lemma has_deriv_within_at.log (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, log (f y)) (f' / (f x)) s x :=
begin
convert (has_deriv_at_log hx).comp_has_deriv_within_at x hf,
field_simp
end
lemma has_deriv_at.log (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, log (f y)) (f' / f x) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.log hx
end
lemma differentiable_within_at.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, log (f x)) s x :=
(hf.has_deriv_within_at.log hx).differentiable_within_at
@[simp] lemma differentiable_at.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, log (f x)) x :=
(hf.has_deriv_at.log hx).differentiable_at
lemma differentiable_on.log (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, log (f x)) s :=
λx h, (hf x h).log (hx x h)
@[simp] lemma differentiable.log (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, log (f x)) :=
λx, (hf x).log (hx x)
lemma deriv_within_log' (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, log (f x)) s x = (deriv_within f s x) / (f x) :=
(hf.has_deriv_within_at.log hx).deriv_within hxs
@[simp] lemma deriv_log' (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, log (f x)) x = (deriv f x) / (f x) :=
(hf.has_deriv_at.log hx).deriv
end log_differentiable
namespace real
/-- The real exponential function tends to `+∞` at `+∞`. -/
lemma tendsto_exp_at_top : tendsto exp at_top at_top :=
begin
have A : tendsto (λx:ℝ, x + 1) at_top at_top :=
tendsto_at_top_add_const_right at_top 1 tendsto_id,
have B : ∀ᶠ x in at_top, x + 1 ≤ exp x,
{ have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0,
filter_upwards [this],
exact λx hx, add_one_le_exp_of_nonneg hx },
exact tendsto_at_top_mono' at_top B A
end
/-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0`
at +infinity -/
lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm)
/-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/
lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top :=
begin
have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n,
have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos,
have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n,
{ assume x hx,
let y := x / (n+1),
have y_pos : 0 < y := div_pos hx n_pos,
have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc
exp y = exp y * 1 : by simp
... ≤ exp y * (exp y / y)^n : begin
apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)),
apply one_le_div_of_le _ y_pos,
apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)),
exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one)
end
... = exp y * exp (n * y) / y^n :
by rw [div_pow, exp_nat_mul, mul_div_assoc]
... = exp ((n + 1) * y) / y^n :
by rw [← exp_add, add_mul, one_mul, add_comm]
... = exp x / (x / (n+1))^n :
by { dsimp [y], rw mul_div_cancel' _ n_ne_zero }
... = (n+1)^n * (exp x / x^n) :
by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm],
rwa div_le_iff' (pow_pos n_pos n) },
have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n :=
mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩,
have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top :=
tendsto_at_top_div (pow_pos n_pos n)
(tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)),
exact tendsto_at_top_mono' at_top B C
end
/-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/
lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx,
by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg]
open_locale big_operators
/-- A crude lemma estimating the difference between `log (1-x)` and its Taylor series at `0`,
where the main point of the bound is that it tends to `0`. The goal is to deduce the series
expansion of the logarithm, in `has_sum_pow_div_log_of_abs_lt_1`.
-/
lemma abs_log_sub_add_sum_range_le {x : ℝ} (h : abs x < 1) (n : ℕ) :
abs ((∑ i in range n, x^(i+1)/(i+1)) + log (1-x)) ≤ (abs x)^(n+1) / (1 - abs x) :=
begin
/- For the proof, we show that the derivative of the function to be estimated is small,
and then apply the mean value inequality. -/
let F : ℝ → ℝ := λ x, ∑ i in range n, x^(i+1)/(i+1) + log (1-x),
-- First step: compute the derivative of `F`
have A : ∀ y ∈ set.Ioo (-1 : ℝ) 1, deriv F y = - (y^n) / (1 - y),
{ assume y hy,
have : (∑ i in range n, (↑i + 1) * y ^ i / (↑i + 1)) = (∑ i in range n, y ^ i),
{ congr,
ext i,
have : (i : ℝ) + 1 ≠ 0 := ne_of_gt (nat.cast_add_one_pos i),
field_simp [this, mul_comm] },
field_simp [F, this, ← geom_series_def, geom_sum (ne_of_lt hy.2),
sub_ne_zero_of_ne (ne_of_gt hy.2), sub_ne_zero_of_ne (ne_of_lt hy.2)],
ring },
-- second step: show that the derivative of `F` is small
have B : ∀ y ∈ set.Icc (-abs x) (abs x), abs (deriv F y) ≤ (abs x)^n / (1 - abs x),
{ assume y hy,
have : y ∈ set.Ioo (-(1 : ℝ)) 1 := ⟨lt_of_lt_of_le (neg_lt_neg h) hy.1, lt_of_le_of_lt hy.2 h⟩,
calc abs (deriv F y) = abs (-(y^n) / (1 - y)) : by rw [A y this]
... ≤ (abs x)^n / (1 - abs x) :
begin
have : abs y ≤ abs x := abs_le_of_le_of_neg_le hy.2 (by linarith [hy.1]),
have : 0 < 1 - abs x, by linarith,
have : 1 - abs x ≤ abs (1 - y) := le_trans (by linarith [hy.2]) (le_abs_self _),
simp only [← pow_abs, abs_div, abs_neg],
apply_rules [div_le_div, pow_nonneg, abs_nonneg, pow_le_pow_of_le_left]
end },
-- third step: apply the mean value inequality
have C : ∥F x - F 0∥ ≤ ((abs x)^n / (1 - abs x)) * ∥x - 0∥,
{ have : ∀ y ∈ set.Icc (- abs x) (abs x), differentiable_at ℝ F y,
{ assume y hy,
have : 1 - y ≠ 0 := sub_ne_zero_of_ne (ne_of_gt (lt_of_le_of_lt hy.2 h)),
simp [F, this] },
apply convex.norm_image_sub_le_of_norm_deriv_le this B (convex_Icc _ _) _ _,
{ simpa using abs_nonneg x },
{ simp [le_abs_self x, neg_le.mp (neg_le_abs_self x)] } },
-- fourth step: conclude by massaging the inequality of the third step
simpa [F, norm_eq_abs, div_mul_eq_mul_div, pow_succ'] using C
end
/-- Power series expansion of the logarithm around `1`. -/
theorem has_sum_pow_div_log_of_abs_lt_1 {x : ℝ} (h : abs x < 1) :
has_sum (λ (n : ℕ), x ^ (n + 1) / (n + 1)) (-log (1 - x)) :=
begin
rw summable.has_sum_iff_tendsto_nat,
show tendsto (λ (n : ℕ), ∑ (i : ℕ) in range n, x ^ (i + 1) / (i + 1)) at_top (𝓝 (-log (1 - x))),
{ rw [tendsto_iff_norm_tendsto_zero],
simp only [norm_eq_abs, sub_neg_eq_add],
refine squeeze_zero (λ n, abs_nonneg _) (abs_log_sub_add_sum_range_le h) _,
suffices : tendsto (λ (t : ℕ), abs x ^ (t + 1) / (1 - abs x)) at_top
(𝓝 (abs x * 0 / (1 - abs x))), by simpa,
simp only [pow_succ],
refine (tendsto_const_nhds.mul _).div_const,
exact tendsto_pow_at_top_nhds_0_of_lt_1 (abs_nonneg _) h },
show summable (λ (n : ℕ), x ^ (n + 1) / (n + 1)),
{ refine summable_of_norm_bounded _ (summable_geometric_of_lt_1 (abs_nonneg _) h) (λ i, _),
calc ∥x ^ (i + 1) / (i + 1)∥
= abs x ^ (i+1) / (i+1) :
begin
have : (0 : ℝ) ≤ i + 1 := le_of_lt (nat.cast_add_one_pos i),
rw [norm_eq_abs, abs_div, ← pow_abs, abs_of_nonneg this],
end
... ≤ abs x ^ (i+1) / (0 + 1) :
begin
apply_rules [div_le_div_of_le_left, pow_nonneg, abs_nonneg, add_le_add_right,
i.cast_nonneg],
norm_num,
end
... ≤ abs x ^ i :
by simpa [pow_succ'] using mul_le_of_le_one_right (pow_nonneg (abs_nonneg x) i) (le_of_lt h) }
end
end real
|
f9e02366927344a42ae9d23027efe40b629e9ffd | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/dynamic.lean | 0361ed7eba7455d0287f4cd3b3f151b0a3ae45be | [
"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 | 288 | lean | import Std
open Std
deriving instance TypeName for Nat
deriving instance TypeName for String
example : (Dynamic.mk 42).get? String = none := by native_decide
example : (Dynamic.mk 42).get? Nat = some 42 := by native_decide
example : (Dynamic.mk 42).typeName = ``Nat := by native_decide
|
337dc2b3476b6c0078e56069f7e1943857bc92fb | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/coeffs.lean | 654538ea9fadd7a033f1e7995ca5965d6790a3a5 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,723 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.list.func
import Mathlib.tactic.ring
import Mathlib.tactic.omega.misc
import Mathlib.PostPort
namespace Mathlib
/-
Non-constant terms of linear constraints are represented
by storing their coefficients in integer lists.
-/
namespace omega
namespace coeffs
/-- `val_between v as l o` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping all
subterms that include variables outside the range `[l,l+o)` -/
@[simp] def val_between (v : ℕ → ℤ) (as : List ℤ) (l : ℕ) : ℕ → ℤ :=
sorry
@[simp] theorem val_between_nil {v : ℕ → ℤ} {l : ℕ} (m : ℕ) : val_between v [] l m = 0 := sorry
/-- Evaluation of the nonconstant component of a normalized linear arithmetic term. -/
def val (v : ℕ → ℤ) (as : List ℤ) : ℤ :=
val_between v as 0 (list.length as)
@[simp] theorem val_nil {v : ℕ → ℤ} : val v [] = 0 :=
rfl
theorem val_between_eq_of_le {v : ℕ → ℤ} {as : List ℤ} {l : ℕ} (m : ℕ) : list.length as ≤ l + m → val_between v as l m = val_between v as l (list.length as - l) := sorry
theorem val_eq_of_le {v : ℕ → ℤ} {as : List ℤ} {k : ℕ} : list.length as ≤ k → val v as = val_between v as 0 k := sorry
theorem val_between_eq_val_between {v : ℕ → ℤ} {w : ℕ → ℤ} {as : List ℤ} {bs : List ℤ} {l : ℕ} {m : ℕ} : (∀ (x : ℕ), l ≤ x → x < l + m → v x = w x) →
(∀ (x : ℕ), l ≤ x → x < l + m → list.func.get x as = list.func.get x bs) → val_between v as l m = val_between w bs l m := sorry
theorem val_between_set {v : ℕ → ℤ} {a : ℤ} {l : ℕ} {n : ℕ} {m : ℕ} : l ≤ n → n < l + m → val_between v (list.func.set a [] n) l m = a * v n := sorry
@[simp] theorem val_set {v : ℕ → ℤ} {m : ℕ} {a : ℤ} : val v (list.func.set a [] m) = a * v m := sorry
theorem val_between_neg {v : ℕ → ℤ} {as : List ℤ} {l : ℕ} {o : ℕ} : val_between v (list.func.neg as) l o = -val_between v as l o := sorry
@[simp] theorem val_neg {v : ℕ → ℤ} {as : List ℤ} : val v (list.func.neg as) = -val v as := sorry
theorem val_between_add {v : ℕ → ℤ} {is : List ℤ} {js : List ℤ} {l : ℕ} (m : ℕ) : val_between v (list.func.add is js) l m = val_between v is l m + val_between v js l m := sorry
@[simp] theorem val_add {v : ℕ → ℤ} {is : List ℤ} {js : List ℤ} : val v (list.func.add is js) = val v is + val v js := sorry
theorem val_between_sub {v : ℕ → ℤ} {is : List ℤ} {js : List ℤ} {l : ℕ} (m : ℕ) : val_between v (list.func.sub is js) l m = val_between v is l m - val_between v js l m := sorry
@[simp] theorem val_sub {v : ℕ → ℤ} {is : List ℤ} {js : List ℤ} : val v (list.func.sub is js) = val v is - val v js := sorry
/-- `val_except k v as` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping the
subterm that includes the `k`th variable. -/
def val_except (k : ℕ) (v : ℕ → ℤ) (as : List ℤ) : ℤ :=
val_between v as 0 k + val_between v as (k + 1) (list.length as - (k + 1))
theorem val_except_eq_val_except {k : ℕ} {is : List ℤ} {js : List ℤ} {v : ℕ → ℤ} {w : ℕ → ℤ} : (∀ (x : ℕ), x ≠ k → v x = w x) →
(∀ (x : ℕ), x ≠ k → list.func.get x is = list.func.get x js) → val_except k v is = val_except k w js := sorry
theorem val_except_update_set {v : ℕ → ℤ} {n : ℕ} {as : List ℤ} {i : ℤ} {j : ℤ} : val_except n (update n i v) (list.func.set j as n) = val_except n v as :=
val_except_eq_val_except update_eq_of_ne (list.func.get_set_eq_of_ne n)
theorem val_between_add_val_between {v : ℕ → ℤ} {as : List ℤ} {l : ℕ} {m : ℕ} {n : ℕ} : val_between v as l m + val_between v as (l + m) n = val_between v as l (m + n) := sorry
theorem val_except_add_eq {v : ℕ → ℤ} (n : ℕ) {as : List ℤ} : val_except n v as + list.func.get n as * v n = val v as := sorry
@[simp] theorem val_between_map_mul {v : ℕ → ℤ} {i : ℤ} {as : List ℤ} {l : ℕ} {m : ℕ} : val_between v (list.map (Mul.mul i) as) l m = i * val_between v as l m := sorry
theorem forall_val_dvd_of_forall_mem_dvd {i : ℤ} {as : List ℤ} : (∀ (x : ℤ), x ∈ as → i ∣ x) → ∀ (n : ℕ), i ∣ list.func.get n as :=
fun (ᾰ : ∀ (x : ℤ), x ∈ as → i ∣ x) (n : ℕ) =>
idRhs ((fun (x : ℤ) => i ∣ x) (list.func.get n as)) (list.func.forall_val_of_forall_mem (dvd_zero i) ᾰ n)
theorem dvd_val_between {v : ℕ → ℤ} {i : ℤ} {as : List ℤ} {l : ℕ} {m : ℕ} : (∀ (x : ℤ), x ∈ as → i ∣ x) → i ∣ val_between v as l m := sorry
theorem dvd_val {v : ℕ → ℤ} {as : List ℤ} {i : ℤ} : (∀ (x : ℤ), x ∈ as → i ∣ x) → i ∣ val v as :=
dvd_val_between
@[simp] theorem val_between_map_div {v : ℕ → ℤ} {as : List ℤ} {i : ℤ} {l : ℕ} (h1 : ∀ (x : ℤ), x ∈ as → i ∣ x) {m : ℕ} : val_between v (list.map (fun (x : ℤ) => x / i) as) l m = val_between v as l m / i := sorry
@[simp] theorem val_map_div {v : ℕ → ℤ} {as : List ℤ} {i : ℤ} : (∀ (x : ℤ), x ∈ as → i ∣ x) → val v (list.map (fun (x : ℤ) => x / i) as) = val v as / i := sorry
theorem val_between_eq_zero {v : ℕ → ℤ} {is : List ℤ} {l : ℕ} {m : ℕ} : (∀ (x : ℤ), x ∈ is → x = 0) → val_between v is l m = 0 := sorry
theorem val_eq_zero {v : ℕ → ℤ} {is : List ℤ} : (∀ (x : ℤ), x ∈ is → x = 0) → val v is = 0 :=
val_between_eq_zero
|
1fd29a302b4859db471226534a04b6c98887d475 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/measure_theory/borel_space.lean | e1deb81427daaed5eb2f7c45dd19ad80c4087e32 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 26,050 | 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
Borel (measurable) space -- the smallest σ-algebra generated by open sets
It would be nice to encode this in the topological space type class, i.e. each topological space
carries a measurable space, the Borel space. This would be similar how each uniform space carries a
topological space. The idea is to allow definitional equality for product instances.
We would like to have definitional equality for
borel t₁ × borel t₂ = borel (t₁ × t₂)
Unfortunately, this only holds if t₁ and t₂ are second-countable topologies.
-/
import measure_theory.measurable_space topology.instances.ennreal analysis.normed_space.basic
noncomputable theory
open classical set lattice real
open_locale classical
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α}
open measurable_space topological_space
@[instance, priority 900] def borel (α : Type u) [topological_space α] : measurable_space α :=
generate_from {s : set α | is_open s}
lemma borel_eq_generate_from_of_subbasis {s : set (set α)}
[t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) :
borel α = generate_from s :=
le_antisymm
(generate_from_le $ assume u (hu : t.is_open u),
begin
rw [hs] at hu,
induction hu,
case generate_open.basic : u hu
{ exact generate_measurable.basic u hu },
case generate_open.univ
{ exact @is_measurable.univ α (generate_from s) },
case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂
{ exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ },
case generate_open.sUnion : f hf ih {
rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩,
rw ← vu,
exact @is_measurable.sUnion α (generate_from s) _ hv
(λ x xv, ih _ (vf xv)) }
end)
(generate_from_le $ assume u hu, generate_measurable.basic _ $
show t.is_open u, by rw [hs]; exact generate_open.basic _ hu)
lemma borel_eq_generate_Iio (α)
[topological_space α] [second_countable_topology α]
[linear_order α] [orderable_topology α] :
borel α = generate_from (range Iio) :=
begin
refine le_antisymm _ (generate_from_le _),
{ rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α),
have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) :=
λ a, generate_measurable.basic _ ⟨_, rfl⟩,
refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H],
by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b,
{ rcases h with ⟨a', ha'⟩,
rw (_ : Ioi a = -Iio a'), {exact (H _).compl _},
simp [set.ext_iff, ha'] },
{ rcases is_open_Union_countable
(λ a' : {a' : α // a < a'}, {b | a'.1 < b})
(λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩,
simp [set.ext_iff] at vu,
have : Ioi a = ⋃ x : v, -Iio x.1.1,
{ simp [set.ext_iff],
refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩,
rcases (vu x).2 _ with ⟨a', h₁, h₂⟩,
{ exact ⟨a', h₁, le_of_lt h₂⟩ },
refine not_imp_comm.1 (λ h, _) h,
exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩),
lt_of_lt_of_le ax⟩⟩ },
rw this, resetI,
apply is_measurable.Union,
exact λ _, (H _).compl _ } },
{ simp, rintro _ a rfl,
exact generate_measurable.basic _ is_open_Iio }
end
lemma borel_eq_generate_Ioi (α)
[topological_space α] [second_countable_topology α]
[linear_order α] [orderable_topology α] :
borel α = generate_from (range (λ a, {x | a < x})) :=
begin
refine le_antisymm _ (generate_from_le _),
{ rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α),
have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} :=
λ a, generate_measurable.basic _ ⟨_, rfl⟩,
refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H},
by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a',
{ rcases h with ⟨a', ha'⟩,
rw (_ : Iio a = -Ioi a'), {exact (H _).compl _},
simp [set.ext_iff, ha'] },
{ rcases is_open_Union_countable
(λ a' : {a' : α // a' < a}, {b | b < a'.1})
(λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩,
simp [set.ext_iff] at vu,
have : Iio a = ⋃ x : v, -Ioi x.1.1,
{ simp [set.ext_iff],
refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩,
rcases (vu x).2 _ with ⟨a', h₁, h₂⟩,
{ exact ⟨a', h₁, le_of_lt h₂⟩ },
refine not_imp_comm.1 (λ h, _) h,
exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩),
λ h, lt_of_le_of_lt h ax⟩⟩ },
rw this, resetI,
apply is_measurable.Union,
exact λ _, (H _).compl _ } },
{ simp, rintro _ a rfl,
exact generate_measurable.basic _ (is_open_lt' _) }
end
lemma borel_comap {f : α → β} {t : topological_space β} :
@borel α (t.induced f) = (@borel β t).comap f :=
calc @borel α (t.induced f) =
measurable_space.generate_from (preimage f '' {s | is_open s }) :
congr_arg measurable_space.generate_from $ set.ext $ assume s : set α,
show (t.induced f).is_open s ↔ s ∈ preimage f '' {s | is_open s},
by simp [topological_space.induced, set.image, eq_comm]; refl
... = (@borel β t).comap f : comap_generate_from.symm
section
variables [topological_space α]
lemma is_measurable_of_is_open : is_open s → is_measurable s := generate_measurable.basic s
lemma is_measurable_interior : is_measurable (interior s) :=
is_measurable_of_is_open is_open_interior
lemma is_measurable_ball [metric_space β] {x : β} {ε : ℝ} : is_measurable (metric.ball x ε) :=
is_measurable_of_is_open metric.is_open_ball
lemma is_measurable_of_is_closed (h : is_closed s) : is_measurable s :=
is_measurable.compl_iff.1 $ is_measurable_of_is_open h
lemma is_measurable_singleton [t1_space α] {x : α} : is_measurable ({x} : set α) :=
is_measurable_of_is_closed is_closed_singleton
lemma is_measurable_closure : is_measurable (closure s) :=
is_measurable_of_is_closed is_closed_closure
lemma measurable_of_continuous [topological_space β] {f : α → β} (h : continuous f) :
measurable f :=
measurable_generate_from $ assume t ht, is_measurable_of_is_open $ h t ht
lemma borel_prod_le [topological_space β] :
prod.measurable_space ≤ borel (α × β) :=
sup_le
(comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_fst)
(comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_snd)
lemma borel_induced {α β} [t : topological_space β] (f : α → β) :
@borel α (t.induced f) = (borel β).comap f :=
comap_generate_from.symm
lemma borel_eq_subtype (s : set α) : borel s = subtype.measurable_space :=
borel_induced coe
lemma borel_prod [second_countable_topology α] [topological_space β] [second_countable_topology β] :
prod.measurable_space = borel (α × β) :=
let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := @is_open_generated_countable_inter α _ _ in
let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := @is_open_generated_countable_inter β _ _ in
le_antisymm borel_prod_le begin
have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v},
{ rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ },
rw [borel_eq_generate_from_of_subbasis this],
exact generate_from_le (assume p ⟨u, hu, v, hv, eq⟩,
have hu : is_open u, by rw [ha₅]; exact generate_open.basic _ hu,
have hv : is_open v, by rw [hb₅]; exact generate_open.basic _ hv,
eq.symm ▸ is_measurable_set_prod (is_measurable_of_is_open hu) (is_measurable_of_is_open hv))
end
lemma measurable_of_continuous2 {α β γ}
[topological_space α] [second_countable_topology α]
[topological_space β] [second_countable_topology β]
[topological_space γ] [measurable_space δ] {f : δ → α} {g : δ → β} {c : α → β → γ}
(h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) :
measurable (λa, c (f a) (g a)) :=
show measurable ((λp:α×β, c p.1 p.2) ∘ (λa, (f a, g a))),
begin
apply measurable.comp,
{ rw borel_prod,
exact measurable_of_continuous h },
{ exact measurable.prod_mk hf hg }
end
lemma measurable.add
[add_monoid α] [topological_add_monoid α] [second_countable_topology α] [measurable_space β]
{f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a + g a) :=
measurable_of_continuous2 continuous_add
lemma measurable_finset_sum {ι : Type*}
[add_comm_monoid α] [topological_add_monoid α] [second_countable_topology α] [measurable_space β]
{f : ι → β → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, s.sum (λi, f i a)) :=
finset.induction_on s
(by simpa using measurable_const)
(assume i s his ih, by simpa [his] using measurable.add (hf i) ih)
lemma measurable.neg
[add_group α] [topological_add_group α] [measurable_space β] {f : β → α}
(hf : measurable f) : measurable (λa, - f a) :=
(measurable_of_continuous continuous_neg).comp hf
lemma measurable_neg_iff
[add_group α] [topological_add_group α] [measurable_space β] (f : β → α) :
measurable (-f) ↔ measurable f :=
iff.intro
begin
assume h,
have := measurable.neg h,
convert this,
funext,
simp only [pi.neg_apply, _root_.neg_neg]
end
$ measurable.neg
lemma measurable.sub
[add_group α] [topological_add_group α] [second_countable_topology α] [measurable_space β]
{f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a - g a) :=
measurable_of_continuous2 continuous_sub
lemma measurable.mul
[monoid α] [topological_monoid α] [second_countable_topology α] [measurable_space β]
{f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a * g a) :=
measurable_of_continuous2 continuous_mul
lemma is_measurable_le {α β}
[topological_space α] [partial_order α] [ordered_topology α] [second_countable_topology α]
[measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) :
is_measurable {a | f a ≤ g a} :=
have is_measurable {p : α × α | p.1 ≤ p.2},
by rw borel_prod; exact is_measurable_of_is_closed (ordered_topology.is_closed_le' _),
show is_measurable {a | (f a, g a).1 ≤ (f a, g a).2},
begin
refine measurable.preimage _ this,
exact measurable.prod_mk hf hg
end
lemma measurable.max {α β}
[topological_space α] [decidable_linear_order α] [ordered_topology α] [second_countable_topology α]
[measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λa, max (f a) (g a)) :=
measurable.if (is_measurable_le hf hg) hg hf
lemma measurable.min {α β}
[topological_space α] [decidable_linear_order α] [ordered_topology α] [second_countable_topology α]
[measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λa, min (f a) (g a)) :=
measurable.if (is_measurable_le hf hg) hf hg
-- generalize
lemma measurable_coe_int_real : measurable (λa, a : ℤ → ℝ) :=
assume s (hs : is_measurable s), by trivial
section ordered_topology
variables [linear_order α] [ordered_topology α] {a b c : α}
lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_measurable_of_is_open is_open_Ioo
lemma is_measurable_Iio : is_measurable (Iio a) := is_measurable_of_is_open is_open_Iio
lemma is_measurable_Ico : is_measurable (Ico a b) :=
(is_measurable_of_is_closed $ is_closed_le continuous_const continuous_id).inter
is_measurable_Iio
end ordered_topology
lemma measurable.is_lub {α} [topological_space α] [linear_order α]
[orderable_topology α] [second_countable_topology α]
{β} [measurable_space β] {ι} [encodable ι]
{f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
rw borel_eq_generate_Ioi α,
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
have : {b | a < g b} = ⋃ i, {b | a < f i b},
{ simp [set.ext_iff], intro b, rw [lt_is_lub_iff (hg b)],
exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ },
show is_measurable {b | a < g b}, rw this,
exact is_measurable.Union (λ i, hf i _
(is_measurable_of_is_open (is_open_lt' _)))
end
lemma measurable.is_glb {α} [topological_space α] [linear_order α]
[orderable_topology α] [second_countable_topology α]
{β} [measurable_space β] {ι} [encodable ι]
{f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
rw borel_eq_generate_Iio α,
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
have : {b | g b < a} = ⋃ i, {b | f i b < a},
{ simp [set.ext_iff], intro b, rw [is_glb_lt_iff (hg b)],
exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ },
show is_measurable {b | g b < a}, rw this,
exact is_measurable.Union (λ i, hf i _
(is_measurable_of_is_open (is_open_gt' _)))
end
lemma measurable.supr {α} [topological_space α] [complete_linear_order α]
[orderable_topology α] [second_countable_topology α]
{β} [measurable_space β] {ι} [encodable ι]
{f : ι → β → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨆ i, f i b) :=
measurable.is_lub hf $ λ b, is_lub_supr
lemma measurable.infi {α} [topological_space α] [complete_linear_order α]
[orderable_topology α] [second_countable_topology α]
{β} [measurable_space β] {ι} [encodable ι]
{f : ι → β → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨅ i, f i b) :=
measurable.is_glb hf $ λ b, is_glb_infi
lemma measurable.supr_Prop {α} [topological_space α] [complete_linear_order α]
{β} [measurable_space β] {p : Prop} {f : β → α} (hf : measurable f) :
measurable (λ b, ⨆ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact supr_pos h end)
(assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end)
lemma measurable.infi_Prop {α} [topological_space α] [complete_linear_order α]
{β} [measurable_space β] {p : Prop} {f : β → α} (hf : measurable f) :
measurable (λ b, ⨅ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact infi_pos h end )
(assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end)
end
def homemorph.to_measurable_equiv [topological_space α] [topological_space β] (h : α ≃ₜ β) :
measurable_equiv α β :=
{ to_equiv := h.to_equiv,
measurable_to_fun := measurable_of_continuous h.continuous_to_fun,
measurable_inv_fun := measurable_of_continuous h.continuous_inv_fun }
namespace real
open measurable_space
lemma borel_eq_generate_from_Ioo_rat :
borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2
lemma borel_eq_generate_from_Iio_rat :
borel ℝ = generate_from (⋃a:ℚ, {Iio a}) :=
begin
let g, swap,
apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)),
{ rw borel_eq_generate_from_Ioo_rat,
refine generate_from_le (λ t, _),
simp only [mem_Union], rintro ⟨a, b, h, rfl|⟨⟨⟩⟩⟩,
rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, - Iio c) ∩ Iio b),
{ have hg : ∀q:ℚ, g.is_measurable (Iio q) :=
λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩),
refine @is_measurable.inter _ g _ _ _ (hg _),
refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _),
exact @is_measurable.compl _ _ g (hg _) },
{ simp [Ioo, Iio],
refine and_congr _ iff.rfl,
exact ⟨λ h,
let ⟨c, ac, cx⟩ := exists_rat_btwn h in
⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩,
λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } },
{ simp, rintro r rfl,
exact is_measurable_of_is_open (is_open_gt' _) }
end
end real
namespace nnreal
open filter
lemma measurable.add [measurable_space α] {f : α → nnreal} {g : α → nnreal} :
measurable f → measurable g → measurable (λa, f a + g a) :=
measurable_of_continuous2 continuous_add
lemma measurable.sub [measurable_space α] {f g: α → nnreal}
(hf : measurable f) (hg : measurable g) : measurable (λ a, f a - g a) :=
measurable_of_continuous2 continuous_sub hf hg
lemma measurable.mul [measurable_space α] {f : α → nnreal} {g : α → nnreal} :
measurable f → measurable g → measurable (λa, f a * g a) :=
measurable_of_continuous2 continuous_mul
lemma measurable_of_real : measurable nnreal.of_real :=
measurable_of_continuous nnreal.continuous_of_real
end nnreal
namespace ennreal
open filter
lemma measurable_coe : measurable (coe : nnreal → ennreal) :=
measurable_of_continuous (continuous_coe.2 continuous_id)
def ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r < ⊤} nnreal :=
{ to_fun := λr, ennreal.to_nnreal r.1,
inv_fun := λr, ⟨r, coe_lt_top⟩,
left_inv := assume ⟨r, hr⟩, by simp [coe_to_nnreal (ne_of_lt hr)],
right_inv := assume r, to_nnreal_coe,
measurable_to_fun :=
begin
rw [← borel_eq_subtype],
refine measurable_of_continuous (continuous_iff_continuous_at.2 _),
rintros ⟨r, hr⟩,
simp [continuous_at, nhds_subtype_eq_comap],
refine tendsto.comp (tendsto_to_nnreal (ne_of_lt hr)) tendsto_comap
end,
measurable_inv_fun := measurable.subtype_mk measurable_coe }
lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α}
(h : measurable (λp:nnreal, f p)) : measurable f :=
begin
refine measurable_of_measurable_union_cover {⊤} {r : ennreal | r < ⊤}
(is_measurable_of_is_closed $ is_closed_singleton)
(is_measurable_of_is_open $ is_open_gt' _)
(assume r _, by cases r; simp [ennreal.none_eq_top, ennreal.some_eq_coe])
_
_,
exact (measurable_equiv.set.singleton ⊤).symm.measurable_coe_iff.1 (measurable_unit _),
exact (ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h)
end
def ennreal_equiv_sum :
@measurable_equiv ennreal (nnreal ⊕ unit) _ sum.measurable_space :=
{ to_fun :=
@option.rec nnreal (λ_, nnreal ⊕ unit) (sum.inr ()) (sum.inl : nnreal → nnreal ⊕ unit),
inv_fun :=
@sum.rec nnreal unit (λ_, ennreal) (coe : nnreal → ennreal) (λ_, ⊤),
left_inv := assume s, by cases s; refl,
right_inv := assume s, by rcases s with r | ⟨⟨⟩⟩; refl,
measurable_to_fun := measurable_of_measurable_nnreal measurable_inl,
measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤) }
lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β]
(f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal}
(h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2))
(h₂ : measurable (λr:nnreal, f ⊤ r))
(h₃ : measurable (λr:nnreal, f r ⊤))
(hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) :=
let e : measurable_equiv (ennreal × ennreal)
(((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) :=
(measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans
(measurable_equiv.sum_prod_sum _ _ _ _) in
have measurable (λp:ennreal×ennreal, f p.1 p.2),
begin
refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)),
{ show measurable (λp:nnreal × nnreal, f p.1 p.2),
exact h₁ },
{ show measurable (λp:nnreal × unit, f p.1 ⊤),
exact h₃.comp (measurable.fst measurable_id) },
{ show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)),
exact h₂.comp (measurable.snd measurable_id) },
{ show measurable (λp:unit × unit, f ⊤ ⊤),
exact measurable_const }
end,
this.comp (measurable.prod_mk hg hh)
lemma measurable.mul {α : Type*} [measurable_space α] {f g : α → ennreal} :
measurable f → measurable g → measurable (λa, f a * g a) :=
begin
refine measurable_of_measurable_nnreal_nnreal (*) _ _ _,
{ simp only [ennreal.coe_mul.symm],
exact measurable_coe.comp
(measurable.mul (measurable.fst measurable_id) (measurable.snd measurable_id)) },
{ simp [top_mul],
exact measurable.if
(is_measurable_of_is_closed $ is_closed_eq continuous_id continuous_const)
measurable_const
measurable_const },
{ simp [mul_top],
exact measurable.if
(is_measurable_of_is_closed $ is_closed_eq continuous_id continuous_const)
measurable_const
measurable_const }
end
lemma measurable.add {α : Type*} [measurable_space α] {f g : α → ennreal} :
measurable f → measurable g → measurable (λa, f a + g a) :=
begin
refine measurable_of_measurable_nnreal_nnreal (+) _ _ _,
{ simp only [ennreal.coe_add.symm],
exact measurable_coe.comp
(measurable.add (measurable.fst measurable_id) (measurable.snd measurable_id)) },
{ simp [measurable_const] },
{ simp [measurable_const] }
end
lemma measurable.sub {α : Type*} [measurable_space α] {f g : α → ennreal} :
measurable f → measurable g → measurable (λa, f a - g a) :=
begin
refine measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _,
{ simp only [ennreal.coe_sub.symm],
exact measurable_coe.comp
(nnreal.measurable.sub (measurable.fst measurable_id) (measurable.snd measurable_id)) },
{ simp [measurable_const] },
{ simp [measurable_const] }
end
lemma measurable_of_real : measurable ennreal.of_real :=
measurable_of_continuous ennreal.continuous_of_real
end ennreal
namespace measure_theory
open topological_space
lemma measurable_smul' {α : Type*} {β : Type*} {γ : Type*}
[semiring α] [topological_space α] [second_countable_topology α]
[topological_space β] [add_comm_monoid β] [second_countable_topology β]
[semimodule α β] [topological_semimodule α β] [measurable_space γ]
{f : γ → α} {g : γ → β} (hf : measurable f) (hg : measurable g) :
measurable (λ c, f c • g c) :=
measurable_of_continuous2 (continuous_fst.smul continuous_snd) hf hg
lemma measurable_smul {α : Type*} {β : Type*} {γ : Type*}
[semiring α] [topological_space α]
[topological_space β] [add_comm_monoid β]
[semimodule α β] [topological_semimodule α β] [measurable_space γ]
(c : α) {f : γ → β} (hf : measurable f) : measurable (λ x, c • f x) :=
measurable.comp (measurable_of_continuous (continuous_const.smul continuous_id)) hf
lemma measurable_smul_iff {α : Type*} {β : Type*} {γ : Type*}
[division_ring α] [topological_space α]
[topological_space β] [add_comm_monoid β]
[semimodule α β] [topological_semimodule α β] [measurable_space γ]
{c : α} (hc : c ≠ 0) (f : γ → β) : measurable (λ x, c • f x) ↔ measurable f :=
iff.intro
begin
assume h,
have eq : (λ (x : γ), c⁻¹ • (λ (x : γ), c • f x) x) = f,
{ funext, rw [smul_smul, inv_mul_cancel hc, one_smul] },
have := measurable_smul c⁻¹ h,
rwa eq at this
end
$ measurable_smul c
lemma measurable_dist' {α : Type*} [metric_space α] [second_countable_topology α] :
measurable (λp:α×α, dist p.1 p.2) :=
begin
rw [borel_prod],
apply measurable_of_continuous,
exact continuous_dist continuous_fst continuous_snd
end
lemma measurable_dist {α : Type*} [metric_space α] [second_countable_topology α]
[measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, dist (f b) (g b)) :=
measurable.comp measurable_dist' (measurable.prod_mk hf hg)
lemma measurable_nndist' {α : Type*} [metric_space α] [second_countable_topology α] :
measurable (λp:α×α, nndist p.1 p.2) :=
begin
rw [borel_prod],
apply measurable_of_continuous,
exact continuous_nndist continuous_fst continuous_snd
end
lemma measurable_nndist {α : Type*} [metric_space α] [second_countable_topology α]
[measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, nndist (f b) (g b)) :=
measurable.comp measurable_nndist' (measurable.prod_mk hf hg)
lemma measurable_edist' {α : Type*} [emetric_space α] [second_countable_topology α] :
measurable (λp:α×α, edist p.1 p.2) :=
begin
rw [borel_prod],
apply measurable_of_continuous,
exact continuous_edist continuous_fst continuous_snd
end
lemma measurable_edist {α : Type*} [emetric_space α] [second_countable_topology α]
[measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, edist (f b) (g b)) :=
measurable.comp measurable_edist' (measurable.prod_mk hf hg)
lemma measurable_norm' {α : Type*} [normed_group α] : measurable (norm : α → ℝ) :=
measurable_of_continuous continuous_norm
lemma measurable_norm {α : Type*} [normed_group α] [measurable_space β]
{f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) :=
measurable.comp measurable_norm' hf
lemma measurable_nnnorm' {α : Type*} [normed_group α] : measurable (nnnorm : α → nnreal) :=
measurable_of_continuous continuous_nnnorm
lemma measurable_nnnorm {α : Type*} [normed_group α] [measurable_space β]
{f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) :=
measurable.comp measurable_nnnorm' hf
lemma measurable_coe_nnnorm {α : Type*} [normed_group α] [measurable_space β]
{f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) :=
measurable.comp ennreal.measurable_coe $ measurable_nnnorm hf
end measure_theory
|
b8862b686244d66be17281cac0d87fdbe8fd0c03 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/meta/tactic.lean | f8a512b619696d865029041d2b231791c2218d76 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,309 | 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.function init.data.option.basic init.util
import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail
import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment
import init.meta.pexpr init.data.to_string init.data.string.basic init.meta.interaction_monad
meta constant tactic_state : Type
universes u v
namespace tactic_state
meta constant env : tactic_state → environment
meta constant to_format : tactic_state → format
/- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s)^.to_string s^.get_options⟩
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (hiding failed fail)
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ interaction_monad.monad with
failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _ }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace tactic
variables {α : Type u}
meta def try_core (t : tactic α) : tactic (option α) :=
λ s, result.cases_on (t s)
(λ a, success (some a))
(λ e ref s', success none s)
meta def skip : tactic unit :=
success ()
meta def try (t : tactic α) : tactic unit :=
try_core t >>[tactic] skip
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit :=
λ s, result.cases_on (t s)
(λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s)
(λ e ref s', success () s)
open nat
/- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/
meta def repeat_at_most : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := (do t, repeat_at_most n t) <|> skip
/- (repeat_exactly n t) : execute t n times -/
meta def repeat_exactly : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do t, repeat_exactly n t
meta def repeat : tactic unit → tactic unit :=
repeat_at_most 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/- Decorate t's exceptions with msg -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
meta def get_options : tactic options :=
do s ← read, return s^.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s^.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception .α f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨fmap to_fmt ∘ monad.mapm pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s)^.get n
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
take state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : tactic α) : tactic α :=
λ s, timeit desc (t s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
inductive transparency
| all | semireducible | reducible | none
export transparency (reducible semireducible)
/- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'.
'α' must be a closed term.
'α_as_expr' is synthesized by the code generator.
'e' must be a closed expression at runtime. -/
meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α
/- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
meta constant rename : name → name → tactic unit
/- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting. -/
meta constant whnf (e : expr) (md := semireducible) : tactic expr
/- (head) eta expand the given expression -/
meta constant head_eta_expand : expr → tactic expr
/- (head) beta reduction -/
meta constant head_beta : expr → tactic expr
/- (head) zeta reduction -/
meta constant head_zeta : expr → tactic expr
/- zeta reduction -/
meta constant zeta : expr → tactic expr
/- (head) eta reduction -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) : tactic unit
/- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit
/- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
meta constant get_local : name → tactic expr
/- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic expr
/- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
meta constant get_unused_name : name → option nat → tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} (a > b) (nat.decidable_gt a b) nat a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/- Given a local constant t, if t has type (lhs = rhs) apply susbstitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst : expr → tactic unit
/-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals.
If `report_errors` is ff, then errors are reported using position information from q. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (report_errors := ff) : tactic expr
/- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/- Change the target of the main goal.
The input expression must be definitionally equal to the current target. -/
meta constant change : expr → tactic unit
/- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/
meta constant assert_core : name → expr → tactic unit
/- (assertv_core H T P), change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/
meta constant define_core : name → expr → tactic unit
/- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/- rotate goals to the left -/
meta constant rotate_left : nat → tactic unit
meta constant get_goals : tactic (list expr)
meta constant set_goals : list expr → tactic unit
/-- Configuration options for the `apply` tactic. -/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(all := ff)
(use_instances := tt)
/-- Apply the expression `e` to the main goal,
the unification is performed using the transparency mode in `cfg`.
If cfg^.approx is `tt`, then fallback to first-order unification, and approximate context during unification.
If cfg^.all is `tt`, then all unassigned meta-variables are added as new goals.
If cfg^.use_instances is `tt`, then use type class resolution to instantiate unassigned meta-variables.
It returns a list of all introduced meta variables, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr)
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
meta constant mk_fresh_name : tactic name
/- Return a hash code for expr that ignores inst_implicit arguments,
and proofs. -/
meta constant abstract_hash : expr → tactic nat
/- Return the "weight" of the given expr while ignoring inst_implicit arguments,
and proofs. -/
meta constant abstract_weight : expr → tactic nat
meta constant abstract_eq : expr → expr → tactic bool
/- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr)))
/- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/- (doc_string env d k) return the doc string for d (if available) -/
meta constant doc_string : name → tactic string
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
meta constant module_doc_strings : tactic (list (option name × string))
/- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/- (unset_attribute attr_name c_name) -/
meta constant unset_attribute : name → name → tactic unit
/- (has_attribute attr_name c_name) succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority. -/
meta constant has_attribute : name → name → tactic nat
/- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src` -/
meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit :=
try $ do
prio ← has_attribute attr_name src,
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/- (save_type_info e ref) save (typeof e) at position associated with ref -/
meta constant save_type_info : expr → expr → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
meta constant report_error : nat → nat → format → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
open list nat
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line : nat) (col : nat) (t : tactic α) : tactic unit :=
λ s, @scope_trace _ line col ((t >>[tactic] cleanup) s)
meta def report_exception {α : Type} (line col : nat) : option (unit → format) → tactic α
| (some msg_thunk) := λ s,
let msg := msg_thunk () ++ format.line ++ to_fmt "state:" ++ format.line ++ s^.to_format in
(tactic.report_error line col msg >> silent_fail) s
| none := silent_fail
/- Auxiliary definition used to implement begin ... end blocks.
It is similar to step, but it reports an error at the given line/col if the tactic t fails. -/
meta def rstep {α : Type u} (line : nat) (col : nat) (t : tactic α) : tactic unit :=
λ s, result.cases_on (istep line col t s)
(λ a new_s, result.success () new_s)
(λ msg_thunk e, report_exception line col msg_thunk)
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = ```(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env^.get n,
t ← return $ d^.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
meta def intro1 : tactic expr :=
intro `_
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
meta def intro_lst : list name → tactic (list expr)
| [] := return []
| (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs)
meta def to_expr_strict (q : pexpr) (report_errors := ff) : tactic expr :=
to_expr q report_errors
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e^.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
/- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := show p, by assumption
/- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/
meta def assert (h : name) (t : expr) : tactic unit :=
assert_core h t >> swap >> intro h >> swap
/- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic unit :=
assertv_core h t v >> intro h >> return ()
/- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/
meta def define (h : name) (t : expr) : tactic unit :=
define_core h t >> swap >> intro h >> swap
/- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic unit :=
definev_core h t v >> intro h >> return ()
/- Add (h : t := pr) to the current goal -/
meta def pose (h : name) (pr : expr) : tactic unit :=
do t ← infer_type pr,
definev h t pr
/- Add (h : t) to the current goal, given a proof (pr : t) -/
meta def note (n : name) (pr : expr) : tactic unit :=
do t ← infer_type pr,
assertv n t pr
/- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/- We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
meta def rotate : nat → tactic unit :=
rotate_left
/- first [t_1, ..., t_n] applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
match gs with
| [] := fail "focus tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs
| gs := fail "focus tactic failed, focused goal has not been solved"
end
end
/- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/
meta def solve (ts : list (tactic unit)) : tactic unit :=
first $ map solve1 ts
private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] gs rs := set_goals $ rs ++ gs
| (t::ts) (g::gs) rs := do
set_goals [g], t, rs' ← get_goals,
focus_aux ts gs (rs ++ rs')
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
/- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/
meta def focus (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals_core gs (ac ++ new_gs)
/- Apply the given tactic to all goals. -/
meta def all_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals_core gs (ac ++ new_gs) (succeeded^.is_some || progress)
/- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals_core tac gs [] ff
/- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance : has_andthen (tactic unit) :=
⟨seq⟩
meta constant is_trace_enabled_for : name → bool
/- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/- Fail if there are unsolved goals. -/
meta def now : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "now tactic failed, there are unsolved goals")
meta def apply (e : expr) : tactic unit :=
apply_core e >> return ()
meta def fapply (e : expr) : tactic unit :=
apply_core e {all := tt} >> return ()
/- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env^.get c,
let num := decl^.univ_params^.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) : tactic unit :=
mk_const c >>= apply
meta def save_const_type_info (n : name) (ref : expr) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/- Create a fresh universe ?u, a metavariable (?T : Type.{?u}),
and return metavariable (?M : ?T).
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : name) : tactic expr :=
do tgt : expr ← target,
(match_not tgt >> return ())
<|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply)
<|>
fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)",
intro H
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit :=
if e^.is_local_constant then
cases_core e ids md >> return ()
else do
x ← mk_fresh_name,
n ← revert_kdependencies e dmd,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
(step (cases_core h ids md); intron n)
meta def refine (e : pexpr) (report_errors := ff) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt report_errors >>= exact
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ to_string i) in
if ¬env^.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns^.any (λ n, n^.is_prefix_of d) && env^.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/-
Define id_locked using meta-programming because we don't have
syntax for setting reducibility_hints.
See module init.meta.declaration.
Remark: id_locked is used in the builtin implementation of tactic.change
-/
run_cmd do
let l := level.param `l,
let Ty := expr.sort l,
type ← to_expr ``(Π (α : %%Ty), α → α),
val ← to_expr ``(λ (α : %%Ty) (a : α), a),
add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt)
lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a :=
rfl
|
f55f8443956e773e1a7766f8cc4c35a3186c43c3 | ba4ad8a778c69640c9cca8e5dcaeb40d4a10fa10 | /lean4/Bin/Main.lean | a25bce5c4257d633a01a27731fe1217aa8fb00ac | [] | no_license | tangentstorm/tangentlabs | 390ac60618bd913b567d20933dab70b84aac7151 | 137adbba6e7c35f8bb54b0786ada6c8c2ff6bc72 | refs/heads/master | 1,693,514,213,127 | 1,692,322,210,000 | 1,692,322,210,000 | 7,815,356 | 33 | 22 | null | 1,433,592,935,000 | 1,359,097,381,000 | Visual Basic | UTF-8 | Lean | false | false | 81 | lean | import Bin
def main : IO Unit :=
IO.println s!"one is: {Bin.succ Bin.B}!"
|
838bea0a0918188d389db79eb51afaaff05f0f82 | 0c1546a496eccfb56620165cad015f88d56190c5 | /tests/lean/run/elab_crash1.lean | bc4d8773b13bd4fbcf4a77c3bebd483e50cef2a1 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 349 | lean | open expr tactic
meta definition to_expr_target (a : pexpr) : tactic expr :=
do tgt ← target,
to_expr `((%%a : %%tgt))
noncomputable example (A : Type) (a : A) : A :=
by do to_expr_target `(sorry) >>= exact
noncomputable example (A : Type) (a : A) : A :=
by do refine `(sorry)
example (a : nat) : nat :=
by do to_expr `(nat.zero) >>= exact
|
d86f72bd6bba92182c5944b5c1b4bf5fa9dc415b | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/fin.lean | 78f8f2970eb586960d965b3dd78bcc19dd524e45 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,636 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Haitao Zhang, Leonardo de Moura
Finite ordinal types.
-/
import data.list.basic data.finset.basic data.fintype.card algebra.group data.equiv
open eq.ops nat function list finset fintype
structure fin (n : nat) := (val : nat) (is_lt : val < n)
definition less_than [reducible] := fin
namespace fin
attribute fin.val [coercion]
section def_equal
variable {n : nat}
lemma eq_of_veq : ∀ {i j : fin n}, (val i) = j → i = j
| (mk iv ilt) (mk jv jlt) := assume (veq : iv = jv), begin congruence, assumption end
lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = j
| (mk iv ilt) (mk jv jlt) := assume Peq,
show iv = jv, from fin.no_confusion Peq (λ Pe Pqe, Pe)
lemma eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j :=
iff.intro eq_of_veq veq_of_eq
definition val_inj := @eq_of_veq n
end def_equal
section
open decidable
protected definition has_decidable_eq [instance] (n : nat) : ∀ (i j : fin n), decidable (i = j)
| (mk ival ilt) (mk jval jlt) :=
decidable_of_decidable_of_iff (nat.has_decidable_eq ival jval) eq_iff_veq
end
lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk :=
take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe)
lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl
definition upto [reducible] (n : nat) : list (fin n) :=
dmap (λ i, i < n) fin.mk (list.upto n)
lemma nodup_upto (n : nat) : nodup (upto n) :=
dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n)
lemma mem_upto (n : nat) : ∀ (i : fin n), i ∈ upto n :=
take i, fin.destruct i
(take ival Piltn,
assert ival ∈ list.upto n, from mem_upto_of_lt Piltn,
mem_dmap Piltn this)
lemma upto_zero : upto 0 = [] :=
by rewrite [↑upto, list.upto_nil, dmap_nil]
lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n :=
map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n)
lemma length_upto (n : nat) : length (upto n) = n :=
calc
length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹
... = n : list.length_upto n
definition is_fintype [instance] (n : nat) : fintype (fin n) :=
fintype.mk (upto n) (nodup_upto n) (mem_upto n)
section pigeonhole
open fintype
lemma card_fin (n : nat) : card (fin n) = n := length_upto n
theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬∃ f : fin n → fin m, injective f :=
assume Pex, absurd Pmltn (not_lt_of_ge
(calc
n = card (fin n) : card_fin
... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex
... = m : card_fin))
end pigeonhole
definition zero (n : nat) : fin (succ n) :=
mk 0 !zero_lt_succ
definition mk_mod [reducible] (n i : nat) : fin (succ n) :=
mk (i mod (succ n)) (mod_lt _ !zero_lt_succ)
variable {n : nat}
theorem val_lt : ∀ i : fin n, val i < n
| (mk v h) := h
lemma max_lt (i j : fin n) : max i j < n :=
max_lt (is_lt i) (is_lt j)
definition lift : fin n → Π m, fin (n + m)
| (mk v h) m := mk v (lt_add_of_lt_right h m)
definition lift_succ (i : fin n) : fin (nat.succ n) :=
lift i 1
definition maxi [reducible] : fin (succ n) :=
mk n !lt_succ_self
theorem val_lift : ∀ (i : fin n) (m : nat), val i = val (lift i m)
| (mk v h) m := rfl
lemma mk_succ_ne_zero {i : nat} : ∀ {P}, mk (succ i) P ≠ zero n :=
assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero
lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i :=
eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end
lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt :=
begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end
section lift_lower
lemma lift_zero : lift_succ (zero n) = zero (succ n) := rfl
lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi :=
by intro hlt he; substvars; exact absurd hlt (lt.irrefl n)
lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n :=
assume hne : i ≠ maxi,
assert vne : val i ≠ n, from
assume he,
have val (@maxi n) = n, from rfl,
have val i = val (@maxi n), from he ⬝ this⁻¹,
absurd (eq_of_veq this) hne,
have val i < nat.succ n, from val_lt i,
lt_of_le_of_ne (le_of_lt_succ this) vne
lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi :=
begin
cases i with v hlt, esimp [lift_succ, lift, max], intro he,
injection he, substvars,
exact absurd hlt (lt.irrefl v)
end
lemma lift_succ_inj : injective (@lift_succ n) :=
take i j, destruct i (destruct j (take iv ilt jv jlt Pmkeq,
begin congruence, apply fin.no_confusion Pmkeq, intros, assumption end))
lemma lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) :
injective f → (f maxi = maxi) → ∀ i, i < n → f i < n :=
assume Pinj Peq, take i, assume Pilt,
assert P1 : f i = f maxi → i = maxi, from assume Peq, Pinj i maxi Peq,
have f i ≠ maxi, from
begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end,
lt_max_of_ne_max this
definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) :=
λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne))))
definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : injective f) :
f maxi = maxi → fin n → fin n :=
assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max))
lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi :=
begin rewrite [↑lift_fun, dif_pos rfl] end
lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) :
lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) :=
begin rewrite [↑lift_fun, dif_neg Pne] end
lemma lift_fun_eq {f : fin n → fin n} {i : fin n} :
lift_fun f (lift_succ i) = lift_succ (f i) :=
begin
rewrite [lift_fun_of_ne_max lift_succ_ne_max], congruence, congruence,
rewrite [-eq_iff_veq], esimp, rewrite [↑lift_succ, -val_lift]
end
lemma lift_fun_of_inj {f : fin n → fin n} : injective f → injective (lift_fun f) :=
assume Pinj, take i j,
assert Pdi : decidable (i = maxi), from _, assert Pdj : decidable (j = maxi), from _,
begin
cases Pdi with Pimax Pinmax,
cases Pdj with Pjmax Pjnmax,
substvars, intros, exact rfl,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax],
intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max,
cases Pdj with Pjmax Pjnmax,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax],
intro Plmax, apply absurd Plmax lift_succ_ne_max,
rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax],
intro Peq, rewrite [-eq_iff_veq],
exact veq_of_eq (Pinj (lift_succ_inj Peq))
end
lemma lift_fun_inj : injective (@lift_fun n) :=
take f₁ f₂ Peq, funext (λ i,
assert lift_fun f₁ (lift_succ i) = lift_fun f₂ (lift_succ i), from congr_fun Peq _,
begin revert this, rewrite [*lift_fun_eq], apply lift_succ_inj end)
lemma lower_inj_apply {f Pinj Pmax} (i : fin n) :
val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) :=
by rewrite [↑lower_inj]
end lift_lower
section madd
definition madd (i j : fin (succ n)) : fin (succ n) :=
mk ((i + j) mod (succ n)) (mod_lt _ !zero_lt_succ)
definition minv : ∀ i : fin (succ n), fin (succ n)
| (mk iv ilt) := mk ((succ n - iv) mod succ n) (mod_lt _ !zero_lt_succ)
lemma val_madd : ∀ i j : fin (succ n), val (madd i j) = (i + j) mod (succ n)
| (mk iv ilt) (mk jv jlt) := by esimp
lemma madd_inj : ∀ {i : fin (succ n)}, injective (madd i)
| (mk iv ilt) :=
take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin
rewrite [↑madd, -eq_iff_veq],
intro Peq, congruence,
rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)],
apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq
end))
lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) :=
eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end
lemma val_mod : ∀ i : fin (succ n), (val i) mod (succ n) = val i
| (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)]
lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i :=
by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)]
lemma zero_madd (i : fin (succ n)) : madd (zero n) i = i :=
by apply eq_of_veq; rewrite [val_madd, ↑zero, nat.zero_add, mod_eq_of_lt (is_lt i)]
lemma madd_zero (i : fin (succ n)) : madd i (zero n) = i :=
!madd_comm ▸ zero_madd i
lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) :=
by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)]
lemma madd_left_inv : ∀ i : fin (succ n), madd (minv i) i = zero n
| (mk iv ilt) := eq_of_veq (by
rewrite [val_madd, ↑minv, ↑zero, mod_add_mod, sub_add_cancel (le_of_lt ilt), mod_self])
open algebra
definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) :=
add_comm_group.mk madd madd_assoc (zero n) zero_madd madd_zero minv madd_left_inv madd_comm
end madd
definition pred : fin n → fin n
| (mk v h) := mk (nat.pred v) (pre_lt_of_lt h)
lemma val_pred : ∀ (i : fin n), val (pred i) = nat.pred (val i)
| (mk v h) := rfl
lemma pred_zero : pred (zero n) = zero n :=
rfl
definition mk_pred (i : nat) (h : succ i < succ n) : fin n :=
mk i (lt_of_succ_lt_succ h)
definition succ : fin n → fin (succ n)
| (mk v h) := mk (nat.succ v) (succ_lt_succ h)
lemma val_succ : ∀ (i : fin n), val (succ i) = nat.succ (val i)
| (mk v h) := rfl
lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl
lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ :=
funext take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end)
definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i
| (mk v h) := absurd h !not_lt_zero
definition zero_succ_cases {C : fin (nat.succ n) → Type} :
C (zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) :=
begin
intros CO CS k,
induction k with [vk, pk],
induction (nat.decidable_lt 0 vk) with [HT, HF],
{ show C (mk vk pk), from
let vj := nat.pred vk in
have vk = vj+1, from
eq.symm (succ_pred_of_pos HT),
assert vj < n, from
lt_of_succ_lt_succ (eq.subst `vk = vj+1` pk),
have succ (mk vj `vj < n`) = mk vk pk, from
val_inj (eq.symm `vk = vj+1`),
eq.rec_on this (CS (mk vj `vj < n`)) },
{ show C (mk vk pk), from
have vk = 0, from
eq_zero_of_le_zero (le_of_not_gt HF),
have zero n = mk vk pk, from
val_inj (eq.symm this),
eq.rec_on this CO }
end
definition succ_maxi_cases {C : fin (nat.succ n) → Type} :
(Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) :=
begin
intros CL CM k,
induction k with [vk, pk],
induction (nat.decidable_lt vk n) with [HT, HF],
{ show C (mk vk pk), from
have HL : lift_succ (mk vk HT) = mk vk pk, from
val_inj rfl,
eq.rec_on HL (CL (mk vk HT)) },
{ show C (mk vk pk), from
have HMv : vk = n, from
le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF),
have HM : maxi = mk vk pk, from
val_inj (eq.symm HMv),
eq.rec_on HM CM }
end
definition foldr {A B : Type} (m : A → B → B) (b : B) : ∀ {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (f (zero n)) (IH (λ i : fin n, f (succ i))))
definition foldl {A B : Type} (m : B → A → B) (b : B) : ∀ {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi))
theorem choice {C : fin n → Type} :
(∀ i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) :=
begin
revert C,
induction n with [n, IH],
{ intros C H,
apply nonempty.intro,
exact elim0 },
{ intros C H,
fapply nonempty.elim (H (zero n)),
intro CO,
fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))),
intro CS,
apply nonempty.intro,
exact zero_succ_cases CO CS }
end
section
open list
local postfix `+1`:100 := nat.succ
lemma dmap_map_lift {n : nat} : ∀ l : list nat, (∀ i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l)
| [] := assume Plt, rfl
| (i::l) := assume Plt, begin
rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons],
congruence,
apply dmap_map_lift,
intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end
lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) :=
begin
rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)],
congruence,
apply dmap_map_lift, apply @list.lt_of_mem_upto
end
definition upto_step : ∀ {n : nat}, fin.upto (n +1) = (map succ (upto n))++[zero n]
| 0 := rfl
| (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero],
congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ (zero i)), -map_append, -upto_step] end
end
open sum equiv decidable
definition fin_zero_equiv_empty : fin 0 ≃ empty :=
⦃ equiv,
to_fun := λ f : (fin 0), elim0 f,
inv_fun := λ e : empty, empty.rec _ e,
left_inv := λ f : (fin 0), elim0 f,
right_inv := λ e : empty, empty.rec _ e
⦄
definition fin_one_equiv_unit : fin 1 ≃ unit :=
⦃ equiv,
to_fun := λ f : (fin 1), unit.star,
inv_fun := λ u : unit, fin.zero 0,
left_inv := begin
intro f, change mk 0 !zero_lt_succ = f, cases f with v h, congruence,
have v +1 ≤ 1, from succ_le_of_lt h,
have v ≤ 0, from le_of_succ_le_succ this,
have v = 0, from eq_zero_of_le_zero this,
subst v
end,
right_inv := begin
intro u, cases u, reflexivity
end
⦄
definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) :=
assert aux₁ : ∀ {v}, v < m → (v + n) < (n + m), from
take v, suppose v < m, calc
v + n < m + n : add_lt_add_of_lt_of_le this !le.refl
... = n + m : add.comm,
⦃ equiv,
to_fun := λ s : sum (fin n) (fin m),
match s with
| sum.inl (mk v hlt) := mk v (lt_add_of_lt_right hlt m)
| sum.inr (mk v hlt) := mk (v+n) (aux₁ hlt)
end,
inv_fun := λ f : fin (n + m),
match f with
| mk v hlt := if h : v < n then sum.inl (mk v h) else sum.inr (mk (v-n) (sub_lt_of_lt_add hlt (le_of_not_gt h)))
end,
left_inv := begin
intro s, cases s with f₁ f₂,
{ cases f₁ with v hlt, esimp, rewrite [dif_pos hlt] },
{ cases f₂ with v hlt, esimp,
have ¬ v + n < n, from
suppose v + n < n,
assert v < n - n, from lt_sub_of_add_lt this !le.refl,
have v < 0, by rewrite [sub_self at this]; exact this,
absurd this !not_lt_zero,
rewrite [dif_neg this], congruence, congruence, rewrite [add_sub_cancel] }
end,
right_inv := begin
intro f, cases f with v hlt, esimp, apply @by_cases (v < n),
{ intro h₁, rewrite [dif_pos h₁] },
{ intro h₁, rewrite [dif_neg h₁], esimp, congruence, rewrite [sub_add_cancel (le_of_not_gt h₁)] }
end
⦄
definition fin_prod_equiv_of_pos (n m : nat) : n > 0 → (fin n × fin m) ≃ fin (n*m) :=
suppose n > 0,
assert aux₁ : ∀ {v₁ v₂}, v₁ < n → v₂ < m → v₁ + v₂ * n < n*m, from
take v₁ v₂, assume h₁ h₂,
have nat.succ v₂ ≤ m, from succ_le_of_lt h₂,
assert nat.succ v₂ * n ≤ m * n, from mul_le_mul_right _ this,
have v₂ * n + n ≤ n * m, by rewrite [-add_one at this, mul.right_distrib at this, one_mul at this, mul.comm m n at this]; exact this,
assert v₁ + (v₂ * n + n) < n + n * m, from add_lt_add_of_lt_of_le h₁ this,
have v₁ + v₂ * n + n < n * m + n, by rewrite [add.assoc, add.comm (n*m) n]; exact this,
lt_of_add_lt_add_right this,
assert aux₂ : ∀ v, v mod n < n, from
take v, mod_lt _ `n > 0`,
assert aux₃ : ∀ {v}, v < n * m → v div n < m, from
take v, assume h, by rewrite mul.comm at h; exact div_lt_of_lt_mul h,
⦃ equiv,
to_fun := λ p : (fin n × fin m), match p with (mk v₁ hlt₁, mk v₂ hlt₂) := mk (v₁ + v₂ * n) (aux₁ hlt₁ hlt₂) end,
inv_fun := λ f : fin (n*m), match f with (mk v hlt) := (mk (v mod n) (aux₂ v), mk (v div n) (aux₃ hlt)) end,
left_inv := begin
intro p, cases p with f₁ f₂, cases f₁ with v₁ hlt₁, cases f₂ with v₂ hlt₂, esimp,
congruence,
{congruence, rewrite [add_mul_mod_self, mod_eq_of_lt hlt₁] },
{congruence, rewrite [add_mul_div_self `n > 0`, div_eq_zero_of_lt hlt₁, zero_add]}
end,
right_inv := begin
intro f, cases f with v hlt, esimp, congruence,
rewrite [add.comm, -eq_div_mul_add_mod]
end
⦄
definition fin_prod_equiv : Π (n m : nat), (fin n × fin m) ≃ fin (n*m)
| 0 b := calc
(fin 0 × fin b) ≃ (empty × fin b) : prod_congr fin_zero_equiv_empty !equiv.refl
... ≃ empty : prod_empty_left
... ≃ fin 0 : fin_zero_equiv_empty
... ≃ fin (0 * b) : by rewrite zero_mul
| (a+1) b := fin_prod_equiv_of_pos (a+1) b dec_trivial
definition fin_two_equiv_bool : fin 2 ≃ bool :=
calc
fin 2 ≃ fin (1 + 1) : equiv.refl
... ≃ fin 1 + fin 1 : fin_sum_equiv
... ≃ unit + unit : sum_congr fin_one_equiv_unit fin_one_equiv_unit
... ≃ bool : bool_equiv_unit_sum_unit
definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (n+1) :=
calc
fin n + unit ≃ fin n + fin 1 : sum_congr !equiv.refl (equiv.symm fin_one_equiv_unit)
... ≃ fin (n+1) : fin_sum_equiv
end fin
|
d8f4e5fa0b8f9615cb432337ea77ce0a1dd10ed6 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/LocalContext.lean | db26a8c6e5c8e2ea436c474aec08d7417e002841 | [
"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 | 15,322 | 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 Std.Data.PersistentArray
import Lean.Expr
import Lean.Hygiene
namespace Lean
inductive LocalDecl where
| cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo)
| ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool)
deriving Inhabited
@[export lean_mk_local_decl]
def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl :=
LocalDecl.cdecl index fvarId userName type bi
@[export lean_mk_let_decl]
def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl :=
LocalDecl.ldecl index fvarId userName type val false
@[export lean_local_decl_binder_info]
def LocalDecl.binderInfoEx : LocalDecl → BinderInfo
| LocalDecl.cdecl _ _ _ _ bi => bi
| _ => BinderInfo.default
namespace LocalDecl
def isLet : LocalDecl → Bool
| cdecl .. => false
| ldecl .. => true
def index : LocalDecl → Nat
| cdecl (index := i) .. => i
| ldecl (index := i) .. => i
def setIndex : LocalDecl → Nat → LocalDecl
| cdecl _ id n t bi, idx => cdecl idx id n t bi
| ldecl _ id n t v nd, idx => ldecl idx id n t v nd
def fvarId : LocalDecl → FVarId
| cdecl (fvarId := id) .. => id
| ldecl (fvarId := id) .. => id
def userName : LocalDecl → Name
| cdecl (userName := n) .. => n
| ldecl (userName := n) .. => n
def type : LocalDecl → Expr
| cdecl (type := t) .. => t
| ldecl (type := t) .. => t
def setType : LocalDecl → Expr → LocalDecl
| cdecl idx id n _ bi, t => cdecl idx id n t bi
| ldecl idx id n _ v nd, t => ldecl idx id n t v nd
def binderInfo : LocalDecl → BinderInfo
| cdecl (bi := bi) .. => bi
| ldecl .. => BinderInfo.default
def isAuxDecl (d : LocalDecl) : Bool :=
d.binderInfo.isAuxDecl
def value? : LocalDecl → Option Expr
| cdecl .. => none
| ldecl (value := v) .. => some v
def value : LocalDecl → Expr
| cdecl .. => panic! "let declaration expected"
| ldecl (value := v) .. => v
def hasValue : LocalDecl → Bool
| cdecl .. => false
| ldecl .. => true
def setValue : LocalDecl → Expr → LocalDecl
| ldecl idx id n t _ nd, v => ldecl idx id n t v nd
| d, _ => d
def setUserName : LocalDecl → Name → LocalDecl
| cdecl index id _ type bi, userName => cdecl index id userName type bi
| ldecl index id _ type val nd, userName => ldecl index id userName type val nd
def setBinderInfo : LocalDecl → BinderInfo → LocalDecl
| cdecl index id n type _, bi => cdecl index id n type bi
| ldecl .., _ => panic! "unexpected let declaration"
def toExpr (decl : LocalDecl) : Expr :=
mkFVar decl.fvarId
def hasExprMVar : LocalDecl → Bool
| cdecl (type := t) .. => t.hasExprMVar
| ldecl (type := t) (value := v) .. => t.hasExprMVar || v.hasExprMVar
end LocalDecl
open Std (PersistentHashMap PersistentArray PArray)
structure LocalContext where
fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {}
decls : PersistentArray (Option LocalDecl) := {}
deriving Inhabited
namespace LocalContext
@[export lean_mk_empty_local_ctx]
def mkEmpty : Unit → LocalContext := fun _ => {}
def empty : LocalContext := {}
@[export lean_local_ctx_is_empty]
def isEmpty (lctx : LocalContext) : Bool :=
lctx.fvarIdToDecl.isEmpty
/- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/
@[export lean_local_ctx_mk_local_decl]
def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let decl := LocalDecl.cdecl idx fvarId userName type bi
{ fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl }
@[export lean_local_ctx_mk_let_decl]
def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let decl := LocalDecl.ldecl idx fvarId userName type value nonDep
{ fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl }
/- Low level API -/
def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let newDecl := newDecl.setIndex idx
{ fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl }
@[export lean_local_ctx_find]
def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl :=
lctx.fvarIdToDecl.find? fvarId
def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl :=
lctx.find? e.fvarId!
def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl :=
match lctx.find? fvarId with
| some d => d
| none => panic! "unknown free variable"
def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl :=
lctx.get! e.fvarId!
def contains (lctx : LocalContext) (fvarId : FVarId) : Bool :=
lctx.fvarIdToDecl.contains fvarId
def containsFVar (lctx : LocalContext) (e : Expr) : Bool :=
lctx.contains e.fvarId!
def getFVarIds (lctx : LocalContext) : Array FVarId :=
lctx.decls.foldl (init := #[]) fun r decl? => match decl? with
| some decl => r.push decl.fvarId
| none => r
def getFVars (lctx : LocalContext) : Array Expr :=
lctx.getFVarIds.map mkFVar
private partial def popTailNoneAux (a : PArray (Option LocalDecl)) : PArray (Option LocalDecl) :=
if a.size == 0 then a
else match a.get! (a.size - 1) with
| none => popTailNoneAux a.pop
| some _ => a
@[export lean_local_ctx_erase]
def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match map.find? fvarId with
| none => lctx
| some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) }
@[export lean_local_ctx_pop]
def pop (lctx : LocalContext): LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
if decls.size == 0 then lctx
else match decls.get! (decls.size - 1) with
| none => lctx -- unreachable
| some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop }
@[export lean_local_ctx_find_from_user_name]
def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl :=
lctx.decls.findSomeRev? fun decl =>
match decl with
| none => none
| some decl => if decl.userName == userName then some decl else none
@[export lean_local_ctx_uses_user_name]
def usesUserName (lctx : LocalContext) (userName : Name) : Bool :=
(lctx.findFromUserName? userName).isSome
private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) (i : Nat) : Name × Nat :=
let curr := suggestion.appendIndexAfter i
if lctx.usesUserName curr then getUnusedNameAux lctx suggestion (i + 1)
else (curr, i + 1)
@[export lean_local_ctx_get_unused_name]
def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name :=
let suggestion := suggestion.eraseMacroScopes
if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1
else suggestion
@[export lean_local_ctx_last_decl]
def lastDecl (lctx : LocalContext) : Option LocalDecl :=
lctx.decls.get! (lctx.decls.size - 1)
def setUserName (lctx : LocalContext) (fvarId : FVarId) (userName : Name) : LocalContext :=
let decl := lctx.get! fvarId
let decl := decl.setUserName userName
{ fvarIdToDecl := lctx.fvarIdToDecl.insert decl.fvarId decl,
decls := lctx.decls.set decl.index decl }
@[export lean_local_ctx_rename_user_name]
def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match lctx.findFromUserName? fromName with
| none => lctx
| some decl =>
let decl := decl.setUserName toName;
{ fvarIdToDecl := map.insert decl.fvarId decl,
decls := decls.set decl.index decl }
/--
Low-level function for updating the local context.
Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values,
the `index` nor `fvarId` are modified. -/
@[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match lctx.find? fvarId with
| none => lctx
| some decl =>
let decl := f decl;
{ fvarIdToDecl := map.insert decl.fvarId decl,
decls := decls.set decl.index decl }
def setBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext :=
modifyLocalDecl lctx fvarId fun decl => decl.setBinderInfo bi
@[export lean_local_ctx_num_indices]
def numIndices (lctx : LocalContext) : Nat :=
lctx.decls.size
@[export lean_local_ctx_get]
def getAt? (lctx : LocalContext) (i : Nat) : Option LocalDecl :=
lctx.decls.get! i
@[specialize] def foldlM [Monad m] (lctx : LocalContext) (f : β → LocalDecl → m β) (init : β) (start : Nat := 0) : m β :=
lctx.decls.foldlM (init := init) (start := start) fun b decl => match decl with
| none => pure b
| some decl => f b decl
@[specialize] def foldrM [Monad m] (lctx : LocalContext) (f : LocalDecl → β → m β) (init : β) : m β :=
lctx.decls.foldrM (init := init) fun decl b => match decl with
| none => pure b
| some decl => f decl b
@[specialize] def forM [Monad m] (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit :=
lctx.decls.forM fun decl => match decl with
| none => pure PUnit.unit
| some decl => f decl
@[specialize] def findDeclM? [Monad m] (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) :=
lctx.decls.findSomeM? fun decl => match decl with
| none => pure none
| some decl => f decl
@[specialize] def findDeclRevM? [Monad m] (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) :=
lctx.decls.findSomeRevM? fun decl => match decl with
| none => pure none
| some decl => f decl
instance : ForIn m LocalContext LocalDecl where
forIn lctx init f := lctx.decls.forIn init fun d? b => match d? with
| none => ForInStep.yield b
| some d => f d b
@[inline] def foldl (lctx : LocalContext) (f : β → LocalDecl → β) (init : β) (start : Nat := 0) : β :=
Id.run <| lctx.foldlM f init start
@[inline] def foldr (lctx : LocalContext) (f : LocalDecl → β → β) (init : β) : β :=
Id.run <| lctx.foldrM f init
@[inline] def findDecl? (lctx : LocalContext) (f : LocalDecl → Option β) : Option β :=
Id.run <| lctx.findDeclM? f
@[inline] def findDeclRev? (lctx : LocalContext) (f : LocalDecl → Option β) : Option β :=
Id.run <| lctx.findDeclRevM? f
partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) (i j : Nat) : Bool :=
if i < a₁.size then
match a₁[i] with
| none => isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j
| some decl₁ =>
if exceptFVars.any fun fvar => fvar.fvarId! == decl₁.fvarId then
isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j
else if j < a₂.size then
match a₂[j] with
| none => isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1)
| some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) (j+1) else isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1)
else false
else true
/- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true
iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix
of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/
def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool :=
isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0
@[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
let b := b.abstract xs
xs.size.foldRev (init := b) fun i b =>
let x := xs[i]
match lctx.findFVar? x with
| some (LocalDecl.cdecl _ _ n ty bi) =>
let ty := ty.abstractRange i xs;
if isLambda then
Lean.mkLambda n bi ty b
else
Lean.mkForall n bi ty b
| some (LocalDecl.ldecl _ _ n ty val nonDep) =>
if b.hasLooseBVar 0 then
let ty := ty.abstractRange i xs
let val := val.abstractRange i xs
mkLet n ty val b nonDep
else
b.lowerLooseBVars 1 1
| none => panic! "unknown free variable"
def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
mkBinding true lctx xs b
def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
mkBinding false lctx xs b
@[inline] def anyM [Monad m] (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool :=
lctx.decls.anyM fun d => match d with
| some decl => p decl
| none => pure false
@[inline] def allM [Monad m] (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool :=
lctx.decls.allM fun d => match d with
| some decl => p decl
| none => pure true
@[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool :=
Id.run <| lctx.anyM p
@[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool :=
Id.run <| lctx.allM p
def sanitizeNames (lctx : LocalContext) : StateM NameSanitizerState LocalContext := do
let st ← get
if !getSanitizeNames st.options then pure lctx else
StateT.run' (s := ({} : NameSet)) <|
lctx.decls.size.foldRevM (init := lctx) fun i lctx => do
match lctx.decls[i] with
| none => pure lctx
| some decl =>
if decl.userName.hasMacroScopes || (← get).contains decl.userName then do
modify fun s => s.insert decl.userName
let userNameNew ← liftM <| sanitizeName decl.userName
pure <| lctx.setUserName decl.fvarId userNameNew
else
modify fun s => s.insert decl.userName
pure lctx
end LocalContext
class MonadLCtx (m : Type → Type) where
getLCtx : m LocalContext
export MonadLCtx (getLCtx)
instance [MonadLift m n] [MonadLCtx m] : MonadLCtx n where
getLCtx := liftM (getLCtx : m _)
def replaceFVarIdAtLocalDecl (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl :=
if d.fvarId == fvarId then d
else match d with
| LocalDecl.cdecl idx id n type bi => LocalDecl.cdecl idx id n (type.replaceFVarId fvarId e) bi
| LocalDecl.ldecl idx id n type val nonDep => LocalDecl.ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep
end Lean
|
ad4ad9ea1b8e97cb21fa2c13e5b55cf93e4c0a3e | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/geometry/manifold/algebra/monoid.lean | 278d0fc72bd464322b3143b556e85ab03726fd49 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,321 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.times_cont_mdiff_map
/-!
# Smooth monoid
A smooth monoid is a monoid that is also a smooth manifold, in which multiplication is a smooth map
of the product manifold `G` × `G` into `G`.
In this file we define the basic structures to talk about smooth monoids: `has_smooth_mul` and its
additive counterpart `has_smooth_add`. These structures are general enough to also talk about smooth
semigroups.
-/
open_locale manifold
section
set_option old_structure_cmd true
/--
1. All smooth algebraic structures on `G` are `Prop`-valued classes that extend
`smooth_manifold_with_corners I G`. This way we save users from adding both
`[smooth_manifold_with_corners I G]` and `[has_smooth_mul I G]` to the assumptions. While many API
lemmas hold true without the `smooth_manifold_with_corners I G` assumption, we're not aware of a
mathematically interesting monoid on a topological manifold such that (a) the space is not a
`smooth_manifold_with_corners`; (b) the multiplication is smooth at `(a, b)` in the charts
`ext_chart_at I a`, `ext_chart_at I b`, `ext_chart_at I (a * b)`.
2. Because of `model_prod` we can't assume, e.g., that a `lie_group` is modelled on `𝓘(𝕜, E)`. So,
we formulate the definitions and lemmas for any model.
3. While smoothness of an operation implies its continuity, lemmas like
`has_continuous_mul_of_smooth` can't be instances becausen otherwise Lean would have to search for
`has_smooth_mul I G` with unknown `𝕜`, `E`, `H`, and `I : model_with_corners 𝕜 E H`. If users needs
`[has_continuous_mul G]` in a proof about a smooth monoid, then they need to either add
`[has_continuous_mul G]` as an assumption (worse) or use `haveI` in the proof (better). -/
library_note "Design choices about smooth algebraic structures"
/-- Basic hypothesis to talk about a smooth (Lie) additive monoid or a smooth additive
semigroup. A smooth additive monoid over `α`, for example, is obtained by requiring both the
instances `add_monoid α` and `has_smooth_add α`. -/
-- See note [Design choices about smooth algebraic structures]
@[ancestor smooth_manifold_with_corners]
class has_smooth_add {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H)
(G : Type*) [has_add G] [topological_space G] [charted_space H G]
extends smooth_manifold_with_corners I G : Prop :=
(smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2))
/-- Basic hypothesis to talk about a smooth (Lie) monoid or a smooth semigroup.
A smooth monoid over `G`, for example, is obtained by requiring both the instances `monoid G`
and `has_smooth_mul I G`. -/
-- See note [Design choices about smooth algebraic structures]
@[ancestor smooth_manifold_with_corners, to_additive]
class has_smooth_mul {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H)
(G : Type*) [has_mul G] [topological_space G] [charted_space H G]
extends smooth_manifold_with_corners I G : Prop :=
(smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2))
end
section has_smooth_mul
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [has_mul G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M : Type*} [topological_space M] [charted_space H' M]
section
variables (I)
@[to_additive]
lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) :=
has_smooth_mul.smooth_mul
/-- If the multiplication is smooth, then it is continuous. This is not an instance for technical
reasons, see note [Design choices about smooth algebraic structures]. -/
@[to_additive
"If the addition is smooth, then it is continuous. This is not an instance for technical reasons,
see note [Design choices about smooth algebraic structures]."]
lemma has_continuous_mul_of_smooth : has_continuous_mul G :=
⟨(smooth_mul I).continuous⟩
end
@[to_additive]
lemma smooth.mul {f : M → G} {g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) :
smooth I' I (f * g) :=
(smooth_mul I).comp (hf.prod_mk hg)
@[to_additive]
lemma smooth_mul_left {a : G} : smooth I I (λ b : G, a * b) :=
smooth_const.mul smooth_id
@[to_additive]
lemma smooth_mul_right {a : G} : smooth I I (λ b : G, b * a) :=
smooth_id.mul smooth_const
@[to_additive]
lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M}
(hf : smooth_on I' I f s) (hg : smooth_on I' I g s) :
smooth_on I' I (f * g) s :=
((smooth_mul I).comp_smooth_on (hf.prod_mk hg) : _)
variables (I) (g h : G)
/-- Left multiplication by `g`. It is meant to mimic the usual notation in Lie groups.
Lemmas involving `smooth_left_mul` with the notation `𝑳` usually use `L` instead of `𝑳` in the
names. -/
def smooth_left_mul : C^∞⟮I, G; I, G⟯ := ⟨(left_mul g), smooth_mul_left⟩
/-- Right multiplication by `g`. It is meant to mimic the usual notation in Lie groups.
Lemmas involving `smooth_right_mul` with the notation `𝑹` usually use `R` instead of `𝑹` in the
names. -/
def smooth_right_mul : C^∞⟮I, G; I, G⟯ := ⟨(right_mul g), smooth_mul_right⟩
/- Left multiplication. The abbreviation is `MIL`. -/
localized "notation `𝑳` := smooth_left_mul" in lie_group
/- Right multiplication. The abbreviation is `MIR`. -/
localized "notation `𝑹` := smooth_right_mul" in lie_group
open_locale lie_group
@[simp] lemma L_apply : (𝑳 I g) h = g * h := rfl
@[simp] lemma R_apply : (𝑹 I g) h = h * g := rfl
@[simp] lemma L_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G]
[has_smooth_mul I G] (g h : G) : 𝑳 I (g * h) = (𝑳 I g).comp (𝑳 I h) :=
by { ext, simp only [times_cont_mdiff_map.comp_apply, L_apply, mul_assoc] }
@[simp] lemma R_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G]
[has_smooth_mul I G] (g h : G) : 𝑹 I (g * h) = (𝑹 I h).comp (𝑹 I g) :=
by { ext, simp only [times_cont_mdiff_map.comp_apply, R_apply, mul_assoc] }
section
variables {G' : Type*} [monoid G'] [topological_space G'] [charted_space H G']
[has_smooth_mul I G'] (g' : G')
lemma smooth_left_mul_one : (𝑳 I g') 1 = g' := mul_one g'
lemma smooth_right_mul_one : (𝑹 I g') 1 = g' := one_mul g'
end
/- Instance of product -/
@[to_additive]
instance has_smooth_mul.prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(G : Type*) [topological_space G] [charted_space H G]
[has_mul G] [has_smooth_mul I G]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H')
(G' : Type*) [topological_space G'] [charted_space H' G']
[has_mul G'] [has_smooth_mul I' G'] :
has_smooth_mul (I.prod I') (G×G') :=
{ smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk
((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)),
.. smooth_manifold_with_corners.prod G G' }
end has_smooth_mul
section monoid
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{H' : Type*} [topological_space H']
{E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {I' : model_with_corners 𝕜 E' H'}
{G' : Type*} [monoid G'] [topological_space G'] [charted_space H' G'] [has_smooth_mul I' G']
lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n)
| 0 := by { simp only [pow_zero], exact smooth_const }
| (k+1) := by simpa [pow_succ] using smooth_id.mul (smooth_pow _)
/-- Morphism of additive smooth monoids. -/
structure smooth_add_monoid_morphism
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(G : Type*) [topological_space G] [charted_space H G] [add_monoid G] [has_smooth_add I G]
(G' : Type*) [topological_space G'] [charted_space H' G'] [add_monoid G'] [has_smooth_add I' G']
extends G →+ G' :=
(smooth_to_fun : smooth I I' to_fun)
/-- Morphism of smooth monoids. -/
@[to_additive] structure smooth_monoid_morphism
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G]
(G' : Type*) [topological_space G'] [charted_space H' G'] [monoid G'] [has_smooth_mul I' G']
extends G →* G' :=
(smooth_to_fun : smooth I I' to_fun)
@[to_additive]
instance : has_one (smooth_monoid_morphism I I' G G') :=
⟨{ smooth_to_fun := smooth_const, to_monoid_hom := 1 }⟩
@[to_additive]
instance : inhabited (smooth_monoid_morphism I I' G G') := ⟨1⟩
@[to_additive]
instance : has_coe_to_fun (smooth_monoid_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩
end monoid
section comm_monoid
open_locale big_operators
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [comm_monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M : Type*} [topological_space M] [charted_space H' M]
@[to_additive]
lemma smooth_finset_prod' {ι} {s : finset ι} {f : ι → M → G} (h : ∀ i ∈ s, smooth I' I (f i)) :
smooth I' I (∏ i in s, f i) :=
finset.prod_induction _ _ (λ f g hf hg, hf.mul hg)
(@smooth_const _ _ _ _ _ _ _ I' _ _ _ _ _ _ _ _ I _ _ _ 1) h
@[to_additive]
lemma smooth_finset_prod {ι} {s : finset ι} {f : ι → M → G} (h : ∀ i ∈ s, smooth I' I (f i)) :
smooth I' I (λ x, ∏ i in s, f i x) :=
by { simp only [← finset.prod_apply], exact smooth_finset_prod' h }
open function filter
@[to_additive]
lemma smooth_finprod {ι} {f : ι → M → G} (h : ∀ i, smooth I' I (f i))
(hfin : locally_finite (λ i, mul_support (f i))) :
smooth I' I (λ x, ∏ᶠ i, f i x) :=
begin
intro x,
rcases hfin x with ⟨U, hxU, hUf⟩,
have : smooth_at I' I (λ x, ∏ i in hUf.to_finset, f i x) x,
from smooth_finset_prod (λ i hi, h i) x,
refine this.congr_of_eventually_eq (mem_of_superset hxU $ λ y hy, _),
refine finprod_eq_prod_of_mul_support_subset _ (λ i hi, _),
rw [hUf.coe_to_finset],
exact ⟨y, hi, hy⟩
end
@[to_additive]
lemma smooth_finprod_cond {ι} {f : ι → M → G} {p : ι → Prop} (hc : ∀ i, p i → smooth I' I (f i))
(hf : locally_finite (λ i, mul_support (f i))) :
smooth I' I (λ x, ∏ᶠ i (hi : p i), f i x) :=
begin
simp only [← finprod_subtype_eq_finprod_cond],
exact smooth_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective)
end
end comm_monoid
|
291ec20c9b338b6e80e915501d714b0206d4781c | 8f209eb34c0c4b9b6be5e518ebfc767a38bed79c | /code/src/internal/Gdt/mark_all_rhss_inactive.lean | b28abcea509c1b0eeaa679f00a101ce8641672f5 | [] | no_license | hediet/masters-thesis | 13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5 | dc40c14cc4ed073673615412f36b4e386ee7aac9 | refs/heads/master | 1,680,591,056,302 | 1,617,710,887,000 | 1,617,710,887,000 | 311,762,038 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,910 | lean | import tactic
import ...definitions
import ..internal_definitions
import ..Ant.main
import .eval
variable [GuardModule]
open GuardModule
@[simp]
lemma Gdt.mark_all_rhss_inactive.inactive_rhss (gdt: Gdt):
gdt.mark_all_rhss_inactive.inactive_rhss = gdt.rhss :=
begin
induction gdt;
try { cases gdt_grd };
simp [*, Gdt.rhss, Gdt.mark_all_rhss_inactive, Ant.inactive_rhss],
end
@[simp]
lemma Gdt.mark_all_rhss_inactive.critical_rhs_sets (gdt: Gdt):
gdt.mark_all_rhss_inactive.critical_rhs_sets = ∅ :=
begin
induction gdt;
try { cases gdt_grd };
simp [*, Gdt.rhss, Gdt.mark_all_rhss_inactive, Ant.critical_rhs_sets],
end
@[simp]
lemma Gdt.mark_all_rhss_inactive.rhss (gdt: Gdt):
gdt.mark_all_rhss_inactive.rhss = gdt.rhss :=
begin
induction gdt;
try { cases gdt_grd };
simp [*, Gdt.rhss, Gdt.mark_all_rhss_inactive, Ant.critical_rhs_sets],
end
@[simp]
lemma Gdt.mark_all_rhss_inactive_map_true (gdt: Gdt):
gdt.mark_all_rhss_inactive.map (λ x, tt) = gdt.mark_all_rhss_inactive :=
begin
induction gdt;
try { cases gdt_grd };
simp [*, Ant.map, Gdt.mark_all_rhss_inactive],
end
lemma Gdt.mark_all_rhss_inactive_is_reduntant_set (gdt: Gdt) (rhss: finset Rhs): gdt.mark_all_rhss_inactive.is_redundant_set rhss :=
by simp [Ant.is_redundant_set, finset.inter_subset_right]
lemma Gdt.mark_inactive_rhss_of_tgrd_some { tgrd: TGrd } { env env': Env } (h: tgrd_eval tgrd env = some env') (gdt: Gdt):
(Gdt.grd (Grd.tgrd tgrd) gdt).mark_inactive_rhss env = gdt.mark_inactive_rhss env' :=
by simp [Gdt.mark_inactive_rhss, h, Gdt.mark_inactive_rhss._match_1]
lemma Gdt.mark_inactive_rhss_of_tgrd_none { tgrd: TGrd } { env: Env } (h: tgrd_eval tgrd env = none) (gdt: Gdt):
(Gdt.grd (Grd.tgrd tgrd) gdt).mark_inactive_rhss env = gdt.mark_all_rhss_inactive :=
by simp [Gdt.mark_inactive_rhss, h, Gdt.mark_inactive_rhss._match_1]
lemma Gdt.mark_inactive_rhss_map_tt (gdt: Gdt) (env: Env):
(gdt.mark_inactive_rhss env).map (λ x, tt) = gdt.mark_all_rhss_inactive :=
begin
induction gdt generalizing env;
try { cases gdt_grd };
try { cases c: (gdt_tr1.eval env).is_match };
try { cases c: (tgrd_eval gdt_grd env) };
try { cases c: is_bottom gdt_grd env };
simp [*, Gdt.rhss, Gdt.mark_inactive_rhss, Gdt.mark_all_rhss_inactive, Ant.map],
end
@[simp]
lemma Gdt.mark_inactive_rhss.rhss (gdt: Gdt) (env: Env):
(gdt.mark_inactive_rhss env).rhss = gdt.rhss :=
begin
induction gdt generalizing env;
try { cases gdt_grd };
try { cases c: (gdt_tr1.eval env).is_match };
try { cases c: (tgrd_eval gdt_grd env) };
try { cases c: is_bottom gdt_grd env };
simp [*, Gdt.rhss, Gdt.mark_inactive_rhss, Ant.critical_rhs_sets],
end
lemma Gdt.mark_inactive_rhss.inactive_rhss (gdt: Gdt) (env: Env): (gdt.mark_inactive_rhss env).inactive_rhss ⊆ gdt.rhss :=
by simp only [←Gdt.mark_inactive_rhss.rhss gdt env, Ant.inactive_rhss_subset_rhss]
lemma Gdt.mark_inactive_rhss_no_match { env: Env } { gdt: Gdt } (h: gdt.eval env = Result.no_match):
gdt.mark_inactive_rhss env = gdt.mark_all_rhss_inactive :=
begin
induction gdt with rhs generalizing env,
case Gdt.rhs { finish [Gdt.eval], },
case Gdt.branch {
simp [
Gdt.mark_inactive_rhss, Gdt.mark_all_rhss_inactive,
Gdt.eval_branch_no_match_iff.1 h, *
],
},
case Gdt.grd {
cases gdt_grd with gdt_grd var,
case Grd.tgrd {
cases c: tgrd_eval gdt_grd env, {
simp [Gdt.mark_inactive_rhss, Gdt.mark_all_rhss_inactive, c],
}, {
rw [Gdt.eval_tgrd_of_some c] at h,
simp [Gdt.mark_inactive_rhss, Gdt.mark_all_rhss_inactive, c, gdt_ih h],
},
},
case Grd.bang {
simp [Gdt.mark_inactive_rhss, Gdt.mark_all_rhss_inactive, Gdt.eval_bang_no_match_iff.1 h, gdt_ih],
},
},
end
|
35ae5dcb8e97126131d490bbb566f4f4b984c2b0 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/empty.lean | 8a6c8913f65fdf6a800f874ef86594fe34b25a04 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 136 | lean | import logic hilbert
definition v1 : Prop := epsilon (λ x, true)
inductive Empty : Type
definition v2 : Empty := epsilon (λ x, true)
|
01451e69b9a555040b40c4ccb3f3a0657693ba9d | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/rewriter18.lean | 14988f547a306881fd2efce47d52b8c1cc2007de | [
"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 | 205 | lean | import algebra.ring
open algebra
definition foo {A : Type} [s : monoid A] (a : A) :=
a * a
example {A : Type} [s : comm_ring A] (a b : A) (H : foo a = a) : a * a = a :=
begin
rewrite [↓foo a, H]
end
|
7046daf31f79d6988dd6102fe32a276bb3907c93 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/metric_space/gluing.lean | 2f82a6a9c57b57e84a258411f71909dc90f8bdaa | [] | 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 | 13,349 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Gluing metric spaces
Authors: Sébastien Gouëzel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.metric_space.isometry
import Mathlib.topology.metric_space.premetric_space
import Mathlib.PostPort
universes u v w
namespace Mathlib
/-!
# Metric space gluing
Gluing two metric spaces along a common subset. Formally, we are given
```
Φ
γ ---> α
|
|Ψ
v
β
```
where `hΦ : isometry Φ` and `hΨ : isometry Ψ`.
We want to complete the square by a space `glue_space hΦ hΨ` and two isometries
`to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute.
We start by defining a predistance on the disjoint union `α ⊕ β`, for which
points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated
to this predistance is the desired space.
This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries,
but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two
spaces so that the images of a point under `Φ` and `Ψ` are ε-close. If `ε > 0`, this yields a metric
space structure on `α ⊕ β`, without the need to take a quotient. In particular, when `α` and `β` are
inhabited, this gives a natural metric space structure on `α ⊕ β`, where the basepoints are at
distance 1, say, and the distances between other points are obtained by going through the two
basepoints.
We also define the inductive limit of metric spaces. Given
```
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
```
where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive
limit of the `X n`, also known as the increasing union of the `X n` in this context, if we
identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed
isometrically and in a way compatible with `f n`.
-/
namespace metric
/-- Define a predistance on α ⊕ β, for which Φ p and Ψ p are at distance ε -/
def glue_dist {α : Type u} {β : Type v} {γ : Type w} [metric_space α] [metric_space β] (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : α ⊕ β → α ⊕ β → ℝ :=
sorry
theorem glue_dist_glued_points {α : Type u} {β : Type v} {γ : Type w} [metric_space α] [metric_space β] [Nonempty γ] (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (p : γ) : glue_dist Φ Ψ ε (sum.inl (Φ p)) (sum.inr (Ψ p)) = ε := sorry
/-- Given two maps Φ and Ψ intro metric spaces α and β such that the distances between Φ p and Φ q,
and between Ψ p and Ψ q, coincide up to 2 ε where ε > 0, one can almost glue the two spaces α
and β along the images of Φ and Ψ, so that Φ p and Ψ p are at distance ε. -/
def glue_metric_approx {α : Type u} {β : Type v} {γ : Type w} [metric_space α] [metric_space β] [Nonempty γ] (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (ε0 : 0 < ε) (H : ∀ (p q : γ), abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ bit0 1 * ε) : metric_space (α ⊕ β) :=
metric_space.mk (glue_dist_self Φ Ψ ε) (glue_eq_of_dist_eq_zero Φ Ψ ε ε0) (glue_dist_comm Φ Ψ ε)
(glue_dist_triangle Φ Ψ ε H) (fun (x y : α ⊕ β) => ennreal.of_real (glue_dist Φ Ψ ε x y))
(uniform_space_of_dist (glue_dist Φ Ψ ε) (glue_dist_self Φ Ψ ε) (glue_dist_comm Φ Ψ ε) (glue_dist_triangle Φ Ψ ε H))
/- A particular case of the previous construction is when one uses basepoints in α and β and one
glues only along the basepoints, putting them at distance 1. We give a direct definition of
the distance, without infi, as it is easier to use in applications, and show that it is equal to
the gluing distance defined above to take advantage of the lemmas we have already proved. -/
/- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible
with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam α + diam β + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default. -/
def sum.dist {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] : α ⊕ β → α ⊕ β → ℝ :=
sorry
theorem sum.dist_eq_glue_dist {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] {p : α ⊕ β} {q : α ⊕ β} : sum.dist p q = glue_dist (fun (_x : Unit) => Inhabited.default) (fun (_x : Unit) => Inhabited.default) 1 p q := sorry
theorem sum.one_dist_le {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] {x : α} {y : β} : 1 ≤ sum.dist (sum.inl x) (sum.inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg)
(add_le_add_right (le_add_of_nonneg_left dist_nonneg) (dist Inhabited.default y))
theorem sum.one_dist_le' {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] {x : α} {y : β} : 1 ≤ sum.dist (sum.inr y) (sum.inl x) :=
eq.mpr (id (Eq._oldrec (Eq.refl (1 ≤ sum.dist (sum.inr y) (sum.inl x))) (sum.dist_comm (sum.inr y) (sum.inl x))))
sum.one_dist_le
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties
follow from our choice of the distance. The harder work is to show that the uniform structure
defined by the distance coincides with the disjoint union uniform structure. -/
def metric_space_sum {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] : metric_space (α ⊕ β) :=
metric_space.mk sorry sorry sum.dist_comm sorry (fun (x y : α ⊕ β) => ennreal.of_real (sum.dist x y)) sum.uniform_space
theorem sum.dist_eq {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] {x : α ⊕ β} {y : α ⊕ β} : dist x y = sum.dist x y :=
rfl
/-- The left injection of a space in a disjoint union in an isometry -/
theorem isometry_on_inl {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] : isometry sum.inl :=
iff.mpr isometry_emetric_iff_metric fun (x y : α) => rfl
/-- The right injection of a space in a disjoint union in an isometry -/
theorem isometry_on_inr {α : Type u} {β : Type v} [metric_space α] [metric_space β] [Inhabited α] [Inhabited β] : isometry sum.inr :=
iff.mpr isometry_emetric_iff_metric fun (x y : β) => rfl
/- Exact gluing of two metric spaces along isometric subsets. -/
def glue_premetric {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) : premetric_space (α ⊕ β) :=
premetric_space.mk sorry sorry sorry
def glue_space {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) :=
premetric.metric_quot (α ⊕ β)
protected instance metric_space_glue_space {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) : metric_space (glue_space hΦ hΨ) :=
premetric.metric_space_quot
def to_glue_l {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : α) : glue_space hΦ hΨ :=
quotient.mk (sum.inl x)
def to_glue_r {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : β) : glue_space hΦ hΨ :=
quotient.mk (sum.inr y)
protected instance inhabited_left {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) [Inhabited α] : Inhabited (glue_space hΦ hΨ) :=
{ default := to_glue_l hΦ hΨ Inhabited.default }
protected instance inhabited_right {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) [Inhabited β] : Inhabited (glue_space hΦ hΨ) :=
{ default := to_glue_r hΦ hΨ Inhabited.default }
theorem to_glue_commute {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) : to_glue_l hΦ hΨ ∘ Φ = to_glue_r hΦ hΨ ∘ Ψ := sorry
theorem to_glue_l_isometry {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) :=
iff.mpr isometry_emetric_iff_metric fun (_x _x_1 : α) => rfl
theorem to_glue_r_isometry {α : Type u} {β : Type v} {γ : Type w} [Nonempty γ] [metric_space γ] [metric_space α] [metric_space β] {Φ : γ → α} {Ψ : γ → β} (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) :=
iff.mpr isometry_emetric_iff_metric fun (_x _x_1 : β) => rfl
/- In this section, we define the inductive limit of
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric
space structure on Σn, X n, where the predistance dist x y is obtained by pushing x and y in a
common X k using composition by the f n, and taking the distance there. This does not depend on
the choice of k as the f n are isometries. The metric space associated to this premetric space
is the desired inductive limit.-/
/-- Predistance on the disjoint union Σn, X n. -/
def inductive_limit_dist {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] (f : (n : ℕ) → X n → X (n + 1)) (x : sigma fun (n : ℕ) => X n) (y : sigma fun (n : ℕ) => X n) : ℝ :=
dist (nat.le_rec_on sorry f (sigma.snd x)) (nat.le_rec_on sorry f (sigma.snd y))
/-- The predistance on the disjoint union Σn, X n can be computed in any X k for large enough k.-/
theorem inductive_limit_dist_eq_dist {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) (x : sigma fun (n : ℕ) => X n) (y : sigma fun (n : ℕ) => X n) (m : ℕ) (hx : sigma.fst x ≤ m) (hy : sigma.fst y ≤ m) : inductive_limit_dist f x y = dist (nat.le_rec_on hx f (sigma.snd x)) (nat.le_rec_on hy f (sigma.snd y)) := sorry
/-- Premetric space structure on Σn, X n.-/
def inductive_premetric {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) : premetric_space (sigma fun (n : ℕ) => X n) :=
premetric_space.mk sorry sorry sorry
/-- The type giving the inductive limit in a metric space context. -/
def inductive_limit {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) :=
premetric.metric_quot (sigma fun (n : ℕ) => X n)
/-- Metric space structure on the inductive limit. -/
protected instance metric_space_inductive_limit {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) : metric_space (inductive_limit I) :=
premetric.metric_space_quot
/-- Mapping each `X n` to the inductive limit. -/
def to_inductive_limit {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) (n : ℕ) (x : X n) : inductive_limit I :=
quotient.mk (sigma.mk n x)
protected instance inductive_limit.inhabited {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) [Inhabited (X 0)] : Inhabited (inductive_limit I) :=
{ default := to_inductive_limit I 0 Inhabited.default }
/-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/
theorem to_inductive_limit_isometry {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) (n : ℕ) : isometry (to_inductive_limit I n) := sorry
/-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/
theorem to_inductive_limit_commute {X : ℕ → Type u} [(n : ℕ) → metric_space (X n)] {f : (n : ℕ) → X n → X (n + 1)} (I : ∀ (n : ℕ), isometry (f n)) (n : ℕ) : to_inductive_limit I (Nat.succ n) ∘ f n = to_inductive_limit I n := sorry
|
cf5865a349a8afcc62ed0638a0acb32682abbf17 | 2c41ae31b2b771ad5646ad880201393f5269a7f0 | /Lean/Examples/Parnas/Functional_Decomposition_Changeable.lean | 8b32f7c821d0c231c410ad0f170a59e7234b3475 | [] | no_license | kevinsullivan/Boehm | 926f25bc6f1a8b6bd47d333d936fdfc278228312 | 55208395bff20d48a598b7fa33a4d55a2447a9cf | refs/heads/master | 1,586,127,134,302 | 1,488,252,326,000 | 1,488,252,326,000 | 32,836,930 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 632 | lean | import Qualities.Satisfactory
import SystemModel.Value
import Examples.Parnas.Functional_Decomposition
definition corpusChangeActionSpec (trigger: kwicAssertion) (agent: kwicStakeholders) (pre post: kwicSystemState): Prop :=
isModular_wrt kwicParameter.corpus pre /\
(trigger = corpusPreState /\ agent = kwicStakeholders.customer /\ corpusPre pre /\ inMaintenancePhase pre ->
corpusPost post /\ post^.value^.modulesChanged <= pre^.value^.modulesChanged + 1)
theorem verifyChangeCorpus: ActionSatisfiesActionSpec (corpusChangeActionSpec corpusPre kwicStakeholders.customer) costomerChangeCorpus :=
sorry |
fe929a6c4001acd613b4e718dfeaf86cf945887e | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/number_theory/arithmetic_function.lean | 83f07c882ea5fa5bb86236bf0404a103c0442f93 | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,574 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import algebra.big_operators.ring
import number_theory.divisors
import algebra.squarefree
import algebra.invertible
/-!
# Arithmetic Functions and Dirichlet Convolution
This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0
to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic
functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition,
to form the Dirichlet ring.
## Main Definitions
* `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`.
* An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`.
* The pointwise operations `pmul` and `ppow` differ from the multiplication
and power instances on `arithmetic_function R`, which use Dirichlet multiplication.
* `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`.
* `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`.
* `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`.
* `id` is the identity arithmetic function on `ℕ`.
* `ω n` is the number of distinct prime factors of `n`.
* `Ω n` is the number of prime factors of `n` counted with multiplicity.
* `μ` is the Möbius function.
## Main Results
* Several forms of Möbius inversion:
* `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring`
* `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group`
* `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group`
* `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero`
## Notation
The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in
the namespace `arithmetic_function`.
## Tags
arithmetic functions, dirichlet convolution, divisors
-/
open finset
open_locale big_operators
namespace nat
variable (R : Type*)
/-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are
often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by
Dirichlet convolution. -/
@[derive [has_zero, inhabited]]
def arithmetic_function [has_zero R] := zero_hom ℕ R
variable {R}
namespace arithmetic_function
section has_zero
variable [has_zero R]
instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun
@[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl
@[simp]
lemma map_zero {f : arithmetic_function R} : f 0 = 0 :=
zero_hom.map_zero' f
theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g :=
⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩
@[simp]
lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 :=
zero_hom.zero_apply x
@[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g :=
zero_hom.ext h
theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x :=
zero_hom.ext_iff
section has_one
variable [has_one R]
instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩
@[simp]
lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl
@[simp]
lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h
end has_one
end has_zero
instance nat_coe [has_zero R] [has_one R] [has_add R] :
has_coe (arithmetic_function ℕ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma nat_coe_nat (f : arithmetic_function ℕ) :
(↑f : arithmetic_function ℕ) = f :=
ext $ λ _, cast_id _
@[simp]
lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] :
has_coe (arithmetic_function ℤ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma int_coe_int (f : arithmetic_function ℤ) :
(↑f : arithmetic_function ℤ) = f :=
ext $ λ _, int.cast_id _
@[simp]
lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R]
{f : arithmetic_function ℤ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
@[simp]
lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} :
((f : arithmetic_function ℤ) : arithmetic_function R) = f :=
by { ext, simp, }
section add_monoid
variable [add_monoid R]
instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩
@[simp]
lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl
instance : add_monoid (arithmetic_function R) :=
{ add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _),
zero_add := λ _, ext (λ _, zero_add _),
add_zero := λ _, ext (λ _, add_zero _),
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_add }
end add_monoid
instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) :=
{ add_comm := λ _ _, ext (λ _, add_comm _ _),
.. arithmetic_function.add_monoid }
instance [add_group R] : add_group (arithmetic_function R) :=
{ neg := λ f, ⟨λ n, - f n, by simp⟩,
add_left_neg := λ _, ext (λ _, add_left_neg _),
.. arithmetic_function.add_monoid }
instance [add_comm_group R] : add_comm_group (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_monoid,
.. arithmetic_function.add_group }
section has_scalar
variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M]
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance : has_scalar (arithmetic_function R) (arithmetic_function M) :=
⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩
@[simp]
lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} :
(f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl
end has_scalar
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩
@[simp]
lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} :
(f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl
section module
variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) :
(f * g) • h = f • g • h :=
begin
ext n,
simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'],
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_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩,
refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨i0.2, n0.2⟩, },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] },
{ rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂,
simp only [finset.mem_sigma, mem_divisors_antidiagonal,
and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢,
rintros rfl h2 rfl rfl,
exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩,
{ simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩,
refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨n0.1, j0.1⟩ },
{ simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true,
ne.def, mem_sigma, heq_iff_eq] at H ⊢,
rw H.2.1 } }
end
lemma one_smul' (b : arithmetic_function M) :
(1 : arithmetic_function R) • b = b :=
begin
ext,
rw smul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y1ne : y.fst ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y1ne],
end
end module
section semiring
variable [semiring R]
instance : monoid (arithmetic_function R) :=
{ one_mul := one_smul',
mul_one := λ f,
begin
ext,
rw mul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y2ne : y.snd ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y2ne],
end,
mul_assoc := mul_smul',
.. arithmetic_function.has_one,
.. arithmetic_function.has_mul }
instance : semiring (arithmetic_function R) :=
{ zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] },
mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] },
left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] },
right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] },
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_mul,
.. arithmetic_function.has_add,
.. arithmetic_function.add_comm_monoid,
.. arithmetic_function.monoid }
end semiring
instance [comm_semiring R] : comm_semiring (arithmetic_function R) :=
{ mul_comm := λ f g, by { ext,
rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map],
simp [mul_comm] },
.. arithmetic_function.semiring }
instance [comm_ring R] : comm_ring (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_group,
.. arithmetic_function.comm_semiring }
instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] :
module (arithmetic_function R) (arithmetic_function M) :=
{ one_smul := one_smul',
mul_smul := mul_smul',
smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] },
smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] },
add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] },
zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, }
section zeta
/-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/
def zeta : arithmetic_function ℕ :=
⟨λ x, ite (x = 0) 0 1, rfl⟩
localized "notation `ζ` := zeta" in arithmetic_function
@[simp]
lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl
lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h
@[simp]
theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(↑ζ * f) x = ∑ i in divisors x, f i :=
begin
rw mul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M]
{f : arithmetic_function M} {x : ℕ} :
((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i :=
begin
rw smul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
@[simp]
theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
begin
apply opposite.op_injective,
rw [op_sum],
convert @coe_zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x,
rw [mul_apply, mul_apply, op_sum],
conv_lhs { rw ← map_swap_divisors_antidiagonal, },
rw sum_map,
apply sum_congr rfl,
intros y hy,
by_cases h1 : y.fst = 0,
{ simp [function.comp_apply, h1] },
{ simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap,
if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] }
end
theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} :
(ζ * f) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_zeta_mul_apply]
theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_mul_zeta_apply]
end zeta
open_locale arithmetic_function
section pmul
/-- This is the pointwise product of `arithmetic_function`s. -/
def pmul [mul_zero_class R] (f g : arithmetic_function R) :
arithmetic_function R :=
⟨λ x, f x * g x, by simp⟩
@[simp]
lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} :
f.pmul g x = f x * g x := rfl
lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) :
f.pmul g = g.pmul f :=
by { ext, simp [mul_comm] }
variable [semiring R]
@[simp]
lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
@[simp]
lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
/-- This is the pointwise power of `arithmetic_function`s. -/
def ppow (f : arithmetic_function R) (k : ℕ) :
arithmetic_function R :=
if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k,
by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩
@[simp]
lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ :=
by rw [ppow, dif_pos rfl]
@[simp]
lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) :
f.ppow k x = (f x) ^ k :=
by { rw [ppow, dif_neg (ne_of_gt kpos)], refl }
lemma ppow_succ {f : arithmetic_function R} {k : ℕ} :
f.ppow (k + 1) = f.pmul (f.ppow k) :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ],
induction k; simp,
end
lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} :
f.ppow (k + 1) = (f.ppow k).pmul f :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ'],
induction k; simp,
end
end pmul
/-- Multiplicative functions -/
def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop :=
f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n)
namespace is_multiplicative
section monoid_with_zero
variable [monoid_with_zero R]
@[simp]
lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 :=
h.1
@[simp]
lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative)
{m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n :=
hf.2 h
end monoid_with_zero
lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma mul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f * g) :=
⟨by { simp [hf, hg], }, begin
simp only [mul_apply],
intros m n cop,
rw sum_mul_sum,
symmetry,
apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)),
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def],
split, {ring},
rw nat.mul_eq_zero at *,
apply not_or ha hb },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
dsimp only,
rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right,
hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right],
ring, },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab,
rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd,
simp only [prod.mk.inj_iff] at h,
ext; dsimp only,
{ transitivity nat.gcd (a1 * a2) (a1 * b1),
{ rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.1, nat.gcd_mul_left,
cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (a1 * a2) (a2 * b2),
{ rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one,
mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a1 * b1),
{ rw [mul_comm, nat.gcd_mul_right,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a2 * b2),
{ rw [nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.2, nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } },
{ rintros ⟨b1, b2⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)),
simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal],
rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1,
nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _],
{ rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] },
rw [mul_comm n m, h.1] }
end⟩
lemma pmul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f.pmul g) :=
⟨by { simp [hf, hg], }, λ m n cop, begin
simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop],
ring,
end⟩
end is_multiplicative
section special_functions
/-- The identity on `ℕ` as an `arithmetic_function`. -/
def id : arithmetic_function ℕ := ⟨id, rfl⟩
@[simp]
lemma id_apply {x : ℕ} : id x = x := rfl
/-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/
def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k
@[simp]
lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k :=
begin
cases k,
{ simp [pow] },
simp [pow, (ne_of_lt (nat.succ_pos k)).symm],
end
/-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/
def sigma (k : ℕ) : arithmetic_function ℕ :=
⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩
localized "notation `σ` := sigma" in arithmetic_function
@[simp]
lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl
lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp
lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k :=
begin
ext,
rw [sigma, zeta_mul_apply],
apply sum_congr rfl,
intros x hx,
rw [pow_apply, if_neg (not_and_of_not_right _ _)],
contrapose! hx,
simp [hx],
end
lemma is_multiplicative_zeta : is_multiplicative ζ :=
⟨by simp, λ m n cop, begin
cases m, {simp},
cases n, {simp},
simp [nat.succ_ne_zero]
end⟩
lemma is_multiplicative_id : is_multiplicative arithmetic_function.id :=
⟨rfl, λ _ _ _, rfl⟩
lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R}
(hf : f.is_multiplicative) {k : ℕ} :
is_multiplicative (f.ppow k) :=
begin
induction k with k hi,
{ exact is_multiplicative_zeta.nat_cast },
{ rw ppow_succ,
apply hf.pmul hi },
end
lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) :=
is_multiplicative_id.ppow
lemma is_multiplicative_sigma {k : ℕ} :
is_multiplicative (sigma k) :=
begin
rw [← zeta_mul_pow_eq_sigma],
apply ((is_multiplicative_zeta).mul is_multiplicative_pow)
end
/-- `Ω n` is the number of prime factors of `n`. -/
def card_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.length, by simp⟩
localized "notation `Ω` := card_factors" in arithmetic_function
lemma card_factors_apply {n : ℕ} :
Ω n = n.factors.length := rfl
@[simp]
lemma card_factors_one : Ω 1 = 0 := by simp [card_factors]
lemma card_factors_eq_one_iff_prime {n : ℕ} :
Ω n = 1 ↔ n.prime :=
begin
refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩,
cases n,
{ contrapose! h,
simp },
rcases list.length_eq_one.1 h with ⟨x, hx⟩,
rw [← prod_factors n.succ_pos, hx, list.prod_singleton],
apply prime_of_mem_factors,
rw [hx, list.mem_singleton]
end
lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) :
Ω (m * n) = Ω m + Ω n :=
by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card,
← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq,
multiset.card_add, multiset.coe_card, multiset.coe_card]
lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) :
Ω s.prod = (multiset.map Ω s).sum :=
begin
revert h0,
apply s.induction_on, by simp,
intros a t h h0,
rw [multiset.prod_cons, mul_ne_zero_iff] at h0,
simp [h0, card_factors_mul, h],
end
/-- `ω n` is the number of distinct prime factors of `n`. -/
def card_distinct_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.erase_dup.length, by simp⟩
localized "notation `ω` := card_distinct_factors" in arithmetic_function
lemma card_distinct_factors_zero : ω 0 = 0 := by simp
lemma card_distinct_factors_apply {n : ℕ} :
ω n = n.factors.erase_dup.length := rfl
lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) :
ω n = Ω n ↔ squarefree n :=
begin
rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply],
split; intro h,
{ rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h,
apply list.nodup_erase_dup },
{ rw h.erase_dup,
refl }
end
/-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors,
`μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`.
If `n` is not squarefree, `μ n = 0`. -/
def moebius : arithmetic_function ℤ :=
⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩
localized "notation `μ` := moebius" in arithmetic_function
@[simp]
lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) :=
if_pos h
@[simp]
lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h
lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n :=
begin
split; intro h,
{ contrapose! h,
simp [h] },
{ simp [h, pow_ne_zero] }
end
lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 :=
begin
split; intro h,
{ rw moebius_ne_zero_iff_squarefree at h,
rw moebius_apply_of_squarefree h,
apply neg_one_pow_eq_or },
{ rcases h with h | h; simp [h] }
end
open unique_factorization_monoid
@[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 :=
begin
ext x,
cases x,
{ simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply,
zero_ne_one, one_apply_ne] },
cases x,
{ simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one,
int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] },
rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))],
simp_rw [int_coe_apply],
rw [←int.cast_sum, ← sum_filter_ne_zero],
convert int.cast_zero,
simp only [moebius_ne_zero_iff_squarefree],
suffices :
∑ (y : finset ℕ) in
(unique_factorization_monoid.normalized_factors x.succ.succ).to_finset.powerset,
ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0,
{ have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ :=
(sum_divisors_filter_squarefree (nat.succ_ne_zero _)),
exact (eq.trans (by congr') h).trans this },
apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _),
{ intros y hy,
rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy,
have h : unique_factorization_monoid.normalized_factors y.val.prod = y.val,
{ apply factors_multiset_prod_of_irreducible,
intros z hz,
apply irreducible_of_normalized_factor _ (multiset.subset_of_le
(le_trans hy (multiset.erase_dup_le _)) hz) },
rw [if_pos],
{ rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] },
rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors, h],
{ apply y.nodup },
rw [ne.def, multiset.prod_eq_zero_iff],
intro con,
rw ← h at con,
exact not_irreducible_zero (irreducible_of_normalized_factor 0 con) },
{ rw finset.nonempty,
rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩,
{ rcases exists_mem_normalized_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩,
use j,
apply multiset.mem_to_finset.2 hj },
rw nat.is_unit_iff,
norm_num },
end
@[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 :=
by rw [mul_comm, coe_moebius_mul_coe_zeta]
@[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 :=
by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta]
@[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 :=
by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius]
section comm_ring
variable [comm_ring R]
instance : invertible (ζ : arithmetic_function R) :=
{ inv_of := μ,
inv_of_mul_self := coe_moebius_mul_coe_zeta,
mul_inv_of_self := coe_zeta_mul_coe_moebius}
/-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/
def zeta_unit : units (arithmetic_function R) :=
⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩
@[simp]
lemma coe_zeta_unit :
((zeta_unit : units (arithmetic_function R)) : arithmetic_function R) = ζ := rfl
@[simp]
lemma inv_zeta_unit :
((zeta_unit⁻¹ : units (arithmetic_function R)) : arithmetic_function R) = μ := rfl
end comm_ring
/-- Möbius inversion for functions to an `add_comm_group`. -/
theorem sum_eq_iff_sum_smul_moebius_eq
[add_comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n :=
begin
let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩,
let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩,
transitivity (ζ : arithmetic_function ℤ) • f' = g',
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
rw coe_zeta_smul_apply,
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) },
transitivity μ • g' = f',
{ split; intro h,
{ rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] },
{ rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } },
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply,
if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) },
end
/-- Möbius inversion for functions to a `comm_ring`. -/
theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n :=
begin
rw sum_eq_iff_sum_smul_moebius_eq,
apply forall_congr,
intro a,
apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))),
rw [zsmul_eq_mul],
end
/-- Möbius inversion for functions to a `comm_group`. -/
theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
@sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _
/-- Möbius inversion for functions to a `comm_group_with_zero`. -/
theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R}
(hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
begin
refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq (units R) _
(λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1)
(λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _));
refine imp_congr_right (λ hn, _),
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] },
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)),
units.coe_hom_apply, units.coe_zpow₀, units.coe_mk0] }
end
end special_functions
end arithmetic_function
end nat
|
115495179cb8fd03de9b1879c0863ff3c81fd7d3 | 9c1ad797ec8a5eddb37d34806c543602d9a6bf70 | /examples/semigroups/dev.lean | 4ff71ff3ddc70010e6fd3faddabcae36c2244b51 | [] | no_license | timjb/lean-category-theory | 816eefc3a0582c22c05f4ee1c57ed04e57c0982f | 12916cce261d08bb8740bc85e0175b75fb2a60f4 | refs/heads/master | 1,611,078,926,765 | 1,492,080,000,000 | 1,492,080,000,000 | 88,348,246 | 0 | 0 | null | 1,492,262,499,000 | 1,492,262,498,000 | null | UTF-8 | Lean | false | false | 1,533 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import ...monoidal_categories.braided_monoidal_category
import .monoidal_category_of_semigroups
open tqft.categories.natural_transformation
open tqft.categories.braided_monoidal_category
namespace tqft.categories.examples.semigroups
definition SymmetryOnCategoryOfSemigroups' : Symmetry MonoidalStructureOnCategoryOfSemigroups :=
begin
refine {
braiding := {
morphism := {
components := λ _, {
map := λ p, (p.2, p.1),
multiplicative := ♮
},
naturality := ♮
},
inverse := _,
witness_1 := _,
witness_2 := _
},
hexagon_1 := sorry,
hexagon_2 := sorry,
symmetry := sorry
},
-- Everything below is an attempt to build the inverse in a way that automation could conceivably handle.
unfold_unfoldable,
split,
intros X Y f,
dsimp at X,
induction X with X1 X2,
induction X1 with X1α X1s,
induction X2 with X2α X2s,
dsimp at Y,
induction Y with Y1 Y2,
induction Y1 with Y1α Y1s,
induction Y2 with Y2α Y2s,
dsimp at f,
induction f with f1 f2,
simp,
apply semigroup_morphism_pointwise_equality,
intros x,
dsimp at x,
unfold TensorProduct_for_Semigroups at x,
dsimp at x,
induction x with x1 x2,
dsimp,
end
end tqft.categories.examples.semigroups |
9de35ac710dce7a5c58f6d6ea93a7c9e5d0a69d2 | 367134ba5a65885e863bdc4507601606690974c1 | /src/deprecated/group.lean | da15775f37bbeeaebaad1b2df369fa20c63f5699 | [
"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 | 13,559 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import algebra.group.type_tags
import algebra.group.units_hom
import algebra.ring.basic
import data.equiv.mul_add
/-!
# Unbundled monoid and group homomorphisms (deprecated)
This file defines typeclasses for unbundled monoid and group homomorphisms. Though these classes are
deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4
because Lean 3 often fails to coerce a bundled homomorphism to a function.
## main definitions
is_monoid_hom (deprecated), is_group_hom (deprecated)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
## Tags
is_group_hom, is_monoid_hom, monoid_hom
-/
/--
We have lemmas stating that the composition of two morphisms is again a morphism.
Since composition is reducible, type class inference will always succeed in applying these
instances. For example when the goal is just `⊢ is_mul_hom f` the instance `is_mul_hom.comp`
will still succeed, unifying `f` with `f ∘ (λ x, x)`. This causes type class inference to loop.
To avoid this, we do not make these lemmas instances.
-/
library_note "no instance on morphisms"
universes u v
variables {α : Type u} {β : Type v}
/-- Predicate for maps which preserve an addition. -/
class is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop :=
(map_add [] : ∀ x y, f (x + y) = f x + f y)
/-- Predicate for maps which preserve a multiplication. -/
@[to_additive]
class is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop :=
(map_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_mul_hom
variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ]
/-- The identity map preserves multiplication. -/
@[to_additive "The identity map preserves addition"]
instance id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl}
/-- The composition of maps which preserve multiplication, also preserves multiplication. -/
-- see Note [no instance on morphisms]
@[to_additive "The composition of addition preserving maps also preserves addition"]
lemma comp (f : α → β) (g : β → γ) [is_mul_hom f] [hg : is_mul_hom g] : is_mul_hom (g ∘ f) :=
{ map_mul := λ x y, by simp only [function.comp, map_mul f, map_mul g] }
/-- A product of maps which preserve multiplication,
preserves multiplication when the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [semigroup α] [comm_semigroup β]
(f g : α → β) [is_mul_hom f] [is_mul_hom g] :
is_mul_hom (λa, f a * g a) :=
{ map_mul := assume a b, by simp only [map_mul f, map_mul g, mul_comm, mul_assoc, mul_left_comm] }
/-- The inverse of a map which preserves multiplication,
preserves multiplication when the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [has_mul α] [comm_group β] (f : α → β) [is_mul_hom f] :
is_mul_hom (λa, (f a)⁻¹) :=
{ map_mul := assume a b, (map_mul f a b).symm ▸ mul_inv _ _ }
end is_mul_hom
/-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) extends is_add_hom f : Prop :=
(map_zero [] : f 0 = 0)
/-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
@[to_additive]
class is_monoid_hom [monoid α] [monoid β] (f : α → β) extends is_mul_hom f : Prop :=
(map_one [] : f 1 = 1)
namespace monoid_hom
/-!
Throughout this section, some `monoid` arguments are specified with `{}` instead of `[]`.
See note [implicit instance arguments].
-/
variables {M : Type*} {N : Type*} {P : Type*} [mM : monoid M] [mN : monoid N] {mP : monoid P}
variables {G : Type*} {H : Type*} [group G] [comm_group H]
include mM mN
/-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/
@[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."]
def of (f : M → N) [h : is_monoid_hom f] : M →* N :=
{ to_fun := f,
map_one' := h.2,
map_mul' := h.1.1 }
variables {mM mN mP}
@[simp, to_additive]
lemma coe_of (f : M → N) [is_monoid_hom f] : ⇑ (monoid_hom.of f) = f :=
rfl
@[to_additive]
instance (f : M →* N) : is_monoid_hom (f : M → N) :=
{ map_mul := f.map_mul,
map_one := f.map_one }
end monoid_hom
namespace mul_equiv
variables {M : Type*} {N : Type*} [monoid M] [monoid N]
/-- A multiplicative isomorphism preserves multiplication (deprecated). -/
@[to_additive]
instance (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩
/-- A multiplicative bijection between two monoids is a monoid hom
(deprecated -- use to_monoid_hom). -/
@[to_additive]
instance {M N} [monoid M] [monoid N] (h : M ≃* N) : is_monoid_hom h :=
⟨h.map_one⟩
end mul_equiv
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- A monoid homomorphism preserves multiplication. -/
@[to_additive]
lemma map_mul (x y) : f (x * y) = f x * f y :=
is_mul_hom.map_mul f x y
end is_monoid_hom
/-- A map to a group preserving multiplication is a monoid homomorphism. -/
@[to_additive]
theorem is_monoid_hom.of_mul [monoid α] [group β] (f : α → β) [is_mul_hom f] :
is_monoid_hom f :=
{ map_one := mul_right_eq_self.1 $ by rw [← is_mul_hom.map_mul f, one_mul] }
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- The identity map is a monoid homomorphism. -/
@[to_additive]
instance id : is_monoid_hom (@id α) := { map_one := rfl }
/-- The composite of two monoid homomorphisms is a monoid homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] :
is_monoid_hom (g ∘ f) :=
{ map_one := show g _ = 1, by rw [map_one f, map_one g], ..is_mul_hom.comp _ _ }
end is_monoid_hom
namespace is_add_monoid_hom
/-- Left multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, x * y) :=
{ map_zero := mul_zero x, map_add := λ y z, mul_add x y z }
/-- Right multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, y * x) :=
{ map_zero := zero_mul x, map_add := λ y z, add_mul y z x }
end is_add_monoid_hom
/-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/
class is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop
/-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/
@[to_additive]
class is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop
@[to_additive]
instance monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) :
is_group_hom (f : G → H) :=
{ map_mul := f.map_mul }
@[to_additive]
instance mul_equiv.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (h : G ≃* H) :
is_group_hom h := { map_mul := h.map_mul }
/-- Construct `is_group_hom` from its only hypothesis. The default constructor tries to get
`is_mul_hom` from class instances, and this makes some proofs fail. -/
@[to_additive]
lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) :
is_group_hom f :=
{ map_mul := hf }
namespace is_group_hom
variables [group α] [group β] (f : α → β) [is_group_hom f]
open is_mul_hom (map_mul)
/-- A group homomorphism is a monoid homomorphism. -/
@[priority 100, to_additive] -- see Note [lower instance priority]
instance to_is_monoid_hom : is_monoid_hom f :=
is_monoid_hom.of_mul f
/-- A group homomorphism sends 1 to 1. -/
@[to_additive]
lemma map_one : f 1 = 1 := is_monoid_hom.map_one f
/-- A group homomorphism sends inverses to inverses. -/
@[to_additive]
theorem map_inv (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [← map_mul f, inv_mul_self, map_one f]
/-- The identity is a group homomorphism. -/
@[to_additive]
instance id : is_group_hom (@id α) := { }
/-- The composition of two group homomorphisms is a group homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) :=
{ ..is_mul_hom.comp _ _ }
/-- A group homomorphism is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff (f : α → β) [is_group_hom f] :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h _, by rw ← is_group_hom.map_one f; exact @h _ _,
λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← map_inv f,
← map_mul f] at hxy;
simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩
/-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [group α] [comm_group β]
(f g : α → β) [is_group_hom f] [is_group_hom g] :
is_group_hom (λa, f a * g a) :=
{ }
/-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] :
is_group_hom (λa, (f a)⁻¹) :=
{ }
end is_group_hom
namespace ring_hom
/-!
These instances look redundant, because `deprecated.ring` provides `is_ring_hom` for a `→+*`.
Nevertheless these are harmless, and helpful for stripping out dependencies on `deprecated.ring`.
-/
variables {R : Type*} {S : Type*}
section
variables [semiring R] [semiring S]
instance (f : R →+* S) : is_monoid_hom f :=
{ map_one := f.map_one,
map_mul := f.map_mul }
instance (f : R →+* S) : is_add_monoid_hom f :=
{ map_zero := f.map_zero,
map_add := f.map_add }
end
section
variables [ring R] [ring S]
instance (f : R →+* S) : is_add_group_hom f :=
{ map_add := f.map_add }
end
end ring_hom
/-- Inversion is a group homomorphism if the group is commutative. -/
@[instance, to_additive neg.is_add_group_hom
"Negation is an `add_group` homomorphism if the `add_group` is commutative."]
lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) :=
{ map_mul := mul_inv }
namespace is_add_group_hom
variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f]
/-- Additive group homomorphisms commute with subtraction. -/
lemma map_sub (a b) : f (a - b) = f a - f b :=
calc f (a - b) = f (a + -b) : congr_arg f (sub_eq_add_neg a b)
... = f a + f (-b) : is_add_hom.map_add f _ _
... = f a + -f b : by rw [map_neg f]
... = f a - f b : (sub_eq_add_neg _ _).symm
end is_add_group_hom
/-- The difference of two additive group homomorphisms is an additive group
homomorphism if the target is commutative. -/
@[instance]
lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β]
(f g : α → β) [is_add_group_hom f] [is_add_group_hom g] :
is_add_group_hom (λa, f a - g a) :=
by { simp only [sub_eq_add_neg], exact is_add_group_hom.add f (λa, - g a) }
namespace units
variables {M : Type*} {N : Type*} [monoid M] [monoid N]
/-- The group homomorphism on units induced by a multiplicative morphism. -/
@[reducible] def map' (f : M → N) [is_monoid_hom f] : units M →* units N :=
map (monoid_hom.of f)
@[simp] lemma coe_map' (f : M → N) [is_monoid_hom f] (x : units M) :
↑((map' f : units M → units N) x) = f x :=
rfl
instance coe_is_monoid_hom : is_monoid_hom (coe : units M → M) := (coe_hom M).is_monoid_hom
end units
namespace is_unit
variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M}
lemma map' (f : M → N) {x : M} (h : is_unit x) [is_monoid_hom f] :
is_unit (f x) :=
h.map (monoid_hom.of f)
end is_unit
lemma additive.is_add_hom [has_mul α] [has_mul β] (f : α → β) [is_mul_hom f] :
@is_add_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_mul_hom [has_add α] [has_add β] (f : α → β) [is_add_hom f] :
@is_mul_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
lemma additive.is_add_monoid_hom [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] :
@is_add_monoid_hom (additive α) (additive β) _ _ f :=
{ map_zero := @is_monoid_hom.map_one α β _ _ f _,
..additive.is_add_hom f }
lemma multiplicative.is_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] :
@is_monoid_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_one := @is_add_monoid_hom.map_zero α β _ _ f _,
..multiplicative.is_mul_hom f }
lemma additive.is_add_group_hom [group α] [group β] (f : α → β) [is_group_hom f] :
@is_add_group_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_group_hom [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] :
@is_group_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
|
0decd296f5270581ab3497a91a326b1fa70e26da | a76f677b87d42a9470ba3a0a78cfddd3063118e6 | /src/incidence/basic.lean | 8476cd383163f95f18479c07b9b37e98b05981c0 | [] | no_license | Ja1941/hilberts-axioms | 50219c732ad5fa167408432e8c8baae259777a40 | 5b653a92e448b77da41c9893066b641bc4e6b316 | refs/heads/master | 1,693,238,884,856 | 1,635,702,120,000 | 1,635,702,120,000 | 385,546,384 | 9 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 11,716 | lean | /-
Copyright (c) 2021 Tianchen Zhao. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tianchen Zhao
-/
import set_theory.zfc
/-!
# Incidence geometry
This file defines incidence geometry as a class and proves basic lemmas about
points, lines and collinearity.
## Main definitions
* `incidence_geometry` is a class satisfying the three axioms of incidence.
* `line`, with notation `-ₗ`, is the unique line determined by the given two points.
* `col` is a ternary relation among points meaning they lie on the same line.
* `noncol` is the opposite of `col`.
## References
* See [Geometry: Euclid and Beyond]
-/
universes u
/--An incidence geometry contains a type `pts` and a set `lines` that includes some sets of pts,
with the following axioms :
I1. Two distinct points uniquely define a line.
I2. Every line contains at least 2 distinct points.
I3. There exists 3 noncol points.
-/
class incidence_geometry :=
(pts : Type u) (lines : set (set pts))
(I1 : ∀ {a b : pts}, a ≠ b → ∃ l ∈ lines,
a ∈ l ∧ b ∈ l ∧ (∀ l' ∈ lines, a ∈ l' → b ∈ l' → l' = l))
(I2 : ∀ l ∈ lines, ∃ a b : pts, a ≠ b ∧ a ∈ l ∧ b ∈ l)
(I3 : ∃ a b c : pts, a ≠ b ∧ a ≠ c ∧ b ≠ c ∧ ¬(∃ l ∈ lines, a ∈ l ∧ b ∈ l ∧ c ∈ l))
open incidence_geometry
variable [I : incidence_geometry]
include I
/--A line is a set of points defined given two points.
If two points are distinct, it is given by I1. Otherwise, it is defined as a singleton, but
this almost never occurs later.
-/
noncomputable def line (a b : pts) :
{ L : set pts // (a ≠ b → L ∈ lines) ∧ a ∈ L ∧ b ∈ L ∧ (a = b → L = {a}) } :=
begin
by_cases hab : a = b, rw hab,
exact ⟨{b}, λ hf, absurd rfl hf, by simp⟩,
choose l hl ha hb h using (I1 hab),
exact ⟨l, λ h, hl, ha, hb, λh, absurd h hab⟩
end
notation a`-ₗ`b := (line a b : set pts)
/--Two sets of points intersect if their intersection is nonempty. -/
def intersect [I : incidence_geometry] (m n : set pts) : Prop := (m ∩ n).nonempty
notation m`♥`n := intersect m n
lemma intersect_symm {m n : set pts} :
(m ♥ n) → (n ♥ m) :=
by {unfold intersect, rw set.inter_comm, simp only [imp_self]}
/--Two lines are parallel if they have no intersection. -/
def parallel (l₁ l₂ : set pts) : Prop :=
¬(l₁ ♥ l₂) ∧ (l₁ ∈ lines) ∧ (l₂ ∈ lines)
notation l₁`∥ₗ`l₂ := parallel l₁ l₂
lemma parallel_symm {l₁ l₂ : set pts} :
(l₁ ∥ₗ l₂) → (l₂ ∥ₗ l₁) :=
begin
rintros ⟨hl₁l₂, hl₁, hl₂⟩,
exact ⟨λhf, hl₁l₂ (intersect_symm hf), hl₂, hl₁⟩
end
lemma line_in_lines {a b : pts} (hab : a ≠ b) :
(a-ₗb) ∈ lines := (line a b).2.1 hab
lemma pt_left_in_line (a b : pts) :
a ∈ (a-ₗb) := (line a b).2.2.1
lemma pt_right_in_line (a b : pts) :
b ∈ (a-ₗb) := (line a b).2.2.2.1
lemma one_pt_line (a : pts) : ∃ l ∈ lines, a ∈ l :=
begin
have : ∃ b : pts, a ≠ b,
by_contra hf, push_neg at hf,
rcases I3 with ⟨x, y, z, h, -⟩, exact h ((hf x).symm.trans (hf y)),
cases this with b hab,
exact ⟨line a b, line_in_lines hab, pt_left_in_line a b⟩
end
lemma two_pt_line_unique {a b : pts} (hab : a ≠ b)
{l : set pts} (hl : l ∈ lines) (ha : a ∈ l) (hb : b ∈ l) : l = (a-ₗb) :=
begin
rcases (I1 hab) with ⟨n, hn, -, -, key⟩,
rw [key l hl ha hb,
key (a-ₗb) (line_in_lines hab) (pt_left_in_line a b) (pt_right_in_line a b)]
end
lemma two_pt_on_one_line {l : set pts} (hl : l ∈ lines) :
∃ a b : pts, a ≠ b ∧ a ∈ l ∧ b ∈ l := I2 l hl
lemma line_two_pt {a b : pts} (hl : (a-ₗb) ∈ lines) : a ≠ b :=
begin
intro hf,
rw [hf, ←subtype.val_eq_coe, (line b b).2.2.2.2 rfl] at hl,
rcases two_pt_on_one_line hl with ⟨x, y, hxy, hx, hy⟩,
rw set.mem_singleton_iff at hx hy,
rw [hx, hy] at hxy,
exact hxy rfl
end
-- this would be much better as a ∈ l → b ∈ l → a ∈ m → ... (all before the colon!)
lemma two_pt_one_line {l m : set pts} (hl : l ∈ lines) (hm : m ∈ lines)
{a b : pts} (hab : a ≠ b) (hal : a ∈ l) (hbl : b ∈ l) (ham : a ∈ m) (hbm : b ∈ m) : l = m :=
(two_pt_line_unique hab hl hal hbl).trans(two_pt_line_unique hab hm ham hbm).symm
lemma line_symm (a b : pts) : (a-ₗb) = (b-ₗa) :=
begin
by_cases a = b, rw h,
exact two_pt_one_line (line_in_lines h) (line_in_lines (ne.symm h))
h (pt_left_in_line a b) (pt_right_in_line a b) (pt_right_in_line b a) (pt_left_in_line b a)
end
lemma two_line_one_pt {l₁ l₂ : set pts} (hl₁ : l₁ ∈ lines) (hl₂ : l₂ ∈ lines) :
∀ {a b : pts}, l₁ ≠ l₂ → a ∈ l₁ → a ∈ l₂ → b ∈ l₁ → b ∈ l₂ → a = b :=
begin
intros a b hll ha₁ ha₂ hb₁ hb₂,
by_cases hab : a = b, exact hab,
rcases (I1 hab) with ⟨l, hl, -, -, key⟩,
exact absurd ((key l₁ hl₁ ha₁ hb₁).trans (key l₂ hl₂ ha₂ hb₂).symm) hll
end
/--Three points are col if there are on the same line. -/
def col (a b c : pts) : Prop :=
∃ l ∈ lines, a ∈ l ∧ b ∈ l ∧ c ∈ l
/--Opposite to col -/
def noncol (a b c : pts) : Prop := ¬col a b c
lemma noncol_exist {a b : pts} (hab : a ≠ b) : ∃ c : pts, noncol a b c :=
begin
by_contra hf, unfold noncol col at hf, push_neg at hf,
rcases I3 with ⟨x, y, z, hxy, hxz, hyz, hxyz⟩,
rcases hf x with ⟨l, hl, hal, hbl, hxl⟩,
rcases hf y with ⟨m, hm, ham, hbm, hym⟩,
rcases hf z with ⟨n, hn, han, hbn, hzn⟩,
rw ←two_pt_one_line hl hm hab hal hbl ham hbm at hym,
rw ←two_pt_one_line hl hn hab hal hbl han hbn at hzn,
exact hxyz ⟨l, hl, hxl, hym, hzn⟩
end
lemma noncol_neq {a b c : pts} (hf : noncol a b c) : a ≠ b ∧ a ≠ c ∧ b ≠ c :=
begin
have : ∀ a b : pts, ∃ l ∈ lines, a ∈ l ∧ b ∈ l,
intros a b, by_cases a = b,
rw ←h, simp,
have : ∃ p : pts, a ≠ p,
by_contra, push_neg at h,
rcases I3 with ⟨x, y, -, hxy, -, -, -⟩,
exact hxy ((h x).symm .trans (h y)),
cases this with b h,
use (a-ₗb), exact ⟨line_in_lines h, pt_left_in_line a b⟩,
use (a-ₗb), exact ⟨line_in_lines h, pt_left_in_line a b, pt_right_in_line a b⟩,
split, intro h,
rw h at hf,
rcases this b c with ⟨l, hl, key⟩,
exact hf ⟨l, hl, key.1, key.1, key.2⟩,
split, intro h,
rw h at hf,
rcases this c b with ⟨l, hl, key⟩,
exact hf ⟨l, hl, key.1, key.2, key.1⟩,
intro h, rw h at hf,
rcases this a c with ⟨l, hl, key⟩,
exact hf ⟨l, hl, key.1, key.2, key.2⟩
end
lemma col12 {a b c : pts} : col a b c → col b a c :=
by {rintros ⟨l, hl, habc⟩, use l, tauto}
lemma noncol12 {a b c : pts} : noncol a b c → noncol b a c :=
by {unfold noncol, contrapose!, exact col12}
lemma col13 {a b c : pts} : col a b c → col c b a :=
by {rintros ⟨l, hl, habc⟩, use l, tauto}
lemma noncol13 {a b c : pts} : noncol a b c → noncol c b a :=
by {unfold noncol, contrapose!, exact col13}
lemma col23 {a b c : pts} : col a b c → col a c b :=
by {rintros ⟨l, hl, habc⟩, use l, tauto}
lemma noncol23 {a b c : pts} : noncol a b c → noncol a c b :=
by {unfold noncol, contrapose!, exact col23}
lemma col123 {a b c : pts} : col a b c → col b c a :=
λh, col23 (col12 h)
lemma col132 {a b c : pts} : col a b c → col c a b :=
λh, col23 (col13 h)
lemma noncol123 {a b c : pts} : noncol a b c → noncol b c a :=
by {unfold noncol, contrapose!, exact col132}
lemma noncol132 {a b c : pts} : noncol a b c → noncol c a b :=
by {unfold noncol, contrapose!, exact col123}
lemma col_trans {a b c d : pts} (habc : col a b c) (habd : col a b d)
(hab : a ≠ b) : col a c d :=
begin
rcases habc with ⟨l, hl, hal, hbl, hcl⟩, rcases habd with ⟨m, hm, ham, hbm, hdm⟩,
rw two_pt_one_line hm hl hab ham hbm hal hbl at hdm,
exact ⟨l, hl, hal, hcl, hdm⟩
end
lemma col_noncol {a b c d : pts} (habc : col a b c) (habd : noncol a b d) :
a ≠ c → noncol a c d :=
λhac hacd, habd (col_trans (col23 habc) hacd hac)
lemma col_in12 {a b c : pts} : col a b c → a ≠ b → c ∈ (a-ₗb) :=
begin
rintros ⟨l, hl, hal, hbl, hcl⟩, intro hab,
rw two_pt_one_line hl (line_in_lines hab) hab
hal hbl (pt_left_in_line a b) (pt_right_in_line a b) at hcl,
exact hcl
end
lemma col_in21 {a b c : pts} : col a b c → b ≠ a → c ∈ (b-ₗa) :=
by {rw line_symm, exact λhabc hba, col_in12 habc hba.symm}
lemma col_in13 {a b c : pts} : col a b c → a ≠ c → b ∈ (a-ₗc) :=
begin
rintros ⟨l, hl, hal, hbl, hcl⟩, intro hac,
rw two_pt_one_line hl (line_in_lines hac) hac
hal hcl (pt_left_in_line a c) (pt_right_in_line a c) at hbl,
exact hbl
end
lemma col_in31 {a b c : pts} : col a b c → c ≠ a → b ∈ (c-ₗa) :=
by {rw line_symm, exact λhabc hca, col_in13 habc hca.symm}
lemma col_in23 {a b c : pts} : col a b c → b ≠ c → a ∈ (b-ₗc) :=
begin
rintros ⟨l, hl, hal, hbl, hcl⟩, intro hbc,
rw two_pt_one_line hl (line_in_lines hbc) hbc
hbl hcl (pt_left_in_line b c) (pt_right_in_line b c) at hal,
exact hal
end
lemma col_in32 {a b c : pts} : col a b c → c ≠ b → a ∈ (c-ₗb) :=
by {rw line_symm, exact λhabc hcb, col_in23 habc hcb.symm}
lemma noncol_in12 {a b c : pts} : noncol a b c → c ∉ (a-ₗb) :=
λ habc hc, habc ⟨(a-ₗb), line_in_lines (noncol_neq habc).1,
pt_left_in_line a b, pt_right_in_line a b, hc⟩
lemma noncol_in21 {a b c : pts} : noncol a b c → c ∉ (b-ₗa) :=
by {rw line_symm, exact noncol_in12}
lemma noncol_in13 {a b c : pts} : noncol a b c → b ∉ (a-ₗc) :=
λ habc hb, habc ⟨(a-ₗc), line_in_lines (noncol_neq habc).2.1,
pt_left_in_line a c, hb, pt_right_in_line a c⟩
lemma noncol_in31 {a b c : pts} : noncol a b c → b ∉ (c-ₗa) :=
by {rw line_symm, exact noncol_in13}
lemma noncol_in23 {a b c : pts} : noncol a b c → a ∉ (b-ₗc) :=
λ habc ha, habc ⟨(b-ₗc), line_in_lines (noncol_neq habc).2.2, ha,
pt_left_in_line b c, pt_right_in_line b c⟩
lemma noncol_in32 {a b c : pts} : noncol a b c → a ∉ (c-ₗb) :=
by {rw line_symm, exact noncol_in23}
lemma col_in12' {a b c : pts} : c ∈ (a-ₗb) → col a b c :=
by { intro h, by_contra habc, exact (noncol_in12 habc) h }
lemma col_in21' {a b c : pts} : c ∈ (b-ₗa) → col a b c :=
by { rw line_symm, exact col_in12' }
lemma col_in13' {a b c : pts} : b ∈ (a-ₗc) → col a b c :=
by { intro h, by_contra habc, exact (noncol_in13 habc) h }
lemma col_in31' {a b c : pts} : b ∈ (c-ₗa) → col a b c :=
by { rw line_symm, exact col_in13' }
lemma col_in23' {a b c : pts} : a ∈ (b-ₗc) → col a b c :=
by { intro h, by_contra habc, exact (noncol_in23 habc) h }
lemma col_in32' {a b c : pts} : a ∈ (c-ₗb) → col a b c :=
by { rw line_symm, exact col_in23' }
lemma noncol_in12' {a b c : pts} (hab : a ≠ b) : c ∉ (a-ₗb) → noncol a b c :=
by { contrapose!, intro h, unfold noncol at h, rw not_not at h,
exact col_in12 h hab }
lemma noncol_in21' {a b c : pts} (hba : b ≠ a) : c ∉ (b-ₗa) → noncol a b c :=
by { rw line_symm, exact noncol_in12' hba.symm }
lemma noncol_in13' {a b c : pts} (hac : a ≠ c) : b ∉ (a-ₗc) → noncol a b c :=
by { contrapose!, intro h, unfold noncol at h, rw not_not at h,
exact col_in13 h hac }
lemma noncol_in31' {a b c : pts} (hca : c ≠ a) : b ∉ (c-ₗa) → noncol a b c :=
by { rw line_symm, exact noncol_in13' hca.symm }
lemma noncol_in23' {a b c : pts} (hbc : b ≠ c) : a ∉ (b-ₗc) → noncol a b c :=
by { contrapose!, intro h, unfold noncol at h, rw not_not at h,
exact col_in23 h hbc }
lemma noncol_in32' {a b c : pts} (hcb : c ≠ b) : a ∉ (c-ₗb) → noncol a b c :=
by { rw line_symm, exact noncol_in23' hcb.symm } |
5d74424cd083fa240dcd256d2e145e399f9aa13b | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/standard/data/string.lean | 298477716620fd6d872c28a4bf03126e0f4df77d | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 797 | lean | ------------------------------------------------------------------------------------------------------ Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura
----------------------------------------------------------------------------------------------------
import data.bool
using bool
namespace string
inductive char : Type :=
| ascii : bool → bool → bool → bool → bool → bool → bool → bool → char
inductive string : Type :=
| empty : string
| str : char → string → string
theorem inhabited_char [instance] : inhabited char :=
inhabited_intro (ascii ff ff ff ff ff ff ff ff)
theorem inhabited_string [instance] : inhabited string :=
inhabited_intro empty
end
|
6b66b2ecb30df43f4969e5dcfb8e0975a650ef82 | 6fbf10071e62af7238f2de8f9aa83d55d8763907 | /hw/hw3b.lean | e0dbe204ebf6120505d7ea2dcfbec60a055d1f15 | [] | no_license | HasanMukati/uva-cs-dm-s19 | ee5aad4568a3ca330c2738ed579c30e1308b03b0 | 3e7177682acdb56a2d16914e0344c10335583dcf | refs/heads/master | 1,596,946,213,130 | 1,568,221,949,000 | 1,568,221,949,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,316 | lean | /-
CS 2102 Spring 2019 Homework #3b
The first part of your homework this week is to make
a new copy of the *blank* homework #2 assignment in
your "work" directory, now called "hw3a.lean", then
complete the questions that you did *not* complete
last week. To rename the file after copying it, click
on the file name, hit enter, then enter a new name for
the file.
This file contains the second half of the homework for
this week, which everyone in CS2102 is to complete.
The purpose of this part of the homework assignment
for this week is to help you learn how to write
propositions of various kinds in formal predicate
logic.
-/
/-
To this end, you are to translate the informally
stated propositions we give you into formal and
mechanically checked propositions using Lean.
To prepare to do this work, we strong recommend
that you reread the very recently updated version
of Chapter 2.5 in the notes, on Propositions.
So here we go.
-/
/-
#1. 10 points
To start, write the Lean code using the axiom keyword
needed to introduce the assumptions that "ItsRaining"
and "TheStreetsAreWet" are propositions. Write your
answer just below this comment block and before the
next one. There are examples in the chapter that you
can adapt to answer this question.
-/
-- Your answer here
/-
#2. 90 points
Now, write formal (using Lean) versions of each of
the following informally stated propositions. Do this
by writing your expressions in place of the underscore
characters in the following incomplete definitions.
-/
/- If it's raining, then the streets are wet. -/
def p1 : Prop := _
/- It's raining and the streets are wet. -/
def p2 : Prop := _
/- It's not raining. -/
def p3 : Prop := _
/- It's raining or the streets are wet. -/
def p4 : Prop := _
/- It's raining if and only if the streets are wet. -/
def p5 : Prop := _
/- It's raining or the streets are not wet. -/
def p6 : Prop := _
/-
If it's raining then (if the streets are wet then
it's raining).
-/
def p7 : Prop := _
/-
If (if it's raining then the streets are wet) then
it's raining.
-/
def p8 : Prop := _
/-
If the streets are wet and it's raining then
the streets are wet.
-/
def p9 : Prop := _
/-
The streets are wet and the streets are not wet
implies a contradiction (false).
-/
def p10 : Prop := _
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.