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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a2ec872d054dfd99c5b235d69d6713512c864d91 | 54c9ed381c63410c9b6af3b0a1722c41152f037f | /Binport/ProcessActionItem.lean | 21334e44aa183c0cca3a4b006b696eb173c89f28 | [
"Apache-2.0"
] | permissive | dselsam/binport | 0233f1aa961a77c4fc96f0dccc780d958c5efc6c | aef374df0e169e2c3f1dc911de240c076315805c | refs/heads/master | 1,687,453,448,108 | 1,627,483,296,000 | 1,627,483,296,000 | 333,825,622 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,978 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Gabriel Ebner
-/
import Binport.Util
import Binport.Basic
import Binport.ActionItem
import Binport.Rules
import Binport.Translate
import Binport.OldRecursor
import Lean
namespace Binport
open Lean Lean.Meta Lean.Elab Lean.Elab.Command
def shouldGenCodeFor (d : Declaration) : Bool :=
-- TODO: sadly, noncomputable comes after the definition
-- (so if this isn't good enough, we will need to refactor)
match d with
| Declaration.defnDecl _ => true
| _ => false
def addDeclLoud (n : Name) (d : Declaration) : PortM Unit := do
let path := (← read).path
printlnf! "[addDecl] START {path.mrpath.path} {n}"
addDecl d
printlnf! "[addDecl] END {path.mrpath.path} {n}"
if shouldGenCodeFor d then
match (← getEnv).compileDecl {} d with
| Except.ok env => println! "[compile] {n} SUCCESS!"
setEnv env
| Except.error err => let msg ← err.toMessageData (← getOptions)
let msg ← msg.toString
println! "[compile] {n} {msg}"
def setAttr (attr : Attribute) (declName : Name) : PortM Unit := do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl => liftMetaM $ attrImpl.add declName attr.stx attr.kind
def processMixfix (kind : MixfixKind) (n : Name) (prec : Nat) (tok : String) : PortM Unit := do
-- For now, we avoid the `=` `=` clash by making all Mathlib notations
-- lower priority than the Lean4 ones.
let prio : Nat := (← liftMacroM <| evalOptPrio none).pred
let stxPrec : Syntax := Syntax.mkNumLit (toString prec)
let stxName : Option Syntax := none
let stxPrio : Option Syntax := quote prio
let stxOp : Syntax := Syntax.mkStrLit tok
let stxFun : Syntax := Syntax.ident SourceInfo.none n.toString.toSubstring n []
let stx ←
match kind with
| MixfixKind.infixl =>
`(infixl:$stxPrec $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.infixr =>
`(infixr:$stxPrec $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.prefix =>
`(prefix:$stxPrec $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.postfix =>
`(postfix:$stxPrec $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
| MixfixKind.singleton =>
let correctPrec : Option Syntax := Syntax.mkNumLit (toString Parser.maxPrec)
`(notation $[: $correctPrec]? $[(name := $stxName)]? $[(priority := $stxPrio)]? $stxOp => $stxFun)
let nextIdx : Nat ← (← get).nNotations
modify λ s => { s with nNotations := nextIdx + 1 }
let ns : Syntax := mkIdent $ s!"{"__".intercalate (← read).path.mrpath.path.components}_{nextIdx}"
let stx ← `(namespace $ns:ident $stx end $ns:ident)
elabCommand stx
def maybeRegisterEquation (n : Name) : PortM Unit := do
-- example: list.nth.equations._eqn_1
-- def insertWith (m : HashMap α β) (merge : β → β → β) (a : α) (b : β) : HashMap α β :=
let n₁ : Name := n.getPrefix
if n₁.isStr && n₁.getString! == "equations" then
modify λ s => { s with name2equations := s.name2equations.insertWith (· ++ ·) n₁.getPrefix [n] }
def tryAddSimpLemma (n : Name) (prio : Nat) : PortM Unit :=
try
liftMetaM $ addSimpLemma n False AttributeKind.global prio
println! "[simp] {n} {prio}"
catch ex => warn ex
def isBadSUnfold (n : Name) : PortM Bool := do
if !n.isStr then return false
if n.getString! != "_sunfold" then return false
match (← getEnv).find? (n.getPrefix ++ `_main) with
| some cinfo =>
match cinfo.value? with
-- bad means the original function isn't actually recursive
| some v => Option.isNone $ v.find? fun e => e.isConst && e.constName!.isStr && e.constName!.getString! == "brec_on"
| _ => throwError "should have value"
| _ => return false /- this can happen when e.g. `nat.add._main -> Nat.add` (which may be needed due to eqn lemmas) -/
def processActionItem (actionItem : ActionItem) : PortM Unit := do
modify λ s => { s with decl := actionItem.toDecl }
let s ← get
let env ← getEnv
let f : Name → PortM Name :=
fun n => do translateName s (← getEnv) n
match actionItem with
| ActionItem.export d => do
println! "[export] {d.currNs} {d.ns} {d.nsAs} {d.hadExplicit}, renames={d.renames}, excepts={d.exceptNames}"
-- we use the variable names of elabExport
if not d.exceptNames.isEmpty then
warnStr s!"export of {d.ns} with exceptions is ignored"
else if d.nsAs != Name.anonymous then
warnStr s!"export of {d.ns} with 'nsAs' is ignored"
else if ¬ d.hadExplicit then
warnStr s!"export of {d.ns} with no explicits is ignored"
else
let mut env ← getEnv
for (n1, n2) in d.renames do
println! "[alias] {← f n1} short for {← f n2}"
env := addAlias env (← f n1) (← f n2)
setEnv env
| ActionItem.mixfix kind n prec tok =>
println! "[mixfix] {kind} {tok} {prec} {n}"
processMixfix kind (← f n) prec tok
| ActionItem.simp n prio => do
tryAddSimpLemma (← f n) prio
for eqn in (← get).name2equations.findD n [] do
tryAddSimpLemma (← f eqn) prio
| ActionItem.reducibility n kind => do
-- (note: this will fail if it declares reducible in a new module)
println! "reducibility {n} {repr kind}"
try setAttr { name := reducibilityToName kind } (← f n)
catch ex => warn ex
| ActionItem.projection proj => do
println! "[projection] {reprStr proj}"
setEnv $ addProjectionFnInfo (← getEnv) (← f proj.projName) (← f proj.ctorName) proj.nParams proj.index proj.fromClass
| ActionItem.class n => do
let env ← getEnv
if s.ignored.contains n then return ()
-- for meta classes, Lean4 won't know about the decl
match addClass env (← f n) with
| Except.error msg => warnStr msg
| Except.ok env => setEnv env
| ActionItem.instance nc ni prio => do
-- for meta instances, Lean4 won't know about the decl
-- note: we use `prio.pred` so that the Lean4 builtin instances get priority
-- this is currently needed because Decidable instances aren't getting compiled!
match (← get).noInsts.find? ni with
| some _ => println! "[skipInstance] {ni}"
| none => try liftMetaM $ addInstance (← f ni) AttributeKind.global prio
setAttr { name := `inferTCGoalsRL } (← f ni)
catch ex => warn ex
| ActionItem.private _ _ => pure ()
| ActionItem.protected n =>
-- TODO: have the semantics changed here?
-- When we mark `nat.has_one` as `Protected`, the kernel
-- fails to find it when typechecking definitions (but not theorems)
-- setEnv $ addProtected (← getEnv) (f n)
pure ()
| ActionItem.decl d => do
match d with
| Declaration.axiomDecl ax => do
let name ← f ax.name
let type ← translate ax.type
if s.ignored.contains ax.name then return ()
maybeRegisterEquation ax.name
addDeclLoud ax.name $ Declaration.axiomDecl {
ax with
name := name,
type := type
}
| Declaration.thmDecl thm => do
let name ← f thm.name
let type ← translate thm.type
if s.ignored.contains thm.name then return ()
maybeRegisterEquation thm.name
if s.sorries.contains thm.name ∨ (¬ (← read).proofs ∧ ¬ s.neverSorries.contains thm.name) then
printlnf! "sorry skipping: {thm.name}"
addDeclLoud thm.name $ Declaration.axiomDecl {
thm with
name := name,
type := type,
isUnsafe := false -- TODO: what to put here?
}
else
let value ← translate thm.value
addDeclLoud thm.name $ Declaration.thmDecl {
thm with
name := name,
type := type,
value := value
}
| Declaration.defnDecl defn => do
let name ← f defn.name
let type ← translate defn.type
if s.ignored.contains defn.name then return ()
if ← isBadSUnfold name then return ()
let mut value ← translate defn.value
addDeclLoud defn.name $ Declaration.defnDecl {
defn with
name := name,
type := type,
value := value,
hints := defn.hints
}
| Declaration.inductDecl lps nps [ind] iu => do
let name ← f ind.name
let type ← translate ind.type (reduce := false)
if not (s.ignored.contains ind.name) then
-- TODO: why do I need this nested do? Because of the scope?
let ctors ← ind.ctors.mapM fun (ctor : Constructor) => do
let cname ← f ctor.name
let ctype ← translate ctor.type (reduce := false)
pure { ctor with name := cname, type := ctype }
addDeclLoud ind.name $ Declaration.inductDecl lps nps
[{ ind with name := name, type := type, ctors := ctors }] iu
try
-- these may fail for the invalid inductive types currently being accepted
-- by the temporary patch https://github.com/dselsam/lean4/commit/1bef1cb3498cf81f93095bda16ed8bc65af42535
mkRecOn name
mkCasesOn name
mkNoConfusion name
mkBelow name -- already there
mkIBelow name
mkBRecOn name
mkBInductionOn name
catch _ => pure ()
let oldRecName := mkOldRecName (← f ind.name)
let oldRec ← liftMetaM $ mkOldRecursor (← f ind.name) oldRecName
match oldRec with
| some oldRec => do
addDeclLoud oldRecName oldRec
setAttr { name := `reducible } oldRecName
| none => pure ()
| _ => throwError (toString d.names)
end Binport
|
4fe767a07fe45b74af58575d9c7a31927f5bde7d | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/1675.lean | 6b07612312ad19ad1a9cb51358f41d38a051a097 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 1,233 | lean | def foo (a b : nat) : Prop :=
a = 0 ∧ b = 0
attribute [simp] foo
example (p : nat → Prop) (a b : nat) : foo a b → p (a + b) → p 0 :=
begin
intros h₁ h₂,
simp * at *,
end
example (a b : nat) (p : nat → Prop) (h₁ : a = b + 0) (h₂ : b = 0) (h₃ : p a) : p 0 ∧ a = 0 :=
by simp * at *
constant q : Prop
axiom q_lemma : q
open tactic
example (a b : nat) (p : nat → Prop) (h₁ : a = b + 0) (h₂ : b = 0) (h₃ : p a) : p 0 ∧ a = 0 ∧ q :=
begin
simp * at *,
guard_target q,
do {e₁ ← get_local `h₁ >>= infer_type, e₂ ← to_expr ```(a = 0), guard (e₁ = e₂)},
do {e₁ ← get_local `h₃ >>= infer_type, e₂ ← to_expr ```(p 0), guard (e₁ = e₂)},
apply q_lemma
end
example (p : nat → Prop) (a b : nat) : a = 0 ∧ b = 0 → p (a + b) → p 0 :=
begin
intros h₁ h₂,
simp [h₁] at *,
assumption
end
example (p : Prop) : p :=
begin
fail_if_success {simp * at *}, -- should fail if nothing was simplified
simp * at * {fail_if_unchanged := ff}, -- should work
admit
end
example (p : Prop) : let h : 0 = 0 := rfl in p :=
begin
intro h,
simp * at *,
do {e₁ ← get_local `h >>= infer_type, e₂ ← to_expr ```(true), guard (e₁ = e₂)},
admit
end
|
7179d038062a02c83bb94e6540579248788773cd | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /tests/lean/run/class7.lean | 7453b1dd91be88fef925a645df9dabecb509c753 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 467 | lean | import logic
open tactic
inductive inh [class] (A : Type) : Type :=
intro : A -> inh A
theorem inh_bool [instance] : inh Prop
:= inh.intro true
set_option class.trace_instances true
theorem inh_fun [instance] {A B : Type} [H : inh B] : inh (A → B)
:= inh.rec (λ b, inh.intro (λ a : A, b)) H
theorem tst {A B : Type} (H : inh B) : inh (A → B → B)
theorem T1 {A : Type} (a : A) : inh A :=
by repeat (apply @inh.intro | eassumption)
theorem T2 : inh Prop
|
588977c8e566c16be0973595c74dd3f1d6ea0316 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/localization/integral.lean | d225831a96e863d6db012500adfd88296d3ac7b9 | [
"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 | 19,520 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
-/
import algebra.ring.equiv
import group_theory.monoid_localization
import ring_theory.algebraic
import ring_theory.ideal.local_ring
import ring_theory.ideal.quotient
import ring_theory.integral_closure
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
import ring_theory.non_zero_divisors
import group_theory.submonoid.inverses
import tactic.ring_exp
/-!
# Integral and algebraic elements of a fraction field
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
open_locale big_operators polynomial
namespace is_localization
section integer_normalization
open polynomial
variables (M) {S} [is_localization M S]
open_locale classical
/-- `coeff_integer_normalization p` gives the coefficients of the polynomial
`integer_normalization p` -/
noncomputable def coeff_integer_normalization (p : S[X]) (i : ℕ) : R :=
if hi : i ∈ p.support
then classical.some (classical.some_spec
(exist_integer_multiples_of_finset M (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩))
else 0
lemma coeff_integer_normalization_of_not_mem_support (p : S[X]) (i : ℕ)
(h : coeff p i = 0) : coeff_integer_normalization M p i = 0 :=
by simp only [coeff_integer_normalization, h, mem_support_iff, eq_self_iff_true, not_true,
ne.def, dif_neg, not_false_iff]
lemma coeff_integer_normalization_mem_support (p : S[X]) (i : ℕ)
(h : coeff_integer_normalization M p i ≠ 0) : i ∈ p.support :=
begin
contrapose h,
rw [ne.def, not_not, coeff_integer_normalization, dif_neg h]
end
/-- `integer_normalization g` normalizes `g` to have integer coefficients
by clearing the denominators -/
noncomputable def integer_normalization (p : S[X]) :
R[X] :=
∑ i in p.support, monomial i (coeff_integer_normalization M p i)
@[simp]
lemma integer_normalization_coeff (p : S[X]) (i : ℕ) :
(integer_normalization M p).coeff i = coeff_integer_normalization M p i :=
by simp [integer_normalization, coeff_monomial, coeff_integer_normalization_of_not_mem_support]
{contextual := tt}
lemma integer_normalization_spec (p : S[X]) :
∃ (b : M), ∀ i,
algebra_map R S ((integer_normalization M p).coeff i) = (b : R) • p.coeff i :=
begin
use classical.some (exist_integer_multiples_of_finset M (p.support.image p.coeff)),
intro i,
rw [integer_normalization_coeff, coeff_integer_normalization],
split_ifs with hi,
{ exact classical.some_spec (classical.some_spec
(exist_integer_multiples_of_finset M (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩)) },
{ convert (smul_zero _).symm,
{ apply ring_hom.map_zero },
{ exact not_mem_support_iff.mp hi } }
end
lemma integer_normalization_map_to_map (p : S[X]) :
∃ (b : M), (integer_normalization M p).map (algebra_map R S) = (b : R) • p :=
let ⟨b, hb⟩ := integer_normalization_spec M p in
⟨b, polynomial.ext (λ i, by { rw [coeff_map, coeff_smul], exact hb i })⟩
variables {R' : Type*} [comm_ring R']
lemma integer_normalization_eval₂_eq_zero (g : S →+* R') (p : S[X])
{x : R'} (hx : eval₂ g x p = 0) :
eval₂ (g.comp (algebra_map R S)) x (integer_normalization M p) = 0 :=
let ⟨b, hb⟩ := integer_normalization_map_to_map M p in
trans (eval₂_map (algebra_map R S) g x).symm
(by rw [hb, ← is_scalar_tower.algebra_map_smul S (b : R) p, eval₂_smul, hx, mul_zero])
lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra S R'] [is_scalar_tower R S R']
(p : S[X]) {x : R'} (hx : aeval x p = 0) :
aeval x (integer_normalization M p) = 0 :=
by rw [aeval_def, is_scalar_tower.algebra_map_eq R S R',
integer_normalization_eval₂_eq_zero _ _ _ hx]
end integer_normalization
end is_localization
namespace is_fraction_ring
open is_localization
variables {A K C : Type*} [comm_ring A] [is_domain A] [field K] [algebra A K] [is_fraction_ring A K]
variables [comm_ring C]
lemma integer_normalization_eq_zero_iff {p : K[X]} :
integer_normalization (non_zero_divisors A) p = 0 ↔ p = 0 :=
begin
refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm),
obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec _ p,
split; intros h i,
{ apply to_map_eq_zero_iff.mp,
rw [hb i, h i],
apply smul_zero,
assumption },
{ have hi := h i,
rw [polynomial.coeff_zero, ← @to_map_eq_zero_iff A _ K, hb i, algebra.smul_def] at hi,
apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi),
intro h,
apply mem_non_zero_divisors_iff_ne_zero.mp nonzero,
exact to_map_eq_zero_iff.mp h }
end
variables (A K C)
/-- An element of a ring is algebraic over the ring `A` iff it is algebraic
over the field of fractions of `A`.
-/
lemma is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] {x : C} :
is_algebraic A x ↔ is_algebraic K x :=
begin
split; rintros ⟨p, hp, px⟩,
{ refine ⟨p.map (algebra_map A K), λ h, hp (polynomial.ext (λ i, _)), _⟩,
{ have : algebra_map A K (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]),
exact to_map_eq_zero_iff.mp this },
{ rwa is_scalar_tower.aeval_apply _ K at px } },
{ exact ⟨integer_normalization _ p,
mt integer_normalization_eq_zero_iff.mp hp,
integer_normalization_aeval_eq_zero _ p px⟩ },
end
variables {A K C}
/-- A ring is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`.
-/
lemma comap_is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] :
algebra.is_algebraic A C ↔ algebra.is_algebraic K C :=
⟨λ h x, (is_algebraic_iff A K C).mp (h x), λ h x, (is_algebraic_iff A K C).mpr (h x)⟩
end is_fraction_ring
open is_localization
section is_integral
variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ]
variables [algebra R Rₘ] [is_localization M Rₘ]
variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ]
variables {S M}
open polynomial
lemma ring_hom.is_integral_elem_localization_at_leading_coeff
{R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S)
(x : S) (p : R[X]) (hf : p.eval₂ f x = 0) (M : submonoid R)
(hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ]
[algebra R Rₘ] [is_localization M Rₘ]
[algebra S Sₘ] [is_localization (M.map f : submonoid S) Sₘ] :
(map Sₘ f M.le_comap_map : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) :=
begin
by_cases triv : (1 : Rₘ) = 0,
{ exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ },
haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv,
obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp
(map_units Rₘ ⟨p.leading_coeff, hM⟩),
refine ⟨(p.map (algebra_map R Rₘ)) * C b, ⟨_, _⟩⟩,
{ refine monic_mul_C_of_leading_coeff_mul_eq_one _,
rwa leading_coeff_map_of_leading_coeff_ne_zero (algebra_map R Rₘ),
refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) },
{ refine eval₂_mul_eq_zero_of_left _ _ _ _,
erw [eval₂_map, is_localization.map_comp, ← hom_eval₂ _ f (algebra_map S Sₘ) x],
exact trans (congr_arg (algebra_map S Sₘ) hf) (ring_hom.map_zero _) }
end
/-- Given a particular witness to an element being algebraic over an algebra `R → S`,
We can localize to a submonoid containing the leading coefficient to make it integral.
Explicitly, the map between the localizations will be an integral ring morphism -/
theorem is_integral_localization_at_leading_coeff {x : S} (p : R[X])
(hp : aeval x p = 0) (hM : p.leading_coeff ∈ M) :
(map Sₘ (algebra_map R S)
(show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map)
: Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) :=
(algebra_map R S).is_integral_elem_localization_at_leading_coeff x p hp M hM
/-- If `R → S` is an integral extension, `M` is a submonoid of `R`,
`Rₘ` is the localization of `R` at `M`,
and `Sₘ` is the localization of `S` at the image of `M` under the extension map,
then the induced map `Rₘ → Sₘ` is also an integral extension -/
theorem is_integral_localization (H : algebra.is_integral R S) :
(map Sₘ (algebra_map R S)
(show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map)
: Rₘ →+* _).is_integral :=
begin
intro x,
obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := surj (algebra.algebra_map_submonoid S M) x,
obtain ⟨v, hv⟩ := hu,
obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (map_units Rₘ ⟨v, hv.1⟩),
refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _
(localization_algebra M S) x (algebra_map S Sₘ u) v' _ _,
{ replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) hv',
rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ (algebra_map R Rₘ)] at hv',
erw is_localization.map_comp at hv',
exact hv.2 ▸ hv' },
{ obtain ⟨p, hp⟩ := H s,
exact hx.symm ▸ is_integral_localization_at_leading_coeff p hp.2 (hp.1.symm ▸ M.one_mem) }
end
lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S]
{f : R →+* S} (hf : f.is_integral) (M : submonoid R) :
(map (localization (M.map (f : R →* S))) f
(M.le_comap_map : _ ≤ submonoid.comap (f : R →* S) _) : localization M →+* _).is_integral :=
@is_integral_localization R _ M S _ f.to_algebra _ _ _ _ _ _ _ _ hf
variable (M)
lemma is_localization.scale_roots_common_denom_mem_lifts (p : Rₘ[X])
(hp : p.leading_coeff ∈ (algebra_map R Rₘ).range) :
p.scale_roots (algebra_map R Rₘ $ is_localization.common_denom M p.support p.coeff) ∈
polynomial.lifts (algebra_map R Rₘ) :=
begin
rw polynomial.lifts_iff_coeff_lifts,
intro n,
rw [polynomial.coeff_scale_roots],
by_cases h₁ : n ∈ p.support,
by_cases h₂ : n = p.nat_degree,
{ rwa [h₂, polynomial.coeff_nat_degree, tsub_self, pow_zero, _root_.mul_one] },
{ have : n + 1 ≤ p.nat_degree := lt_of_le_of_ne (polynomial.le_nat_degree_of_mem_supp _ h₁) h₂,
rw [← tsub_add_cancel_of_le (le_tsub_of_add_le_left this), pow_add, pow_one, mul_comm,
_root_.mul_assoc, ← map_pow],
change _ ∈ (algebra_map R Rₘ).range,
apply mul_mem,
{ exact ring_hom.mem_range_self _ _ },
{ rw ← algebra.smul_def,
exact ⟨_, is_localization.map_integer_multiple M p.support p.coeff ⟨n, h₁⟩⟩ } },
{ rw polynomial.not_mem_support_iff at h₁,
rw [h₁, zero_mul],
exact zero_mem (algebra_map R Rₘ).range }
end
lemma is_integral.exists_multiple_integral_of_is_localization
[algebra Rₘ S] [is_scalar_tower R Rₘ S] (x : S) (hx : is_integral Rₘ x) :
∃ m : M, is_integral R (m • x) :=
begin
cases subsingleton_or_nontrivial Rₘ with _ nontriv; resetI,
{ haveI := (algebra_map Rₘ S).codomain_trivial,
exact ⟨1, polynomial.X, polynomial.monic_X, subsingleton.elim _ _⟩ },
obtain ⟨p, hp₁, hp₂⟩ := hx,
obtain ⟨p', hp'₁, -, hp'₂⟩ := lifts_and_nat_degree_eq_and_monic
(is_localization.scale_roots_common_denom_mem_lifts M p _) _,
{ refine ⟨is_localization.common_denom M p.support p.coeff, p', hp'₂, _⟩,
rw [is_scalar_tower.algebra_map_eq R Rₘ S, ← polynomial.eval₂_map, hp'₁,
submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R Rₘ S],
exact polynomial.scale_roots_eval₂_eq_zero _ hp₂ },
{ rw hp₁.leading_coeff, exact one_mem _ },
{ rwa polynomial.monic_scale_roots_iff },
end
end is_integral
variables {A K : Type*} [comm_ring A] [is_domain A]
namespace is_integral_closure
variables (A) {L : Type*} [field K] [field L] [algebra A K] [algebra A L] [is_fraction_ring A K]
variables (C : Type*) [comm_ring C] [is_domain C] [algebra C L] [is_integral_closure C A L]
variables [algebra A C] [is_scalar_tower A C L]
open algebra
/-- If the field `L` is an algebraic extension of the integral domain `A`,
the integral closure `C` of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_algebraic (alg : is_algebraic A L)
(inj : ∀ x, algebra_map A L x = 0 → x = 0) :
is_fraction_ring C L :=
{ map_units := λ ⟨y, hy⟩,
is_unit.mk0 _ (show algebra_map C L y ≠ 0, from λ h, mem_non_zero_divisors_iff_ne_zero.mp hy
((injective_iff_map_eq_zero (algebra_map C L)).mp (algebra_map_injective C A L) _ h)),
surj := λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in
⟨⟨mk' C (x : L) x.2, algebra_map _ _ y,
mem_non_zero_divisors_iff_ne_zero.mpr (λ h, hy (inj _
(by rw [is_scalar_tower.algebra_map_apply A C L, h, ring_hom.map_zero])))⟩,
by rw [set_like.coe_mk, algebra_map_mk', ← is_scalar_tower.algebra_map_apply A C L, hxy]⟩,
eq_iff_exists := λ x y, ⟨λ h, ⟨1, by simpa using algebra_map_injective C A L h⟩, λ ⟨c, hc⟩,
congr_arg (algebra_map _ L) (mul_right_cancel₀ (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc)⟩ }
variables (K L)
/-- If the field `L` is a finite extension of the fraction field of the integral domain `A`,
the integral closure `C` of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_finite_extension [algebra K L] [is_scalar_tower A K L]
[finite_dimensional K L] : is_fraction_ring C L :=
is_fraction_ring_of_algebraic A C
(is_fraction_ring.comap_is_algebraic_iff.mpr (is_algebraic_of_finite K L))
(λ x hx, is_fraction_ring.to_map_eq_zero_iff.mp ((algebra_map K L).map_eq_zero.mp $
(is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx))
end is_integral_closure
namespace integral_closure
variables {L : Type*} [field K] [field L] [algebra A K] [is_fraction_ring A K]
open algebra
/-- If the field `L` is an algebraic extension of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_algebraic [algebra A L] (alg : is_algebraic A L)
(inj : ∀ x, algebra_map A L x = 0 → x = 0) :
is_fraction_ring (integral_closure A L) L :=
is_integral_closure.is_fraction_ring_of_algebraic A (integral_closure A L) alg inj
variables (K L)
/-- If the field `L` is a finite extension of the fraction field of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_finite_extension [algebra A L] [algebra K L]
[is_scalar_tower A K L] [finite_dimensional K L] :
is_fraction_ring (integral_closure A L) L :=
is_integral_closure.is_fraction_ring_of_finite_extension A K L (integral_closure A L)
end integral_closure
namespace is_fraction_ring
variables (R S K)
/-- `S` is algebraic over `R` iff a fraction ring of `S` is algebraic over `R` -/
lemma is_algebraic_iff' [field K] [is_domain R] [is_domain S] [algebra R K] [algebra S K]
[no_zero_smul_divisors R K] [is_fraction_ring S K] [is_scalar_tower R S K] :
algebra.is_algebraic R S ↔ algebra.is_algebraic R K :=
begin
simp only [algebra.is_algebraic],
split,
{ intros h x,
rw [is_fraction_ring.is_algebraic_iff R (fraction_ring R) K, is_algebraic_iff_is_integral],
obtain ⟨(a : S), b, ha, rfl⟩ := @div_surjective S _ _ _ _ _ _ x,
obtain ⟨f, hf₁, hf₂⟩ := h b,
rw [div_eq_mul_inv],
refine is_integral_mul _ _,
{ rw [← is_algebraic_iff_is_integral],
refine _root_.is_algebraic_of_larger_base_of_injective
(no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)) _,
exact is_algebraic_algebra_map_of_is_algebraic (h a) },
{ rw [← is_algebraic_iff_is_integral],
use (f.map (algebra_map R (fraction_ring R))).reverse,
split,
{ rwa [ne.def, polynomial.reverse_eq_zero, ← polynomial.degree_eq_bot,
polynomial.degree_map_eq_of_injective
(no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)),
polynomial.degree_eq_bot]},
{ haveI : invertible (algebra_map S K b),
from is_unit.invertible (is_unit_of_mem_non_zero_divisors
(mem_non_zero_divisors_iff_ne_zero.2
(λ h, non_zero_divisors.ne_zero ha
((injective_iff_map_eq_zero (algebra_map S K)).1
(no_zero_smul_divisors.algebra_map_injective _ _) b h)))),
rw [polynomial.aeval_def, ← inv_of_eq_inv, polynomial.eval₂_reverse_eq_zero_iff,
polynomial.eval₂_map, ← is_scalar_tower.algebra_map_eq, ← polynomial.aeval_def,
← is_scalar_tower.algebra_map_aeval, hf₂, ring_hom.map_zero] } } },
{ intros h x,
obtain ⟨f, hf₁, hf₂⟩ := h (algebra_map S K x),
use [f, hf₁],
rw [← is_scalar_tower.algebra_map_aeval] at hf₂,
exact (injective_iff_map_eq_zero (algebra_map S K)).1
(no_zero_smul_divisors.algebra_map_injective _ _) _ hf₂ }
end
open_locale non_zero_divisors
variables (R) {S K}
/-- If the `S`-multiples of `a` are contained in some `R`-span, then `Frac(S)`-multiples of `a`
are contained in the equivalent `Frac(R)`-span. -/
lemma ideal_span_singleton_map_subset {L : Type*}
[is_domain R] [is_domain S] [field K] [field L]
[algebra R K] [algebra R L] [algebra S L] [is_integral_closure S R L]
[is_fraction_ring S L] [algebra K L] [is_scalar_tower R S L] [is_scalar_tower R K L]
{a : S} {b : set S} (alg : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L))
(h : (ideal.span ({a} : set S) : set S) ⊆ submodule.span R b) :
(ideal.span ({algebra_map S L a} : set L) : set L) ⊆ submodule.span K (algebra_map S L '' b) :=
begin
intros x hx,
obtain ⟨x', rfl⟩ := ideal.mem_span_singleton.mp hx,
obtain ⟨y', z', rfl⟩ := is_localization.mk'_surjective (S⁰) x',
obtain ⟨y, z, hz0, yz_eq⟩ := is_integral_closure.exists_smul_eq_mul alg inj y'
(non_zero_divisors.coe_ne_zero z'),
have injRS : function.injective (algebra_map R S),
{ refine function.injective.of_comp
(show function.injective (algebra_map S L ∘ algebra_map R S), from _),
rwa [← ring_hom.coe_comp, ← is_scalar_tower.algebra_map_eq] },
have hz0' : algebra_map R S z ∈ S⁰ := map_mem_non_zero_divisors (algebra_map R S) injRS
(mem_non_zero_divisors_of_ne_zero hz0),
have mk_yz_eq : is_localization.mk' L y' z' = is_localization.mk' L y ⟨_, hz0'⟩,
{ rw [algebra.smul_def, mul_comm _ y, mul_comm _ y', ← set_like.coe_mk (algebra_map R S z) hz0']
at yz_eq,
exact is_localization.mk'_eq_of_eq yz_eq.symm },
suffices hy : algebra_map S L (a * y) ∈ submodule.span K (⇑(algebra_map S L) '' b),
{ rw [mk_yz_eq, is_fraction_ring.mk'_eq_div, set_like.coe_mk,
← is_scalar_tower.algebra_map_apply, is_scalar_tower.algebra_map_apply R K L,
div_eq_mul_inv, ← mul_assoc, mul_comm, ← map_inv₀, ← algebra.smul_def,
← _root_.map_mul],
exact (submodule.span K _).smul_mem _ hy },
refine submodule.span_subset_span R K _ _,
rw submodule.span_algebra_map_image_of_tower,
exact submodule.mem_map_of_mem (h (ideal.mem_span_singleton.mpr ⟨y, rfl⟩))
end
end is_fraction_ring
|
3a1343f38954b607d2b62e07afefe7f9b9f5e340 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/monoid_algebra.lean | 235da2d71fc571880504acf17da710b89964148b | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 27,886 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury G. Kudryashov, Scott Morrison
-/
import ring_theory.algebra
/-!
# Monoid algebras
When the domain of a `finsupp` has a multiplicative or additive structure, we can define
a convolution product. To mathematicians this structure is known as the "monoid algebra",
i.e. the finite formal linear combinations over a given semiring of elements of the monoid.
The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses.
In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G`
in the same way, and then define the convolution product on these.
When the domain is additive, this is used to define polynomials:
```
polynomial α := add_monoid_algebra ℕ α
mv_polynominal σ α := add_monoid_algebra (σ →₀ ℕ) α
```
When the domain is multiplicative, e.g. a group, this will be used to define the group ring.
## Implementation note
Unfortunately because additive and multiplicative structures both appear in both cases,
it doesn't appear to be possible to make much use of `to_additive`, and we just settle for
saying everything twice.
Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`,
but the definitional equality `multiplicative G = G` leaks through everywhere, and
seems impossible to use.
-/
noncomputable theory
open_locale classical big_operators
open finset finsupp
universes u₁ u₂ u₃
variables (k : Type u₁) (G : Type u₂)
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def monoid_algebra : Type (max u₁ u₂) := G →₀ k
end
namespace monoid_algebra
variables {k G}
local attribute [reducible] monoid_algebra
section
variables [semiring k] [monoid G]
/-- The product of `f g : monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x * y = a`. (Think of the group ring of a group.) -/
instance : has_mul (monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩
lemma mul_def {f g : monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) :=
rfl
lemma mul_apply (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) :
(f * g) x = ∑ p in s, (f p.1 * g p.2) :=
let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in
calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) :
mul_apply f g x
... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm
... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 :
(finset.sum_filter _ _).symm
... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 :
sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl)
... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _) $ λ p hps hp,
begin
simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢,
by_cases h1 : f p.1 = 0,
{ rw [h1, zero_mul] },
{ rw [hp hps h1, mul_zero] }
end
end
section
variables [semiring k] [monoid G]
lemma support_mul (a b : monoid_algebra k G) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `1` and zero elsewhere. -/
instance : has_one (monoid_algebra k G) :=
⟨single 1 1⟩
lemma one_def : (1 : monoid_algebra k G) = single 1 1 :=
rfl
-- TODO: the simplifier unfolds 0 in the instance proof!
protected lemma zero_mul (f : monoid_algebra k G) : 0 * f = 0 :=
by simp only [mul_def, sum_zero_index]
protected lemma mul_zero (f : monoid_algebra k G) : f * 0 = 0 :=
by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : monoid_algebra k G) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : monoid_algebra k G) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero,
single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
zero_mul := monoid_algebra.zero_mul,
mul_zero := monoid_algebra.mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
@[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
@[simp] lemma single_pow {a : G} {b : k} :
∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n)
| 0 := rfl
| (n+1) := by simp only [pow_succ, single_pow n, single_mul_single]
section
variables (k G)
/-- Embedding of a monoid into its monoid algebra. -/
def of : G →* monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
map_mul' := λ a b, by rw [single_mul_single, one_mul] }
end
@[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl
lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k}
{x y z : G} (H : ∀ a, a * x = z ↔ a = y) :
(f * single x r) z = f y * r :=
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) =
ite (a₁ * x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
-- different `decidable` instances make it not trivial
by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl }
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) :
(f * single 1 r) x = f x * r :=
f.mul_single_apply_aux $ λ a, by rw [mul_one]
lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G}
(H : ∀ a, x * a = y ↔ a = z) :
(single x r * f) y = r * f z :=
have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index this
... = f.sum (λ a b, ite (a = z) (r * b) 0) :
by { simp only [H], congr' with g s, split_ifs; refl }
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h]
lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) :
(single 1 r * f) x = r * f x :=
f.single_mul_apply_aux $ λ a, by rw [one_mul]
end
instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [mul_comm]
end,
.. monoid_algebra.semiring }
instance [ring k] : has_neg (monoid_algebra k G) :=
by apply_instance
instance [ring k] [monoid G] : ring (monoid_algebra k G) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. monoid_algebra.semiring }
instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) :=
{ mul_comm := mul_comm, .. monoid_algebra.ring}
instance [semiring k] : has_scalar k (monoid_algebra k G) :=
finsupp.has_scalar
instance [semiring k] : semimodule k (monoid_algebra k G) :=
finsupp.semimodule G k
lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) :
single 1 r * f = f * single 1 r :=
by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] }
/--
As a preliminary to defining the `k`-algebra structure on `monoid_algebra k G`,
we define the underlying ring homomorphism.
In fact, we do this in more generality, providing the ring homomorphism
`k →+* monoid_algebra A G` given any ring homomorphism `k →+* A`.
-/
def algebra_map' {A : Type*} [semiring k] [semiring A] (f : k →+* A) [monoid G] :
k →+* monoid_algebra A G :=
{ to_fun := λ x, single 1 (f x),
map_one' := by { simp, refl },
map_mul' := λ x y, by rw [single_mul_single, one_mul, f.map_mul],
map_zero' := by rw [f.map_zero, single_zero],
map_add' := λ x y, by rw [f.map_add, single_add], }
/--
The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`.
In particular this provides the instance `algebra k (monoid_algebra k G)`.
-/
instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
algebra k (monoid_algebra A G) :=
{ smul_def' := λ r a, by { ext x, dsimp [algebra_map'], rw single_one_mul_apply, rw algebra.smul_def'', },
commutes' := λ r f, show single 1 (algebra_map k A r) * f = f * single 1 (algebra_map k A r),
by { ext, rw [single_one_mul_apply, mul_single_one_apply, algebra.commutes], },
..algebra_map' (algebra_map k A) }
@[simp] lemma coe_algebra_map [comm_semiring k] [monoid G] :
(algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) = single 1 :=
rfl
lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) :
single a b = (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) b * of k G a :=
by simp
instance [group G] [semiring k] :
distrib_mul_action G (monoid_algebra k G) :=
finsupp.comap_distrib_mul_action_self
section lift
variables (k G) [comm_semiring k] [monoid G] (R : Type u₃) [semiring R] [algebra k R]
/-- Any monoid homomorphism `G →* R` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] R`. -/
def lift : (G →* R) ≃ (monoid_algebra k G →ₐ[k] R) :=
{ inv_fun := λ f, (f : monoid_algebra k G →* R).comp (of k G),
to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a),
map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul },
map_mul' :=
begin
intros f g,
rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a ha, _), simp only,
rw [finsupp.mul_sum, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a' ha', _), simp only,
rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc,
smul_smul, mul_comm],
apply zero_smul
end,
map_zero' := sum_zero_index,
map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul],
commutes' := λ r, by rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def,
mul_one]; apply zero_smul },
left_inv := λ f, begin ext x, simp [sum_single_index] end,
right_inv := λ F,
begin
ext f,
conv_rhs { rw ← f.sum_single },
simp [← F.map_smul, finsupp.sum, ← F.map_sum]
end }
variables {k G R}
lemma lift_apply (F : G →* R) (f : monoid_algebra k G) :
lift k G R F f = f.sum (λ a b, b • F a) := rfl
@[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] R) (x : G) :
(lift k G R).symm F x = F (single x 1) := rfl
lemma lift_of (F : G →* R) (x) :
lift k G R F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : G →* R) (a b) :
lift k G R F (single a b) = b • F a :=
by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of]
lemma lift_unique' (F : monoid_algebra k G →ₐ[k] R) :
F = lift k G R ((F : monoid_algebra k G →* R).comp (of k G)) :=
((lift k G R).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : monoid_algebra k G →ₐ[k] R) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
-- @[ext] -- FIXME I would really like to make this an `ext` lemma, but it seems to cause `ext` to loop.
lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] R⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
(lift k G R).symm.injective $ monoid_hom.ext h
end lift
section
variables (k)
/-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/
def group_smul.linear_map [group G] [comm_ring k]
(V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) :
(semimodule.restrict_scalars k (monoid_algebra k G) V) →ₗ[k]
(semimodule.restrict_scalars k (monoid_algebra k G) V) :=
{ to_fun := λ v, (single g (1 : k) • v : V),
map_add' := λ x y, smul_add (single g (1 : k)) x y,
map_smul' := λ c x,
by simp only [semimodule.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }.
@[simp]
lemma group_smul.linear_map_apply [group G] [comm_ring k]
(V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) (v : V) :
(group_smul.linear_map k V g) v = (single g (1 : k) • v : V) :=
rfl
section
variables {k}
variables [group G] [comm_ring k]
{V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_algebra k G) V}
{W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_algebra k G) W}
(f : (semimodule.restrict_scalars k (monoid_algebra k G) V) →ₗ[k]
(semimodule.restrict_scalars k (monoid_algebra k G) W))
(h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W))
include h
/-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/
def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W :=
{ to_fun := f,
map_add' := λ v v', by simp,
map_smul' := λ c v,
begin
apply finsupp.induction c,
{ simp, },
{ intros g r c' nm nz w,
rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj,
single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul],
erw [f.map_smul, h g v],
refl, }
end, }
@[simp]
lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v :=
rfl
end
end
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, prod_insert has, prod_insert has]
section -- We now prove some additional statements that hold for group algebras.
variables [semiring k] [group G]
@[simp]
lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y * x⁻¹) * r :=
f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm
@[simp]
lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) :
(single x r * f) y = r * f (x⁻¹ * y) :=
f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm
lemma mul_apply_left (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) :=
calc (f * g) x = sum f (λ a b, (single a b * g) x) :
by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single]
... = _ : by simp only [single_mul_apply, finsupp.sum]
-- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`.
lemma mul_apply_right (f g : monoid_algebra k G) (x : G) :
(f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) :=
calc (f * g) x = sum g (λ a b, (f * single a b) x) :
by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single]
... = _ : by simp only [mul_single_apply, finsupp.sum]
end
end monoid_algebra
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the additive monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def add_monoid_algebra := G →₀ k
end
namespace add_monoid_algebra
variables {k G}
local attribute [reducible] add_monoid_algebra
section
variables [semiring k] [add_monoid G]
/-- The product of `f g : add_monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the additive monoid of monomial exponents.) -/
instance : has_mul (add_monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def {f g : add_monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) :=
rfl
lemma mul_apply (f g : add_monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma support_mul (a b : add_monoid_algebra k G) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `0` and zero elsewhere. -/
instance : has_one (add_monoid_algebra k G) :=
⟨single 0 1⟩
lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 :=
rfl
-- TODO: the simplifier unfolds 0 in the instance proof!
protected lemma zero_mul (f : add_monoid_algebra k G) : 0 * f = 0 :=
by simp only [mul_def, sum_zero_index]
protected lemma mul_zero (f : add_monoid_algebra k G) : f * 0 = 0 :=
by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : add_monoid_algebra k G) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : add_monoid_algebra k G) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero,
single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
zero_mul := add_monoid_algebra.zero_mul,
mul_zero := add_monoid_algebra.mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
section
variables (k G)
/-- Embedding of a monoid into its monoid algebra. -/
def of : multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } }
end
@[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl
lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k)
(x y z : G) (H : ∀ a, a + x = z ↔ a = y) :
(f * single x r) z = f y * r :=
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ + a₂ = z) (b₁ * b₂) 0) =
ite (a₁ + x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
-- different `decidable` instances make it not trivial
by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl }
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) :
(f * single 0 r) x = f x * r :=
f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero]
lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G)
(H : ∀ a, x + a = y ↔ a = z) :
(single x r * f) y = r * f z :=
have f.sum (λ a b, ite (x + a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x + a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index this
... = f.sum (λ a b, ite (a = z) (r * b) 0) :
by { simp only [H], congr' with g s, split_ifs; refl }
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h]
lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) :
(single 0 r * f) x = r * f x :=
f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add]
end
instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. add_monoid_algebra.semiring }
instance [ring k] : has_neg (add_monoid_algebra k G) :=
by apply_instance
instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. add_monoid_algebra.semiring }
instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) :=
{ mul_comm := mul_comm, .. add_monoid_algebra.ring}
instance [semiring k] : has_scalar k (add_monoid_algebra k G) :=
finsupp.has_scalar
instance [semiring k] : semimodule k (add_monoid_algebra k G) :=
finsupp.semimodule G k
/--
As a preliminary to defining the `k`-algebra structure on `add_monoid_algebra k G`,
we define the underlying ring homomorphism.
In fact, we do this in more generality, providing the ring homomorphism
`k →+* add_monoid_algebra A G` given any ring homomorphism `k →+* A`.
-/
def algebra_map' {A : Type*} [semiring k] [semiring A] (f : k →+* A) [add_monoid G] :
k →+* add_monoid_algebra A G :=
{ to_fun := λ x, single 0 (f x),
map_one' := by { simp, refl },
map_mul' := λ x y, by rw [single_mul_single, zero_add, f.map_mul],
map_zero' := by rw [f.map_zero, single_zero],
map_add' := λ x y, by rw [f.map_add, single_add], }
/--
The instance `algebra k (add_monoid_algebra A G)` whenever we have `algebra k A`.
In particular this provides the instance `algebra k (add_monoid_algebra k G)`.
-/
instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [add_monoid G] :
algebra k (add_monoid_algebra A G) :=
{ smul_def' := λ r a, by { ext x, dsimp [algebra_map'], rw single_zero_mul_apply, rw algebra.smul_def'', },
commutes' := λ r f, show single 0 (algebra_map k A r) * f = f * single 0 (algebra_map k A r),
by { ext, rw [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], },
..algebra_map' (algebra_map k A) }
@[simp] lemma coe_algebra_map [comm_semiring k] [add_monoid G] :
(algebra_map k (add_monoid_algebra k G) : k → add_monoid_algebra k G) = single 0 :=
rfl
/-- Any monoid homomorphism `multiplicative G →* R` can be lifted to an algebra homomorphism
`add_monoid_algebra k G →ₐ[k] R`. -/
def lift [comm_semiring k] [add_monoid G] {R : Type u₃} [semiring R] [algebra k R] :
(multiplicative G →* R) ≃ (add_monoid_algebra k G →ₐ[k] R) :=
{ inv_fun := λ f, ((f : add_monoid_algebra k G →+* R) : add_monoid_algebra k G →* R).comp (of k G),
to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a),
map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul },
map_mul' :=
begin
intros f g,
rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a ha, _), simp only,
rw [finsupp.mul_sum, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a' ha', _), simp only,
rw [sum_single_index],
erw [F.map_mul],
rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm],
apply zero_smul
end,
map_zero' := sum_zero_index,
map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul],
commutes' := λ r,
begin
rw [coe_algebra_map, sum_single_index],
erw [F.map_one],
rw [algebra.smul_def, mul_one],
apply zero_smul
end, },
left_inv := λ f, begin ext x, simp [sum_single_index] end,
right_inv := λ F,
begin
ext f,
conv_rhs { rw ← f.sum_single },
simp [← F.map_smul, finsupp.sum, ← F.map_sum]
end }
-- It is hard to state the equivalent of `distrib_mul_action G (monoid_algebra k G)`
-- because we've never discussed actions of additive groups.
lemma alg_hom_ext {R : Type u₃} [comm_semiring k] [add_monoid G]
[semiring R] [algebra k R] ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] R⦄
(h : ∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) : φ₁ = φ₂ :=
lift.symm.injective $ by {ext, apply h}
lemma alg_hom_ext_iff {R : Type u₃} [comm_semiring k] [add_monoid G]
[semiring R] [algebra k R] ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] R⦄ :
(∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ :=
⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [add_comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
end add_monoid_algebra
|
4f33ee51103c6e1344e3582fc3afee1459740587 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/dynamics/ergodic/measure_preserving.lean | 305c3f171284bad5b342c2824de80efd8297f327 | [
"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 | 6,381 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import measure_theory.measure.ae_measurable
/-!
# Measure preserving maps
We say that `f : α → β` is a measure preserving map w.r.t. measures `μ : measure α` and
`ν : measure β` if `f` is measurable and `map f μ = ν`. In this file we define the predicate
`measure_theory.measure_preserving` and prove its basic properties.
We use the term "measure preserving" because in many applications `α = β` and `μ = ν`.
## References
Partially based on
[this](https://www.isa-afp.org/browser_info/current/AFP/Ergodic_Theory/Measure_Preserving_Transformations.html)
Isabelle formalization.
## Tags
measure preserving map, measure
-/
variables {α β γ δ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ]
[measurable_space δ]
namespace measure_theory
open measure function set
variables {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ}
/-- `f` is a measure preserving map w.r.t. measures `μa` and `μb` if `f` is measurable
and `map f μa = μb`. -/
@[protect_proj]
structure measure_preserving (f : α → β) (μa : measure α . volume_tac)
(μb : measure β . volume_tac) : Prop :=
(measurable : measurable f)
(map_eq : map f μa = μb)
protected lemma _root_.measurable.measure_preserving {f : α → β}
(h : measurable f) (μa : measure α) :
measure_preserving f μa (map f μa) :=
⟨h, rfl⟩
namespace measure_preserving
protected lemma id (μ : measure α) : measure_preserving id μ μ :=
⟨measurable_id, map_id⟩
protected lemma ae_measurable {f : α → β} (hf : measure_preserving f μa μb) :
ae_measurable f μa :=
hf.1.ae_measurable
lemma symm (e : α ≃ᵐ β) {μa : measure α} {μb : measure β} (h : measure_preserving e μa μb) :
measure_preserving e.symm μb μa :=
⟨e.symm.measurable,
by rw [← h.map_eq, map_map e.symm.measurable e.measurable, e.symm_comp_self, map_id]⟩
lemma restrict_preimage {f : α → β} (hf : measure_preserving f μa μb) {s : set β}
(hs : measurable_set s) : measure_preserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) :=
⟨hf.measurable, by rw [← hf.map_eq, restrict_map hf.measurable hs]⟩
lemma restrict_preimage_emb {f : α → β} (hf : measure_preserving f μa μb)
(h₂ : measurable_embedding f) (s : set β) :
measure_preserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) :=
⟨hf.measurable, by rw [← hf.map_eq, h₂.restrict_map]⟩
lemma restrict_image_emb {f : α → β} (hf : measure_preserving f μa μb) (h₂ : measurable_embedding f)
(s : set α) : measure_preserving f (μa.restrict s) (μb.restrict (f '' s)) :=
by simpa only [preimage_image_eq _ h₂.injective] using hf.restrict_preimage_emb h₂ (f '' s)
lemma ae_measurable_comp_iff {f : α → β} (hf : measure_preserving f μa μb)
(h₂ : measurable_embedding f) {g : β → γ} :
ae_measurable (g ∘ f) μa ↔ ae_measurable g μb :=
by rw [← hf.map_eq, h₂.ae_measurable_map_iff]
protected lemma quasi_measure_preserving {f : α → β} (hf : measure_preserving f μa μb) :
quasi_measure_preserving f μa μb :=
⟨hf.1, hf.2.absolutely_continuous⟩
lemma comp {g : β → γ} {f : α → β} (hg : measure_preserving g μb μc)
(hf : measure_preserving f μa μb) :
measure_preserving (g ∘ f) μa μc :=
⟨hg.1.comp hf.1, by rw [← map_map hg.1 hf.1, hf.2, hg.2]⟩
protected lemma sigma_finite {f : α → β} (hf : measure_preserving f μa μb) [sigma_finite μb] :
sigma_finite μa :=
sigma_finite.of_map μa hf.ae_measurable (by rwa hf.map_eq)
lemma measure_preimage {f : α → β} (hf : measure_preserving f μa μb)
{s : set β} (hs : measurable_set s) :
μa (f ⁻¹' s) = μb s :=
by rw [← hf.map_eq, map_apply hf.1 hs]
lemma measure_preimage_emb {f : α → β} (hf : measure_preserving f μa μb)
(hfe : measurable_embedding f) (s : set β) :
μa (f ⁻¹' s) = μb s :=
by rw [← hf.map_eq, hfe.map_apply]
protected lemma iterate {f : α → α} (hf : measure_preserving f μa μa) :
∀ n, measure_preserving (f^[n]) μa μa
| 0 := measure_preserving.id μa
| (n + 1) := (iterate n).comp hf
variables {μ : measure α} {f : α → α} {s : set α}
/-- If `μ univ < n * μ s` and `f` is a map preserving measure `μ`,
then for some `x ∈ s` and `0 < m < n`, `f^[m] x ∈ s`. -/
lemma exists_mem_image_mem_of_volume_lt_mul_volume (hf : measure_preserving f μ μ)
(hs : measurable_set s) {n : ℕ} (hvol : μ (univ : set α) < n * μ s) :
∃ (x ∈ s) (m ∈ Ioo 0 n), f^[m] x ∈ s :=
begin
have A : ∀ m, measurable_set (f^[m] ⁻¹' s) := λ m, (hf.iterate m).measurable hs,
have B : ∀ m, μ (f^[m] ⁻¹' s) = μ s, from λ m, (hf.iterate m).measure_preimage hs,
have : μ (univ : set α) < (finset.range n).sum (λ m, μ (f^[m] ⁻¹' s)),
by simpa only [B, nsmul_eq_mul, finset.sum_const, finset.card_range],
rcases exists_nonempty_inter_of_measure_univ_lt_sum_measure μ (λ m hm, A m) this
with ⟨i, hi, j, hj, hij, x, hxi, hxj⟩,
-- without `tactic.skip` Lean closes the extra goal but it takes a long time; not sure why
wlog hlt : i < j := hij.lt_or_lt using [i j, j i] tactic.skip,
{ simp only [set.mem_preimage, finset.mem_range] at hi hj hxi hxj,
refine ⟨f^[i] x, hxi, j - i, ⟨tsub_pos_of_lt hlt, lt_of_le_of_lt (j.sub_le i) hj⟩, _⟩,
rwa [← iterate_add_apply, tsub_add_cancel_of_le hlt.le] },
{ exact λ hi hj hij hxi hxj, this hj hi hij.symm hxj hxi }
end
/-- A self-map preserving a finite measure is conservative: if `μ s ≠ 0`, then at least one point
`x ∈ s` comes back to `s` under iterations of `f`. Actually, a.e. point of `s` comes back to `s`
infinitely many times, see `measure_theory.measure_preserving.conservative` and theorems about
`measure_theory.conservative`. -/
lemma exists_mem_image_mem [is_finite_measure μ] (hf : measure_preserving f μ μ)
(hs : measurable_set s) (hs' : μ s ≠ 0) :
∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s :=
begin
rcases ennreal.exists_nat_mul_gt hs' (measure_ne_top μ (univ : set α)) with ⟨N, hN⟩,
rcases hf.exists_mem_image_mem_of_volume_lt_mul_volume hs hN with ⟨x, hx, m, hm, hmx⟩,
exact ⟨x, hx, m, hm.1.ne', hmx⟩
end
end measure_preserving
end measure_theory
|
3aa833b9a5128dd095df379a282f2727e422ade0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/string/basic.lean | 594a47f40015babff9f8f14fcc2d7b6b3acbb3db | [
"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,499 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.lex
import data.char
/-!
# Strings
Supplementary theorems about the `string` type.
-/
namespace string
/-- `<` on string iterators. This coincides with `<` on strings as lists. -/
def ltb : iterator → iterator → bool
| s₁ s₂ := begin
cases s₂.has_next, {exact ff},
cases h₁ : s₁.has_next, {exact tt},
exact if s₁.curr = s₂.curr then
have s₁.next.2.length < s₁.2.length, from
match s₁, h₁ with ⟨_, a::l⟩, h := nat.lt_succ_self _ end,
ltb s₁.next s₂.next
else s₁.curr < s₂.curr,
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ s, s.1.2.length)⟩]}
instance has_lt' : has_lt string :=
⟨λ s₁ s₂, ltb s₁.mk_iterator s₂.mk_iterator⟩
instance decidable_lt : @decidable_rel string (<) :=
by apply_instance -- short-circuit type class inference
@[simp] theorem lt_iff_to_list_lt :
∀ {s₁ s₂ : string}, s₁ < s₂ ↔ s₁.to_list < s₂.to_list
| ⟨i₁⟩ ⟨i₂⟩ :=
suffices ∀ {p₁ p₂ s₁ s₂}, ltb ⟨p₁, s₁⟩ ⟨p₂, s₂⟩ ↔ s₁ < s₂, from this,
begin
intros,
induction s₁ with a s₁ IH generalizing p₁ p₂ s₂;
cases s₂ with b s₂; rw ltb; simp [iterator.has_next],
{ refl, },
{ exact iff_of_true rfl list.lex.nil },
{ exact iff_of_false bool.ff_ne_tt (not_lt_of_lt list.lex.nil) },
{ dsimp [iterator.has_next,
iterator.curr, iterator.next],
split_ifs,
{ subst b, exact IH.trans list.lex.cons_iff.symm },
{ simp, refine ⟨list.lex.rel, λ e, _⟩,
cases e, {cases h rfl}, assumption } }
end
instance has_le : has_le string := ⟨λ s₁ s₂, ¬ s₂ < s₁⟩
instance decidable_le : @decidable_rel string (≤) :=
by apply_instance -- short-circuit type class inference
@[simp] theorem le_iff_to_list_le
{s₁ s₂ : string} : s₁ ≤ s₂ ↔ s₁.to_list ≤ s₂.to_list :=
(not_congr lt_iff_to_list_lt).trans not_lt
theorem to_list_inj : ∀ {s₁ s₂}, to_list s₁ = to_list s₂ ↔ s₁ = s₂
| ⟨s₁⟩ ⟨s₂⟩ := ⟨congr_arg _, congr_arg _⟩
lemma nil_as_string_eq_empty : [].as_string = "" := rfl
@[simp] lemma to_list_empty : "".to_list = [] := rfl
lemma as_string_inv_to_list (s : string) : s.to_list.as_string = s :=
by { cases s, refl }
@[simp] lemma to_list_singleton (c : char) : (string.singleton c).to_list = [c] := rfl
lemma to_list_nonempty : ∀ {s : string}, s ≠ string.empty →
s.to_list = s.head :: (s.popn 1).to_list
| ⟨s⟩ h := by cases s; [cases h rfl, refl]
@[simp] lemma head_empty : "".head = default := rfl
@[simp] lemma popn_empty {n : ℕ} : "".popn n = "" :=
begin
induction n with n hn,
{ refl },
{ rcases hs : "" with ⟨_ | ⟨hd, tl⟩⟩,
{ rw hs at hn,
conv_rhs { rw ←hn },
simp only [popn, mk_iterator, iterator.nextn, iterator.next] },
{ simpa only [←to_list_inj] using hs } }
end
instance : linear_order string :=
{ lt := (<), le := (≤),
decidable_lt := by apply_instance,
decidable_le := string.decidable_le,
decidable_eq := by apply_instance,
le_refl := λ a, le_iff_to_list_le.2 le_rfl,
le_trans := λ a b c, by { simp only [le_iff_to_list_le], exact λ h₁ h₂, h₁.trans h₂ },
le_total := λ a b, by { simp only [le_iff_to_list_le], exact le_total _ _ },
le_antisymm := λ a b, by { simp only [le_iff_to_list_le, ← to_list_inj], apply le_antisymm },
lt_iff_le_not_le := λ a b, by simp only [le_iff_to_list_le, lt_iff_to_list_lt, lt_iff_le_not_le] }
end string
open string
lemma list.to_list_inv_as_string (l : list char) : l.as_string.to_list = l :=
by { cases hl : l.as_string, exact string_imp.mk.inj hl.symm }
@[simp] lemma list.length_as_string (l : list char) : l.as_string.length = l.length := rfl
@[simp] lemma list.as_string_inj {l l' : list char} : l.as_string = l'.as_string ↔ l = l' :=
⟨λ h, by rw [←list.to_list_inv_as_string l, ←list.to_list_inv_as_string l', to_list_inj, h],
λ h, h ▸ rfl⟩
@[simp] lemma string.length_to_list (s : string) : s.to_list.length = s.length :=
by rw [←string.as_string_inv_to_list s, list.to_list_inv_as_string, list.length_as_string]
lemma list.as_string_eq {l : list char} {s : string} :
l.as_string = s ↔ l = s.to_list :=
by rw [←as_string_inv_to_list s, list.as_string_inj, as_string_inv_to_list s]
|
a48cff3b2036f269f657ea26fef9c00ae5ca9148 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/nat/parity.lean | 88b1ee8dcdd8e1a0aed67ef17a6ad93f32dbab1d | [
"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 | 11,191 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Benjamin Davidson
-/
import data.nat.modeq
import data.nat.factors
import algebra.parity
/-!
# Parity of natural numbers
This file contains theorems about the `even` and `odd` predicates on the natural numbers.
## Tags
even, odd
-/
namespace nat
variables {m n : ℕ}
@[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
@[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
theorem even_iff : even n ↔ n % 2 = 0 :=
⟨λ ⟨m, hm⟩, by simp [← two_mul, hm],
λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [← two_mul, h])⟩⟩
theorem odd_iff : odd n ↔ n % 2 = 1 :=
⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod],
λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩
lemma not_even_iff : ¬ even n ↔ n % 2 = 1 :=
by rw [even_iff, mod_two_ne_zero]
lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 :=
by rw [odd_iff, mod_two_ne_one]
lemma even_iff_not_odd : even n ↔ ¬ odd n :=
by rw [not_odd_iff, even_iff]
@[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n :=
by rw [not_even_iff, odd_iff]
lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} :=
by simp only [←set.compl_set_of, is_compl_compl, odd_iff_not_even]
lemma even_or_odd (n : ℕ) : even n ∨ odd n :=
or.imp_right odd_iff_not_even.2 $ em $ even n
lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 :=
by simpa only [← two_mul, exists_or_distrib, ← odd, ← even] using even_or_odd n
lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) :=
begin
cases even_or_odd n with h,
{ exact or.inl ⟨h, even_iff_not_odd.mp h⟩ },
{ exact or.inr ⟨h, odd_iff_not_even.mp h⟩ },
end
lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) :=
begin
rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩;
use k,
{ simpa only [← two_mul, xor, true_and, eq_self_iff_true, not_true, or_false, and_false]
using (succ_ne_self (2*k)).symm },
{ simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff,
one_ne_zero, and_self] },
end
@[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 :=
even_iff_two_dvd.symm.not.trans not_even_iff
instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_iff _ even_iff.symm
instance : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_iff _ odd_iff_not_even.symm
theorem mod_two_add_add_odd_mod_two (m : ℕ) {n : ℕ} (hn : odd n) : m % 2 + (m + n) % 2 = 1 :=
(even_or_odd m).elim (λ hm, by rw [even_iff.1 hm, odd_iff.1 (hm.add_odd hn)]) $
λ hm, by rw [odd_iff.1 hm, even_iff.1 (hm.add_odd hn)]
@[simp] theorem mod_two_add_succ_mod_two (m : ℕ) : m % 2 + (m + 1) % 2 = 1 :=
mod_two_add_add_odd_mod_two m odd_one
@[simp] theorem succ_mod_two_add_mod_two (m : ℕ) : (m + 1) % 2 + m % 2 = 1 :=
by rw [add_comm, mod_two_add_succ_mod_two]
mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`"
@[simp] theorem not_even_one : ¬ even 1 :=
by rw even_iff; norm_num
@[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) :=
by cases mod_two_eq_zero_or_one m with h₁ h₁;
cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂, nat.add_mod];
norm_num
theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) :=
by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not]
@[parity_simps] theorem even_add_one : even (n + 1) ↔ ¬ even n :=
by simp [even_add]
@[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) :=
by simp [bit1] with parity_simps
lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) :=
by simp [add_mod]
lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1)
| (n + 1) _ := two_not_dvd_two_mul_add_one n
@[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) :=
begin
conv { to_rhs, rw [←tsub_add_cancel_of_le h, even_add] },
by_cases h : even n; simp [h]
end
theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) :=
by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not]
theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) :=
(le_total n m).elim
(λ h, by simp only [even_sub' h, *])
(λ h, by simp only [tsub_eq_zero_iff_le.mpr h, even_zero])
@[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n :=
by cases mod_two_eq_zero_or_one m with h₁ h₁;
cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂, nat.mul_mod];
norm_num
theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n :=
by simp [not_or_distrib] with parity_simps
theorem odd.of_mul_left (h : odd (m * n)) : odd m :=
(odd_mul.mp h).1
theorem odd.of_mul_right (h : odd (m * n)) : odd n :=
(odd_mul.mp h).2
/-- If `m` and `n` are natural numbers, then the natural number `m^n` is even
if and only if `m` is even and `n` is positive. -/
@[parity_simps] theorem even_pow : even (m ^ n) ↔ even m ∧ n ≠ 0 :=
by { induction n with n ih; simp [*, pow_succ', even_mul], tauto }
theorem even_pow' (h : n ≠ 0) : even (m ^ n) ↔ even m :=
even_pow.trans $ and_iff_left h
theorem even_div : even (m / n) ↔ m % (2 * n) / n = 0 :=
by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm]
@[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) :=
by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even]
theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) :=
by rw [add_comm, odd_add]
lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n :=
λ hnot, by simpa [hnot] with parity_simps using h
@[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) :=
by rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even]
theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) :=
(odd_sub h).mpr $ iff_of_true hm hn
theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) :=
by rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even]
theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) :=
(odd_sub' h).mpr $ iff_of_true hn hm
lemma even_mul_succ_self (n : ℕ) : even (n * (n + 1)) :=
begin
rw even_mul,
convert n.even_or_odd,
simp with parity_simps
end
lemma even_mul_self_pred (n : ℕ) : even (n * (n - 1)) :=
begin
cases n,
{ exact even_zero },
{ rw mul_comm,
apply even_mul_succ_self }
end
lemma even_sub_one_of_prime_ne_two {p : ℕ} (hp : prime p) (hodd : p ≠ 2) : even (p - 1) :=
odd.sub_odd (odd_iff.2 $ hp.eq_two_or_odd.resolve_left hodd) (odd_iff.2 rfl)
lemma two_mul_div_two_of_even : even n → 2 * (n / 2) = n :=
λ h, nat.mul_div_cancel_left' (even_iff_two_dvd.mp h)
lemma div_two_mul_two_of_even : even n → n / 2 * 2 = n := --nat.div_mul_cancel
λ h, nat.div_mul_cancel (even_iff_two_dvd.mp h)
lemma two_mul_div_two_add_one_of_odd (h : odd n) : 2 * (n / 2) + 1 = n :=
by { rw mul_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h }
lemma div_two_mul_two_add_one_of_odd (h : odd n) : n / 2 * 2 + 1 = n :=
by { convert nat.div_add_mod' n 2, rw odd_iff.mp h }
lemma one_add_div_two_mul_two_of_odd (h : odd n) : 1 + n / 2 * 2 = n :=
by { rw add_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h }
lemma bit0_div_two : bit0 n / 2 = n :=
by rw [←nat.bit0_eq_bit0, bit0_eq_two_mul, two_mul_div_two_of_even (even_bit0 n)]
lemma bit1_div_two : bit1 n / 2 = n :=
by rw [←nat.bit1_eq_bit1, bit1, bit0_eq_two_mul, nat.two_mul_div_two_add_one_of_odd (odd_bit1 n)]
@[simp] lemma bit0_div_bit0 : bit0 n / bit0 m = n / m :=
by rw [bit0_eq_two_mul m, ←nat.div_div_eq_div_mul, bit0_div_two]
@[simp] lemma bit1_div_bit0 : bit1 n / bit0 m = n / m :=
by rw [bit0_eq_two_mul, ←nat.div_div_eq_div_mul, bit1_div_two]
@[simp] lemma bit0_mod_bit0 : bit0 n % bit0 m = bit0 (n % m) :=
by rw [bit0_eq_two_mul n, bit0_eq_two_mul m, bit0_eq_two_mul (n % m), nat.mul_mod_mul_left]
@[simp] lemma bit1_mod_bit0 : bit1 n % bit0 m = bit1 (n % m) :=
begin
have h₁ := congr_arg bit1 (nat.div_add_mod n m),
-- `∀ m n : ℕ, bit0 m * n = bit0 (m * n)` seems to be missing...
rw [bit1_add, bit0_eq_two_mul, ← mul_assoc, ← bit0_eq_two_mul] at h₁,
have h₂ := nat.div_add_mod (bit1 n) (bit0 m),
rw [bit1_div_bit0] at h₂,
exact add_left_cancel (h₂.trans h₁.symm),
end
-- Here are examples of how `parity_simps` can be used with `nat`.
example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) :=
by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps
example : ¬ even 25394535 :=
by simp
end nat
open nat
namespace function
namespace involutive
variables {α : Type*} {f : α → α} {n : ℕ}
theorem iterate_bit0 (hf : involutive f) (n : ℕ) : f^[bit0 n] = id :=
by rw [bit0, ← two_mul, iterate_mul, involutive_iff_iter_2_eq_id.1 hf, iterate_id]
theorem iterate_bit1 (hf : involutive f) (n : ℕ) : f^[bit1 n] = f :=
by rw [bit1, iterate_succ, hf.iterate_bit0, comp.left_id]
theorem iterate_even (hf : involutive f) (hn : even n) : f^[n] = id :=
let ⟨m, hm⟩ := hn in hm.symm ▸ hf.iterate_bit0 m
theorem iterate_odd (hf : involutive f) (hn : odd n) : f^[n] = f :=
let ⟨m, hm⟩ := odd_iff_exists_bit1.mp hn in hm.symm ▸ hf.iterate_bit1 m
theorem iterate_eq_self (hf : involutive f) (hne : f ≠ id) : f^[n] = f ↔ odd n :=
⟨λ H, odd_iff_not_even.2 $ λ hn, hne $ by rwa [hf.iterate_even hn, eq_comm] at H, hf.iterate_odd⟩
theorem iterate_eq_id (hf : involutive f) (hne : f ≠ id) : f^[n] = id ↔ even n :=
⟨λ H, even_iff_not_odd.2 $ λ hn, hne $ by rwa [hf.iterate_odd hn] at H, hf.iterate_even⟩
end involutive
end function
variables {R : Type*} [monoid R] [has_distrib_neg R] {n : ℕ}
lemma neg_one_pow_eq_one_iff_even (h : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n :=
⟨λ h', of_not_not $ λ hn, h $ (odd.neg_one_pow $ odd_iff_not_even.mpr hn).symm.trans h',
even.neg_one_pow⟩
/-- If `a` is even, then `n` is odd iff `n % a` is odd. -/
lemma odd.mod_even_iff {n a : ℕ} (ha : even a) : odd (n % a) ↔ odd n :=
((even_sub' $ mod_le n a).mp $ even_iff_two_dvd.mpr $ (even_iff_two_dvd.mp ha).trans $
dvd_sub_mod n).symm
/-- If `a` is even, then `n` is even iff `n % a` is even. -/
lemma even.mod_even_iff {n a : ℕ} (ha : even a) : even (n % a) ↔ even n :=
((even_sub $ mod_le n a).mp $ even_iff_two_dvd.mpr $ (even_iff_two_dvd.mp ha).trans $
dvd_sub_mod n).symm
/-- If `n` is odd and `a` is even, then `n % a` is odd. -/
lemma odd.mod_even {n a : ℕ} (hn : odd n) (ha : even a) : odd (n % a) :=
(odd.mod_even_iff ha).mpr hn
/-- If `n` is even and `a` is even, then `n % a` is even. -/
lemma even.mod_even {n a : ℕ} (hn : even n) (ha : even a) : even (n % a) :=
(even.mod_even_iff ha).mpr hn
/-- `2` is not a prime factor of an odd natural number. -/
lemma odd.factors_ne_two {n p : ℕ} (hn : odd n) (hp : p ∈ n.factors) : p ≠ 2 :=
by { rintro rfl, exact two_dvd_ne_zero.mpr (odd_iff.mp hn) (dvd_of_mem_factors hp) }
|
c2f61792c24c2c00cdb9aa4911030cebb1a11c04 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/calculus/deriv.lean | 4b673fbaf198b44fff6f79c29590c0d362ae198d | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 94,836 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sébastien Gouëzel
-/
import analysis.calculus.fderiv.basic
import data.polynomial.algebra_map
import data.polynomial.derivative
import linear_algebra.affine_space.slope
/-!
# One-dimensional derivatives
This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a
normed field and `F` is a normed space over this field. The derivative of
such a function `f` at a point `x` is given by an element `f' : F`.
The theory is developed analogously to the [Fréchet
derivatives](./fderiv.html). We first introduce predicates defined in terms
of the corresponding predicates for Fréchet derivatives:
- `has_deriv_at_filter f f' x L` states that the function `f` has the
derivative `f'` at the point `x` as `x` goes along the filter `L`.
- `has_deriv_within_at f f' s x` states that the function `f` has the
derivative `f'` at the point `x` within the subset `s`.
- `has_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x`.
- `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x` in the sense of strict differentiability, i.e.,
`f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`.
For the last two notions we also define a functional version:
- `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the
derivative does not exist, then `deriv_within f s x` equals zero.
- `deriv f x` is a derivative of `f` at `x`. If the derivative does not
exist, then `deriv f x` equals zero.
The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the
one-dimensional derivatives coincide with the general Fréchet derivatives.
We also show the existence and compute the derivatives of:
- constants
- the identity function
- linear maps
- addition
- sum of finitely many functions
- negation
- subtraction
- multiplication
- inverse `x → x⁻¹`
- multiplication of two functions in `𝕜 → 𝕜`
- multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E`
- composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜`
- composition of a function in `F → E` with a function in `𝕜 → F`
- inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
- division
- polynomials
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.
We set up the simplifier so that it can compute the derivative of simple functions. For instance,
```lean
example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) :=
by { simp, ring }
```
## Implementation notes
Most of the theorems are direct restatements of the corresponding theorems
for Fréchet derivatives.
The strategy to construct simp lemmas that give the simplifier the possibility to compute
derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`.
See the explanations there.
-/
universes u v w
noncomputable theory
open_locale classical topology big_operators filter ennreal polynomial
open filter asymptotics set
open continuous_linear_map (smul_right smul_right_one_eq_iff)
variables {𝕜 : Type u} [nontrivially_normed_field 𝕜]
section
variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F]
variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E]
/--
`f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`.
-/
def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) :=
has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L
/--
`f` has the derivative `f'` at the point `x` within the subset `s`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝[s] x)
/--
`f` has the derivative `f'` at the point `x`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`.
-/
def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝 x)
/-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability.
That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/
def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x
/--
Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then
`f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) :=
fderiv_within 𝕜 f s x 1
/--
Derivative of `f` at the point `x`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then
`f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`.
-/
def deriv (f : 𝕜 → F) (x : 𝕜) :=
fderiv 𝕜 f x 1
variables {f f₀ f₁ g : 𝕜 → F}
variables {f' f₀' f₁' g' : F}
variables {x : 𝕜}
variables {s t : set 𝕜}
variables {L L₁ L₂ : filter 𝕜}
/-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/
lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L :=
by simp [has_deriv_at_filter]
lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L :=
has_fderiv_at_filter_iff_has_deriv_at_filter.mp
/-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/
lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
/-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/
lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x ↔
has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
iff.rfl
lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x :=
has_fderiv_within_at_iff_has_deriv_within_at.mp
lemma has_deriv_within_at.has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
has_deriv_within_at_iff_has_fderiv_within_at.mp
/-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/
lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x → has_deriv_at f (f' 1) x :=
has_fderiv_at_iff_has_deriv_at.mp
lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x :=
by simp [has_strict_deriv_at, has_strict_fderiv_at]
protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x :=
has_strict_fderiv_at_iff_has_strict_deriv_at.mp
lemma has_strict_deriv_at_iff_has_strict_fderiv_at :
has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _
/-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/
lemma has_deriv_at_iff_has_fderiv_at {f' : F} :
has_deriv_at f f' x ↔
has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _
lemma deriv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 :=
by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption }
lemma differentiable_within_at_of_deriv_within_ne_zero (h : deriv_within f s x ≠ 0) :
differentiable_within_at 𝕜 f s x :=
not_imp_comm.1 deriv_within_zero_of_not_differentiable_within_at h
lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 :=
by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption }
lemma differentiable_at_of_deriv_ne_zero (h : deriv f x ≠ 0) : differentiable_at 𝕜 f x :=
not_imp_comm.1 deriv_zero_of_not_differentiable_at h
theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x)
(h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' :=
smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁
theorem has_deriv_at_filter_iff_is_o :
has_deriv_at_filter f f' x L ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[L] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_filter_iff_tendsto :
has_deriv_at_filter f f' x L ↔
tendsto (λ x' : 𝕜, ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) L (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_within_at_iff_is_o :
has_deriv_within_at f f' s x
↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝[s] x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_at_iff_is_o :
has_deriv_at f f' x ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝 x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) :
has_deriv_at f f' x :=
h.has_fderiv_at
/-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical
definition with a limit. In this version we have to take the limit along the subset `-{x}`,
because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/
lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} :
has_deriv_at_filter f f' x L ↔ tendsto (slope f x) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') :=
begin
conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (norm_inv _).symm,
(norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] },
conv_rhs { rw [← nhds_translation_sub f', tendsto_comap_iff] },
refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _),
refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right,
simp only [(∘)],
rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul, slope_def_module]
end
lemma has_deriv_within_at_iff_tendsto_slope :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s \ {x}] x) (𝓝 f') :=
begin
simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm],
exact has_deriv_at_filter_iff_tendsto_slope
end
lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s] x) (𝓝 f') :=
begin
convert ← has_deriv_within_at_iff_tendsto_slope,
exact diff_singleton_eq_self hs
end
lemma has_deriv_at_iff_tendsto_slope :
has_deriv_at f f' x ↔ tendsto (slope f x) (𝓝[≠] x) (𝓝 f') :=
has_deriv_at_filter_iff_tendsto_slope
theorem has_deriv_within_at_congr_set {s t u : set 𝕜}
(hu : u ∈ 𝓝 x) (h : s ∩ u = t ∩ u) :
has_deriv_within_at f f' s x ↔ has_deriv_within_at f f' t x :=
by simp_rw [has_deriv_within_at, nhds_within_eq_nhds_within' hu h]
alias has_deriv_within_at_congr_set ↔ has_deriv_within_at.congr_set _
@[simp] lemma has_deriv_within_at_diff_singleton :
has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x :=
by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem]
@[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] :
has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x :=
by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Ioi_iff_Ici ↔
has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici
@[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] :
has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x :=
by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Iio_iff_Iic ↔
has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic
theorem has_deriv_within_at.Ioi_iff_Ioo [linear_order 𝕜] [order_closed_topology 𝕜] {x y : 𝕜}
(h : x < y) :
has_deriv_within_at f f' (Ioo x y) x ↔ has_deriv_within_at f f' (Ioi x) x :=
has_deriv_within_at_congr_set (is_open_Iio.mem_nhds h) $
by { rw [Ioi_inter_Iio, inter_eq_left_iff_subset], exact Ioo_subset_Iio_self }
alias has_deriv_within_at.Ioi_iff_Ioo ↔
has_deriv_within_at.Ioi_of_Ioo has_deriv_within_at.Ioo_of_Ioi
theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔
(λh, f (x + h) - f x - h • f') =o[𝓝 0] (λh, h) :=
has_fderiv_at_iff_is_o_nhds_zero
theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_deriv_at_filter f f' x L₁ :=
has_fderiv_at_filter.mono h hst
theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) :
has_deriv_within_at f f' s x :=
has_fderiv_within_at.mono h hst
theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) :
has_deriv_at_filter f f' x L :=
has_fderiv_at.has_fderiv_at_filter h hL
theorem has_deriv_at.has_deriv_within_at
(h : has_deriv_at f f' x) : has_deriv_within_at f f' s x :=
has_fderiv_at.has_fderiv_within_at h
lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
has_fderiv_within_at.differentiable_within_at h
lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x :=
has_fderiv_at.differentiable_at h
@[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x :=
has_fderiv_within_at_univ
theorem has_deriv_at.unique
(h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' :=
smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁
lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter' h
lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter h
lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x)
(ht : has_deriv_within_at f f' t x) :
has_deriv_within_at f f' (s ∪ t) x :=
hs.has_fderiv_within_at.union ht.has_fderiv_within_at
lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x :=
(has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_deriv_at f f' x :=
has_fderiv_within_at.has_fderiv_at h hs
lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_deriv_within_at f (deriv_within f s x) s x :=
h.has_fderiv_within_at.has_deriv_within_at
lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x :=
h.has_fderiv_at.has_deriv_at
@[simp] lemma has_deriv_at_deriv_iff : has_deriv_at f (deriv f x) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, h.differentiable_at, λ h, h.has_deriv_at⟩
@[simp] lemma has_deriv_within_at_deriv_within_iff :
has_deriv_within_at f (deriv_within f s x) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, h.differentiable_within_at, λ h, h.has_deriv_within_at⟩
lemma differentiable_on.has_deriv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
has_deriv_at f (deriv f x) x :=
(h.has_fderiv_at hs).has_deriv_at
lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' :=
h.differentiable_at.has_deriv_at.unique h
lemma deriv_eq {f' : 𝕜 → F} (h : ∀ x, has_deriv_at f (f' x) x) : deriv f = f' :=
funext $ λ x, (h x).deriv
lemma has_deriv_within_at.deriv_within
(h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within f s x = f' :=
hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h
lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x :=
rfl
lemma deriv_within_fderiv_within :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x :=
by simp [deriv_within]
lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x :=
rfl
lemma deriv_fderiv :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x :=
by simp [deriv]
lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x)
(hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x :=
by { unfold deriv_within deriv, rw h.fderiv_within hxs }
theorem has_deriv_within_at.deriv_eq_zero (hd : has_deriv_within_at f 0 s x)
(H : unique_diff_within_at 𝕜 s x) : deriv f x = 0 :=
(em' (differentiable_at 𝕜 f x)).elim deriv_zero_of_not_differentiable_at $
λ h, H.eq_deriv _ h.has_deriv_at.has_deriv_within_at hd
lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
deriv_within f s x = deriv_within f t x :=
((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht
@[simp] lemma deriv_within_univ : deriv_within f univ = deriv f :=
by { ext, unfold deriv_within deriv, rw fderiv_within_univ }
lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
deriv_within f (s ∩ t) x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_inter ht hs }
lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) :
deriv_within f s x = deriv f x :=
by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl }
lemma deriv_mem_iff {f : 𝕜 → F} {s : set F} {x : 𝕜} :
deriv f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ deriv f x ∈ s) ∨
(¬differentiable_at 𝕜 f x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_at 𝕜 f x; simp [deriv_zero_of_not_differentiable_at, *]
lemma deriv_within_mem_iff {f : 𝕜 → F} {t : set 𝕜} {s : set F} {x : 𝕜} :
deriv_within f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ deriv_within f t x ∈ s) ∨
(¬differentiable_within_at 𝕜 f t x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_within_at 𝕜 f t x;
simp [deriv_within_zero_of_not_differentiable_within_at, *]
lemma differentiable_within_at_Ioi_iff_Ici [partial_order 𝕜] :
differentiable_within_at 𝕜 f (Ioi x) x ↔ differentiable_within_at 𝕜 f (Ici x) x :=
⟨λ h, h.has_deriv_within_at.Ici_of_Ioi.differentiable_within_at,
λ h, h.has_deriv_within_at.Ioi_of_Ici.differentiable_within_at⟩
lemma deriv_within_Ioi_eq_Ici {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] (f : ℝ → E)
(x : ℝ) :
deriv_within f (Ioi x) x = deriv_within f (Ici x) x :=
begin
by_cases H : differentiable_within_at ℝ f (Ioi x) x,
{ have A := H.has_deriv_within_at.Ici_of_Ioi,
have B := (differentiable_within_at_Ioi_iff_Ici.1 H).has_deriv_within_at,
simpa using (unique_diff_on_Ici x).eq le_rfl A B },
{ rw [deriv_within_zero_of_not_differentiable_within_at H,
deriv_within_zero_of_not_differentiable_within_at],
rwa differentiable_within_at_Ioi_iff_Ici at H }
end
section congr
/-! ### Congruence properties of derivatives -/
theorem filter.eventually_eq.has_deriv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') :
has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L :=
h₀.has_fderiv_at_filter_iff hx (by simp [h₁])
lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L :=
by rwa hL.has_deriv_at_filter_iff hx rfl
lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x :=
has_fderiv_within_at.congr_mono h ht hx h₁
lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_deriv_within_at.congr_of_mem (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr hs (hs _ hx)
lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx)
lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _)
lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw hL.fderiv_within_eq hs hx }
lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr hs hL hx }
lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x :=
by { unfold deriv, rwa filter.eventually_eq.fderiv_eq }
protected lemma filter.eventually_eq.deriv (h : f₁ =ᶠ[𝓝 x] f) : deriv f₁ =ᶠ[𝓝 x] deriv f :=
h.eventually_eq_nhds.mono $ λ x h, h.deriv_eq
end congr
section id
/-! ### Derivative of the identity -/
variables (s x L)
theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L :=
(has_fderiv_at_filter_id x L).has_deriv_at_filter
theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id : has_deriv_at id 1 x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x :=
has_deriv_at_filter_id _ _
theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x :=
(has_strict_fderiv_at_id x).has_strict_deriv_at
lemma deriv_id : deriv id x = 1 :=
has_deriv_at.deriv (has_deriv_at_id x)
@[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id
@[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) = λ _, 1 := deriv_id'
lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 :=
(has_deriv_within_at_id x s).deriv_within hxs
end id
section const
/-! ### Derivative of constant functions -/
variables (c : F) (s x L)
theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L :=
(has_fderiv_at_filter_const c x L).has_deriv_at_filter
theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x :=
(has_strict_fderiv_at_const c x).has_strict_deriv_at
theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x :=
has_deriv_at_filter_const _ _ _
theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x :=
has_deriv_at_filter_const _ _ _
lemma deriv_const : deriv (λ x, c) x = 0 :=
has_deriv_at.deriv (has_deriv_at_const x c)
@[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 :=
funext (λ x, deriv_const x c)
lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 :=
(has_deriv_within_at_const _ _ _).deriv_within hxs
end const
section continuous_linear_map
/-! ### Derivative of continuous linear maps -/
variables (e : 𝕜 →L[𝕜] F)
protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.has_fderiv_at_filter.has_deriv_at_filter
protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.has_strict_fderiv_at.has_strict_deriv_at
protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end continuous_linear_map
section linear_map
/-! ### Derivative of bundled linear maps -/
variables (e : 𝕜 →ₗ[𝕜] F)
protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.to_continuous_linear_map₁.has_deriv_at_filter
protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.to_continuous_linear_map₁.has_strict_deriv_at
protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end linear_map
section add
/-! ### Derivative of the sum of two functions -/
theorem has_deriv_at_filter.add
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ y, f y + g y) (f' + g') x L :=
by simpa using (hf.add hg).has_deriv_at_filter
theorem has_strict_deriv_at.add
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ y, f y + g y) (f' + g') x :=
by simpa using (hf.add hg).has_strict_deriv_at
theorem has_deriv_within_at.add
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_deriv_at.add
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x :=
(hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λy, f y + g y) x = deriv f x + deriv g x :=
(hf.has_deriv_at.add hg.has_deriv_at).deriv
theorem has_deriv_at_filter.add_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c)
theorem has_deriv_within_at.add_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_deriv_at.add_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y + c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_add_const hxs]
lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x :=
by simp only [deriv, fderiv_add_const]
@[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f :=
funext $ λ x, deriv_add_const c
theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf
theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c + f y) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_const_add hxs]
lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x :=
by simp only [deriv, fderiv_const_add]
@[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f :=
funext $ λ x, deriv_const_add c
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F}
theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) :
has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter
theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) :
has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at
theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) :
has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_deriv_at_filter.sum h
theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) :
has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_deriv_at_filter.sum h
lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x :=
(has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs
@[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x :=
(has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv
end sum
section pi
/-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/
variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)]
[Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i}
@[simp] lemma has_strict_deriv_at_pi :
has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_deriv_at_filter_pi :
has_deriv_at_filter φ φ' x L ↔
∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L :=
has_fderiv_at_filter_pi'
lemma has_deriv_at_pi :
has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:=
has_deriv_at_filter_pi
lemma has_deriv_within_at_pi :
has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:=
has_deriv_at_filter_pi
lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x :=
(has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs
lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) :
deriv φ x = λ i, deriv (λ x, φ x i) x :=
(has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv
end pi
section smul
/-! ### Derivative of the multiplication of a scalar function and a vector function -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : 𝕜 → 𝕜'} {c' : 𝕜'}
theorem has_deriv_within_at.smul
(hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x :=
by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at
theorem has_deriv_at.smul
(hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul hf
end
theorem has_strict_deriv_at.smul
(hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
by simpa using (hc.smul hf).has_strict_deriv_at
lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x :=
(hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs
lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x :=
(hc.has_deriv_at.smul hf.has_deriv_at).deriv
theorem has_strict_deriv_at.smul_const
(hc : has_strict_deriv_at c c' x) (f : F) :
has_strict_deriv_at (λ y, c y • f) (c' • f) x :=
begin
have := hc.smul (has_strict_deriv_at_const x f),
rwa [smul_zero, zero_add] at this,
end
theorem has_deriv_within_at.smul_const
(hc : has_deriv_within_at c c' s x) (f : F) :
has_deriv_within_at (λ y, c y • f) (c' • f) s x :=
begin
have := hc.smul (has_deriv_within_at_const x s f),
rwa [smul_zero, zero_add] at this
end
theorem has_deriv_at.smul_const
(hc : has_deriv_at c c' x) (f : F) :
has_deriv_at (λ y, c y • f) (c' • f) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul_const f
end
lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f :=
(hc.has_deriv_within_at.smul_const f).deriv_within hxs
lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
deriv (λ y, c y • f) x = (deriv c x) • f :=
(hc.has_deriv_at.smul_const f).deriv
end smul
section const_smul
variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F]
[has_continuous_const_smul R F]
theorem has_strict_deriv_at.const_smul
(c : R) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c • f y) (c • f') x :=
by simpa using (hf.const_smul c).has_strict_deriv_at
theorem has_deriv_at_filter.const_smul
(c : R) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c • f y) (c • f') x L :=
by simpa using (hf.const_smul c).has_deriv_at_filter
theorem has_deriv_within_at.const_smul
(c : R) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c • f y) (c • f') s x :=
hf.const_smul c
theorem has_deriv_at.const_smul (c : R) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c • f y) (c • f') x :=
hf.const_smul c
lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(c : R) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c • f y) s x = c • deriv_within f s x :=
(hf.has_deriv_within_at.const_smul c).deriv_within hxs
lemma deriv_const_smul (c : R) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c • f y) x = c • deriv f x :=
(hf.has_deriv_at.const_smul c).deriv
end const_smul
section neg
/-! ### Derivative of the negative of a function -/
theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, -f x) (-f') x L :=
by simpa using h.neg.has_deriv_at_filter
theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x :=
h.neg
theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, -f x) (-f') x :=
by simpa using h.neg.has_strict_deriv_at
lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λy, -f y) s x = - deriv_within f s x :=
by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply]
lemma deriv.neg : deriv (λy, -f y) x = - deriv f x :=
by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply]
@[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) :=
funext $ λ x, deriv.neg
end neg
section neg2
/-! ### Derivative of the negation function (i.e `has_neg.neg`) -/
variables (s x L)
theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L :=
has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _
theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x :=
has_strict_deriv_at.neg $ has_strict_deriv_at_id _
lemma deriv_neg : deriv has_neg.neg x = -1 :=
has_deriv_at.deriv (has_deriv_at_neg x)
@[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 :=
funext deriv_neg
@[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 :=
deriv_neg x
lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 :=
(has_deriv_within_at_neg x s).deriv_within hxs
lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) :=
differentiable.neg differentiable_id
lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s :=
differentiable_on.neg differentiable_on_id
end neg2
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_deriv_at_filter.sub
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_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_deriv_within_at.sub
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_deriv_at.sub
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
theorem has_strict_deriv_at.sub
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x :=
(hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λ y, f y - g y) x = deriv f x - deriv g x :=
(hf.has_deriv_at.sub hg.has_deriv_at).deriv
theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) :
(λ x', f x' - f x) =O[L] (λ x', x' - x) :=
has_fderiv_at_filter.is_O_sub h
theorem has_deriv_at_filter.is_O_sub_rev (hf : has_deriv_at_filter f f' x L) (hf' : f' ≠ 0) :
(λ x', x' - x) =O[L] (λ x', f x' - f x) :=
suffices antilipschitz_with ‖f'‖₊⁻¹ (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f'), from hf.is_O_sub_rev this,
add_monoid_hom_class.antilipschitz_of_bound (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') $
λ x, by simp [norm_smul, ← div_eq_inv_mul, mul_div_cancel _ (mt norm_eq_zero.1 hf')]
theorem has_deriv_at_filter.sub_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_deriv_within_at.sub_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_deriv_at.sub_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y - c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_sub_const hxs]
lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x :=
by simp only [deriv, fderiv_sub_const]
theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c - f y) s x = -deriv_within f s x :=
by simp [deriv_within, fderiv_within_const_sub hxs]
lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x :=
by simp only [← deriv_within_univ,
deriv_within_const_sub (unique_diff_within_at_univ : unique_diff_within_at 𝕜 _ _)]
end sub
section continuous
/-! ### Continuity of a function admitting a derivative -/
theorem has_deriv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem has_deriv_within_at.continuous_within_at
(h : has_deriv_within_at f f' s x) : continuous_within_at f s x :=
has_deriv_at_filter.tendsto_nhds inf_le_left h
theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x :=
has_deriv_at_filter.tendsto_nhds le_rfl h
protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F}
(hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s :=
λ x hx, (hderiv x hx).continuous_at.continuous_within_at
end continuous
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {G : Type w} [normed_add_comm_group G] [normed_space 𝕜 G]
variables {f₂ : 𝕜 → G} {f₂' : G}
lemma has_deriv_at_filter.prod
(hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) :
has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L :=
hf₁.prod hf₂
lemma has_deriv_within_at.prod
(hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) :
has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x :=
hf₁.prod hf₂
lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) :
has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
lemma has_strict_deriv_at.prod (hf₁ : has_strict_deriv_at f₁ f₁' x)
(hf₂ : has_strict_deriv_at f₂ f₂' x) :
has_strict_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
end cartesian_product
section composition
/-!
### Derivative of the composition of a vector function and a scalar function
We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp`
in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also
because the `comp` version with the shorter name will show up much more often in applications).
The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to
usual multiplication in `comp` lemmas.
-/
/- 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 -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {s' t' : set 𝕜'}
{h : 𝕜 → 𝕜'} {h₁ : 𝕜 → 𝕜} {h₂ : 𝕜' → 𝕜'} {h' h₂' : 𝕜'} {h₁' : 𝕜}
{g₁ : 𝕜' → F} {g₁' : F} {L' : filter 𝕜'} (x)
theorem has_deriv_at_filter.scomp
(hg : has_deriv_at_filter g₁ g₁' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L'):
has_deriv_at_filter (g₁ ∘ h) (h' • g₁') x L :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh hL).has_deriv_at_filter
theorem has_deriv_within_at.scomp_has_deriv_at
(hg : has_deriv_within_at g₁ g₁' s' (h x))
(hh : has_deriv_at h h' x) (hs : ∀ x, h x ∈ s') :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh $ tendsto_inf.2 ⟨hh.continuous_at, tendsto_principal.2 $ eventually_of_forall hs⟩
theorem has_deriv_within_at.scomp
(hg : has_deriv_within_at g₁ g₁' t' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s t') :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
hg.scomp x hh $ hh.continuous_within_at.tendsto_nhds_within hst
/-- The chain rule. -/
theorem has_deriv_at.scomp
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh hh.continuous_at
theorem has_strict_deriv_at.scomp
(hg : has_strict_deriv_at g₁ g₁' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (g₁ ∘ h) (h' • g₁') x :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh).has_strict_deriv_at
theorem has_deriv_at.scomp_has_deriv_within_at
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
has_deriv_within_at.scomp x hg.has_deriv_within_at hh (maps_to_univ _ _)
lemma deriv_within.scomp
(hg : differentiable_within_at 𝕜' g₁ t' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s t') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (g₁ ∘ h) s x = deriv_within h s x • deriv_within g₁ t' (h x) :=
(has_deriv_within_at.scomp x hg.has_deriv_within_at hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.scomp
(hg : differentiable_at 𝕜' g₁ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (g₁ ∘ h) x = deriv h x • deriv g₁ (h x) :=
(has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at).deriv
/-! ### Derivative of the composition of a scalar and vector functions -/
theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
{L'' : filter E} (hh₂ : has_deriv_at_filter h₂ h₂' (f x) L')
(hf : has_fderiv_at_filter f f' x L'') (hL : tendsto f L'' L') :
has_fderiv_at_filter (h₂ ∘ f) (h₂' • f') x L'' :=
by { convert (hh₂.restrict_scalars 𝕜).comp x hf hL, ext x, simp [mul_comm] }
theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_strict_deriv_at h₂ h₂' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
begin
rw has_strict_deriv_at at hh,
convert (hh.restrict_scalars 𝕜).comp x hf,
ext x,
simp [mul_comm]
end
theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_at
theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_within_at
theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s t} (x)
(hh : has_deriv_within_at h₂ h₂' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : maps_to f s t) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf $ hf.continuous_within_at.tendsto_nhds_within hst
/-! ### Derivative of the composition of two scalar functions -/
theorem has_deriv_at_filter.comp
(hh₂ : has_deriv_at_filter h₂ h₂' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L') :
has_deriv_at_filter (h₂ ∘ h) (h₂' * h') x L :=
by { rw mul_comm, exact hh₂.scomp x hh hL }
theorem has_deriv_within_at.comp
(hh₂ : has_deriv_within_at h₂ h₂' s' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s s') :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
by { rw mul_comm, exact hh₂.scomp x hh hst, }
/-- The chain rule. -/
theorem has_deriv_at.comp
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (h₂ ∘ h) (h₂' * h') x :=
hh₂.comp x hh hh.continuous_at
theorem has_strict_deriv_at.comp
(hh₂ : has_strict_deriv_at h₂ h₂' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (h₂ ∘ h) (h₂' * h') x :=
by { rw mul_comm, exact hh₂.scomp x hh }
theorem has_deriv_at.comp_has_deriv_within_at
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
hh₂.has_deriv_within_at.comp x hh (maps_to_univ _ _)
lemma deriv_within.comp
(hh₂ : differentiable_within_at 𝕜' h₂ s' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s s') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (h₂ ∘ h) s x = deriv_within h₂ s' (h x) * deriv_within h s x :=
(hh₂.has_deriv_within_at.comp x hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.comp
(hh₂ : differentiable_at 𝕜' h₂ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (h₂ ∘ h) x = deriv h₂ (h x) * deriv h x :=
(hh₂.has_deriv_at.comp x hh.has_deriv_at).deriv
protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_deriv_at_filter (f^[n]) (f'^n) x L :=
begin
have := hf.iterate hL hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_deriv_at (f^[n]) (f'^n) x :=
begin
have := has_fderiv_at.iterate hf hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_deriv_within_at (f^[n]) (f'^n) s x :=
begin
have := has_fderiv_within_at.iterate hf hx hs n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_deriv_at (f^[n]) (f'^n) x :=
begin
have := hf.iterate hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
end composition
section composition_vector
/-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/
open continuous_linear_map
variables {l : F → E} {l' : F →L[𝕜] E}
variable (x)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set
equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F}
(hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x)
(hst : maps_to f s t) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_fderiv_within_at hst).has_deriv_within_at
theorem has_fderiv_at.comp_has_deriv_within_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
hl.has_fderiv_within_at.comp_has_deriv_within_at x hf (maps_to_univ _ _)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the
Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) :
has_deriv_at (l ∘ f) (l' f') x :=
has_deriv_within_at_univ.mp $ hl.comp_has_deriv_within_at x hf.has_deriv_within_at
theorem has_strict_fderiv_at.comp_has_strict_deriv_at
(hl : has_strict_fderiv_at l l' (f x)) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (l ∘ f) (l' f') x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_strict_fderiv_at).has_strict_deriv_at
lemma fderiv_within.comp_deriv_within {t : set F}
(hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hs : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) :=
(hl.has_fderiv_within_at.comp_has_deriv_within_at x hf.has_deriv_within_at hs).deriv_within hxs
lemma fderiv.comp_deriv
(hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) :
deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) :=
(hl.has_fderiv_at.comp_has_deriv_at x hf.has_deriv_at).deriv
end composition_vector
section mul
/-! ### Derivative of the multiplication of two functions -/
variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜']
[normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'}
theorem has_deriv_within_at.mul
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x :=
begin
have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul hd
end
theorem has_strict_deriv_at.mul
(hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x :=
(hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x :=
(hc.has_deriv_at.mul hd.has_deriv_at).deriv
theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) :
has_deriv_within_at (λ y, c y * d) (c' * d) s x :=
begin
convert hc.mul (has_deriv_within_at_const x s d),
rw [mul_zero, add_zero]
end
theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) :
has_deriv_at (λ y, c y * d) (c' * d) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul_const d
end
theorem has_deriv_at_mul_const (c : 𝕜) : has_deriv_at (λ x, x * c) c x :=
by simpa only [one_mul] using (has_deriv_at_id' x).mul_const c
theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) :
has_strict_deriv_at (λ y, c y * d) (c' * d) x :=
begin
convert hc.mul (has_strict_deriv_at_const x d),
rw [mul_zero, add_zero]
end
lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) :
deriv_within (λ y, c y * d) s x = deriv_within c s x * d :=
(hc.has_deriv_within_at.mul_const d).deriv_within hxs
lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) :
deriv (λ y, c y * d) x = deriv c x * d :=
(hc.has_deriv_at.mul_const d).deriv
lemma deriv_mul_const_field (v : 𝕜') :
deriv (λ y, u y * v) x = deriv u x * v :=
begin
by_cases hu : differentiable_at 𝕜 u x,
{ exact deriv_mul_const hu v },
{ rw [deriv_zero_of_not_differentiable_at hu, zero_mul],
rcases eq_or_ne v 0 with rfl|hd,
{ simp only [mul_zero, deriv_const] },
{ refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu),
simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } }
end
@[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v :=
funext $ λ _, deriv_mul_const_field v
theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c * d y) (c * d') s x :=
begin
convert (has_deriv_within_at_const x s c).mul hd,
rw [zero_mul, zero_add]
end
theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c * d y) (c * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hd.const_mul c
end
theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c * d y) (c * d') x :=
begin
convert (has_strict_deriv_at_const _ _).mul hd,
rw [zero_mul, zero_add]
end
lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c * d y) s x = c * deriv_within d s x :=
(hd.has_deriv_within_at.const_mul c).deriv_within hxs
lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c * d y) x = c * deriv d x :=
(hd.has_deriv_at.const_mul c).deriv
lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x :=
by simp only [mul_comm u, deriv_mul_const_field]
@[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x :=
funext (λ x, deriv_const_mul_field u)
end mul
section inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x :=
begin
suffices : (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)]
(λ p, (p.1 - p.2) * 1),
{ refine this.congr' _ (eventually_of_forall $ λ _, mul_one _),
refine eventually.mono (is_open.mem_nhds (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _,
rintro ⟨y, z⟩ ⟨hy, hz⟩,
simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz], ring, },
refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _),
rw [← sub_self (x * x)⁻¹],
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx)
end
theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) :
has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x :=
(has_strict_deriv_at_inv x_ne_zero).has_deriv_at
theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x :=
(has_deriv_at_inv x_ne_zero).has_deriv_within_at
lemma differentiable_at_inv :
differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:=
⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at,
λ H, (has_deriv_at_inv H).differentiable_at⟩
lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x⁻¹) s x :=
(differentiable_at_inv.2 x_ne_zero).differentiable_within_at
lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} :=
λx hx, differentiable_within_at_inv hx
lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ :=
begin
rcases eq_or_ne x 0 with rfl|hne,
{ simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] },
{ exact (has_deriv_at_inv hne).deriv }
end
@[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv)
lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ :=
begin
rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact deriv_inv
end
lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
has_deriv_at_inv x_ne_zero
lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(has_fderiv_at_inv x_ne_zero).has_fderiv_within_at
lemma fderiv_inv :
fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
by rw [← deriv_fderiv, deriv_inv]
lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
begin
rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact fderiv_inv
end
variables {c : 𝕜 → 𝕜} {h : E → 𝕜} {c' : 𝕜} {z : E} {S : set E}
lemma has_deriv_within_at.inv
(hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) :
has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x :=
begin
convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc,
field_simp
end
lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) :
has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.inv hx
end
lemma differentiable_within_at.inv (hf : differentiable_within_at 𝕜 h S z) (hz : h z ≠ 0) :
differentiable_within_at 𝕜 (λx, (h x)⁻¹) S z :=
(differentiable_at_inv.mpr hz).comp_differentiable_within_at z hf
@[simp] lemma differentiable_at.inv (hf : differentiable_at 𝕜 h z) (hz : h z ≠ 0) :
differentiable_at 𝕜 (λx, (h x)⁻¹) z :=
(differentiable_at_inv.mpr hz).comp z hf
lemma differentiable_on.inv (hf : differentiable_on 𝕜 h S) (hz : ∀ x ∈ S, h x ≠ 0) :
differentiable_on 𝕜 (λx, (h x)⁻¹) S :=
λx h, (hf x h).inv (hz x h)
@[simp] lemma differentiable.inv (hf : differentiable 𝕜 h) (hz : ∀ x, h x ≠ 0) :
differentiable 𝕜 (λx, (h x)⁻¹) :=
λx, (hf x).inv (hz x)
lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 :=
(hc.has_deriv_within_at.inv hx).deriv_within hxs
@[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 :=
(hc.has_deriv_at.inv hx).deriv
end inverse
section division
/-! ### Derivative of `x ↦ c x / d x` -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{c d : 𝕜 → 𝕜'} {c' d' : 𝕜'}
lemma has_deriv_within_at.div
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) :
has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x :=
begin
convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x)
(hx : d x ≠ 0) :
has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) :
has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.div hd hx
end
lemma differentiable_within_at.div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) :
differentiable_within_at 𝕜 (λx, c x / d x) s x :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at
@[simp] lemma differentiable_at.div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
differentiable_at 𝕜 (λx, c x / d x) x :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at
lemma differentiable_on.div
(hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) :
differentiable_on 𝕜 (λx, c x / d x) s :=
λx h, (hc x h).div (hd x h) (hx x h)
@[simp] lemma differentiable.div
(hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) :
differentiable 𝕜 (λx, c x / d x) :=
λx, (hc x).div (hd x) (hx x)
lemma deriv_within_div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d x) s x
= ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs
@[simp] lemma deriv_div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv
lemma has_deriv_at.div_const (hc : has_deriv_at c c' x) (d : 𝕜') :
has_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_deriv_within_at.div_const (hc : has_deriv_within_at c c' s x) (d : 𝕜') :
has_deriv_within_at (λ x, c x / d) (c' / d) s x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_strict_deriv_at.div_const (hc : has_strict_deriv_at c c' x) (d : 𝕜') :
has_strict_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜') :
differentiable_within_at 𝕜 (λx, c x / d) s x :=
(hc.has_deriv_within_at.div_const _).differentiable_within_at
@[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) (d : 𝕜') :
differentiable_at 𝕜 (λ x, c x / d) x :=
(hc.has_deriv_at.div_const _).differentiable_at
lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) (d : 𝕜') :
differentiable_on 𝕜 (λx, c x / d) s :=
λ x hx, (hc x hx).div_const d
@[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) (d : 𝕜') :
differentiable 𝕜 (λx, c x / d) :=
λ x, (hc x).div_const d
lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜')
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d) s x = (deriv_within c s x) / d :=
by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs]
@[simp] lemma deriv_div_const (d : 𝕜') :
deriv (λx, c x / d) x = (deriv c x) / d :=
by simp only [div_eq_mul_inv, deriv_mul_const_field]
end division
section clm_comp_apply
/-! ### Derivative of the pointwise composition/application of continuous linear maps -/
open continuous_linear_map
variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G}
{c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F}
lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x)
(hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x :=
begin
have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x)
(hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x :=
begin
have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, (c y).comp (d y))
(c'.comp (d x) + (c x).comp d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.clm_comp hd
end
lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x)
(hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x):
deriv_within (λ y, (c y).comp (d y)) s x =
((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) :=
(hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, (c y).comp (d y)) x =
((deriv c x).comp (d x) + (c x).comp (deriv d x)) :=
(hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv
lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x)
(hu : has_strict_deriv_at u u' x) :
has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x)
(hu : has_deriv_within_at u u' s x) :
has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x :=
begin
have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) :
has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) :
deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) :=
(hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) :
deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) :=
(hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv
end clm_comp_apply
theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) :
has_strict_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x)
(hf' : f' ≠ 0) :
has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
/-- 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_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_deriv_at g f'⁻¹ a :=
(hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a
nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` 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. -/
lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) :
has_strict_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
/-- 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_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_deriv_at g f'⁻¹ a :=
(hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
nonzero 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_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) :
has_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
∀ᶠ z in 𝓝[≠] x, f z ≠ f x :=
(has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne
⟨‖f'‖⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩
lemma has_deriv_at.tendsto_punctured_nhds (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
tendsto f (𝓝[≠] x) (𝓝[≠] (f x)) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
h.continuous_at.continuous_within_at (h.eventually_ne hf')
theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a)
(hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) :
¬differentiable_within_at 𝕜 g s a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha,
simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _)
end
theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) :
¬differentiable_at 𝕜 g a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm,
simpa using this.unique (has_deriv_at_id a)
end
end
namespace polynomial
/-! ### Derivative of a polynomial -/
variables {R : Type*} [comm_semiring R] [algebra R 𝕜]
variables (p : 𝕜[X]) (q : R[X]) {x : 𝕜} {s : set 𝕜}
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_strict_deriv_at (x : 𝕜) :
has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
begin
apply p.induction_on,
{ simp [has_strict_deriv_at_const] },
{ assume p q hp hq,
convert hp.add hq;
simp },
{ assume n a h,
convert h.mul (has_strict_deriv_at_id x),
{ ext y, simp [pow_add, mul_assoc] },
{ simp only [pow_add, pow_one, derivative_mul, derivative_C, zero_mul, derivative_X_pow,
derivative_X, mul_one, zero_add, eval_mul, eval_C, eval_add, eval_nat_cast, eval_pow, eval_X,
id.def], ring } }
end
protected lemma has_strict_deriv_at_aeval (x : 𝕜) :
has_strict_deriv_at (λx, aeval x q) (aeval x q.derivative) x :=
by simpa only [aeval_def, eval₂_eq_eval_map, derivative_map]
using (q.map (algebra_map R 𝕜)).has_strict_deriv_at x
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
(p.has_strict_deriv_at x).has_deriv_at
protected lemma has_deriv_at_aeval (x : 𝕜) :
has_deriv_at (λx, aeval x q) (aeval x q.derivative) x :=
(q.has_strict_deriv_at_aeval x).has_deriv_at
protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x :=
(p.has_deriv_at x).has_deriv_within_at
protected theorem has_deriv_within_at_aeval (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, aeval x q) (aeval x q.derivative) s x :=
(q.has_deriv_at_aeval x).has_deriv_within_at
protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x :=
(p.has_deriv_at x).differentiable_at
protected lemma differentiable_at_aeval : differentiable_at 𝕜 (λx, aeval x q) x :=
(q.has_deriv_at_aeval x).differentiable_at
protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x :=
p.differentiable_at.differentiable_within_at
protected lemma differentiable_within_at_aeval : differentiable_within_at 𝕜 (λx, aeval x q) s x :=
q.differentiable_at_aeval.differentiable_within_at
protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) :=
λx, p.differentiable_at
protected lemma differentiable_aeval : differentiable 𝕜 (λ x : 𝕜, aeval x q) :=
λx, q.differentiable_at_aeval
protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s :=
p.differentiable.differentiable_on
protected lemma differentiable_on_aeval : differentiable_on 𝕜 (λx, aeval x q) s :=
q.differentiable_aeval.differentiable_on
@[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x :=
(p.has_deriv_at x).deriv
@[simp] protected lemma deriv_aeval : deriv (λx, aeval x q) x = aeval x q.derivative :=
(q.has_deriv_at_aeval x).deriv
protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, p.eval x) s x = p.derivative.eval x :=
begin
rw differentiable_at.deriv_within p.differentiable_at hxs,
exact p.deriv
end
protected lemma deriv_within_aeval (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, aeval x q) s x = aeval x q.derivative :=
by simpa only [aeval_def, eval₂_eq_eval_map, derivative_map]
using (q.map (algebra_map R 𝕜)).deriv_within hxs
protected lemma has_fderiv_at (x : 𝕜) :
has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x :=
p.has_deriv_at x
protected lemma has_fderiv_at_aeval (x : 𝕜) :
has_fderiv_at (λx, aeval x q) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (aeval x q.derivative)) x :=
q.has_deriv_at_aeval x
protected lemma has_fderiv_within_at (x : 𝕜) :
has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x :=
(p.has_fderiv_at x).has_fderiv_within_at
protected lemma has_fderiv_within_at_aeval (x : 𝕜) :
has_fderiv_within_at (λx, aeval x q) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (aeval x q.derivative)) s x :=
(q.has_fderiv_at_aeval x).has_fderiv_within_at
@[simp] protected lemma fderiv :
fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_at x).fderiv
@[simp] protected lemma fderiv_aeval :
fderiv 𝕜 (λx, aeval x q) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (aeval x q.derivative) :=
(q.has_fderiv_at_aeval x).fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_within_at x).fderiv_within hxs
protected lemma fderiv_within_aeval (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, aeval x q) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (aeval x q.derivative) :=
(q.has_fderiv_within_at_aeval x).fderiv_within hxs
end polynomial
section pow
/-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/
variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜}
variable (n : ℕ)
lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) :
has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
begin
convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x,
{ simp },
{ rw [polynomial.derivative_C_mul_X_pow], simp }
end
lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
(has_strict_deriv_at_pow n x).has_deriv_at
theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x :=
(has_deriv_at_pow n x).has_deriv_within_at
lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x :=
(has_deriv_at_pow n x).differentiable_at
lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x :=
(differentiable_at_pow n).differentiable_within_at
lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) :=
λ x, differentiable_at_pow n
lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s :=
(differentiable_pow n).differentiable_on
lemma deriv_pow : deriv (λ x, x^n) x = (n : 𝕜) * x^(n-1) :=
(has_deriv_at_pow n x).deriv
@[simp] lemma deriv_pow' : deriv (λ x, x^n) = λ x, (n : 𝕜) * x^(n-1) :=
funext $ λ x, deriv_pow n
lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) :=
(has_deriv_within_at_pow n x s).deriv_within hxs
lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) :
has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x :=
(has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc
lemma has_deriv_at.pow (hc : has_deriv_at c c' x) :
has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x :=
by { rw ← has_deriv_within_at_univ at *, exact hc.pow n }
lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) :=
(hc.has_deriv_within_at.pow n).deriv_within hxs
@[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) :
deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) :=
(hc.has_deriv_at.pow n).deriv
end pow
section zpow
/-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {x : 𝕜} {s : set 𝕜} {m : ℤ}
lemma has_strict_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
begin
have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x,
{ assume m hm,
lift m to ℕ using (le_of_lt hm),
simp only [zpow_coe_nat, int.cast_coe_nat],
convert has_strict_deriv_at_pow _ _ using 2,
rw [← int.coe_nat_one, ← int.coe_nat_sub, zpow_coe_nat],
norm_cast at hm,
exact nat.succ_le_of_lt hm },
rcases lt_trichotomy m 0 with hm|hm|hm,
{ have hx : x ≠ 0, from h.resolve_right hm.not_le,
have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm));
[skip, exact zpow_ne_zero_of_ne_zero hx _],
simp only [(∘), zpow_neg, one_div, inv_inv, smul_eq_mul] at this,
convert this using 1,
rw [sq, mul_inv, inv_inv, int.cast_neg, neg_mul, neg_mul_neg,
← zpow_add₀ hx, mul_assoc, ← zpow_add₀ hx], congr, abel },
{ simp only [hm, zpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] },
{ exact this m hm }
end
lemma has_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
(has_strict_deriv_at_zpow m x h).has_deriv_at
theorem has_deriv_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) (s : set 𝕜) :
has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x :=
(has_deriv_at_zpow m x h).has_deriv_within_at
lemma differentiable_at_zpow : differentiable_at 𝕜 (λx, x^m) x ↔ x ≠ 0 ∨ 0 ≤ m :=
⟨λ H, normed_field.continuous_at_zpow.1 H.continuous_at,
λ H, (has_deriv_at_zpow m x H).differentiable_at⟩
lemma differentiable_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λx, x^m) s x :=
(differentiable_at_zpow.mpr h).differentiable_within_at
lemma differentiable_on_zpow (m : ℤ) (s : set 𝕜) (h : (0 : 𝕜) ∉ s ∨ 0 ≤ m) :
differentiable_on 𝕜 (λx, x^m) s :=
λ x hxs, differentiable_within_at_zpow m x $ h.imp_left $ ne_of_mem_of_not_mem hxs
lemma deriv_zpow (m : ℤ) (x : 𝕜) : deriv (λ x, x ^ m) x = m * x ^ (m - 1) :=
begin
by_cases H : x ≠ 0 ∨ 0 ≤ m,
{ exact (has_deriv_at_zpow m x H).deriv },
{ rw deriv_zero_of_not_differentiable_at (mt differentiable_at_zpow.1 H),
push_neg at H, rcases H with ⟨rfl, hm⟩,
rw [zero_zpow _ ((sub_one_lt _).trans hm).ne, mul_zero] }
end
@[simp] lemma deriv_zpow' (m : ℤ) : deriv (λ x : 𝕜, x ^ m) = λ x, m * x ^ (m - 1) :=
funext $ deriv_zpow m
lemma deriv_within_zpow (hxs : unique_diff_within_at 𝕜 s x) (h : x ≠ 0 ∨ 0 ≤ m) :
deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) :=
(has_deriv_within_at_zpow m x h s).deriv_within hxs
@[simp] lemma iter_deriv_zpow' (m : ℤ) (k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ m) = λ x, (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
begin
induction k with k ihk,
{ simp only [one_mul, int.coe_nat_zero, id, sub_zero, finset.prod_range_zero,
function.iterate_zero] },
{ simp only [function.iterate_succ_apply', ihk, deriv_const_mul_field', deriv_zpow',
finset.prod_range_succ, int.coe_nat_succ, ← sub_sub, int.cast_sub, int.cast_coe_nat,
mul_assoc], }
end
lemma iter_deriv_zpow (m : ℤ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λ y, y ^ m) x = (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
congr_fun (iter_deriv_zpow' m k) x
lemma iter_deriv_pow (n : ℕ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i)) * x^(n-k) :=
begin
simp only [← zpow_coe_nat, iter_deriv_zpow, int.cast_coe_nat],
cases le_or_lt k n with hkn hnk,
{ rw int.coe_nat_sub hkn },
{ have : ∏ i in finset.range k, (n - i : 𝕜) = 0,
from finset.prod_eq_zero (finset.mem_range.2 hnk) (sub_self _),
simp only [this, zero_mul] }
end
@[simp] lemma iter_deriv_pow' (n k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ n) = λ x, (∏ i in finset.range k, (n - i)) * x ^ (n - k) :=
funext $ λ x, iter_deriv_pow n x k
lemma iter_deriv_inv (k : ℕ) (x : 𝕜) :
deriv^[k] has_inv.inv x = (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
by simpa only [zpow_neg_one, int.cast_neg, int.cast_one] using iter_deriv_zpow (-1) x k
@[simp] lemma iter_deriv_inv' (k : ℕ) :
deriv^[k] has_inv.inv = λ x : 𝕜, (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
funext (iter_deriv_inv k)
variables {f : E → 𝕜} {t : set E} {a : E}
lemma differentiable_within_at.zpow (hf : differentiable_within_at 𝕜 f t a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λ x, f x ^ m) t a :=
(differentiable_at_zpow.2 h).comp_differentiable_within_at a hf
lemma differentiable_at.zpow (hf : differentiable_at 𝕜 f a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_at 𝕜 (λ x, f x ^ m) a :=
(differentiable_at_zpow.2 h).comp a hf
lemma differentiable_on.zpow (hf : differentiable_on 𝕜 f t) (h : (∀ x ∈ t, f x ≠ 0) ∨ 0 ≤ m) :
differentiable_on 𝕜 (λ x, f x ^ m) t :=
λ x hx, (hf x hx).zpow $ h.imp_left (λ h, h x hx)
lemma differentiable.zpow (hf : differentiable 𝕜 f) (h : (∀ x, f x ≠ 0) ∨ 0 ≤ m) :
differentiable 𝕜 (λ x, f x ^ m) :=
λ x, (hf x).zpow $ h.imp_left (λ h, h x)
end zpow
/-! ### Support of derivatives -/
section support
open function
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {f : 𝕜 → F}
lemma support_deriv_subset : support (deriv f) ⊆ tsupport f :=
begin
intros x,
rw [← not_imp_not],
intro h2x,
rw [not_mem_tsupport_iff_eventually_eq] at h2x,
exact nmem_support.mpr (h2x.deriv_eq.trans (deriv_const x 0))
end
lemma has_compact_support.deriv (hf : has_compact_support f) : has_compact_support (deriv f) :=
hf.mono' support_deriv_subset
end support
/-! ### Upper estimates on liminf and limsup -/
section real
variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ}
lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) :
∀ᶠ z in 𝓝[s \ {x}] x, slope f x z < r :=
has_deriv_within_at_iff_tendsto_slope.1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x)
(hs : x ∉ s) (hr : f' < r) :
∀ᶠ z in 𝓝[s] x, slope f x z < r :=
(has_deriv_within_at_iff_tendsto_slope' hs).1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.liminf_right_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) :
∃ᶠ z in 𝓝[>] x, slope f x z < r :=
(hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently
end real
section real_space
open metric
variables {E : Type u} [normed_add_comm_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ}
{x r : ℝ}
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ‖f'‖` the ratio
`‖f z - f x‖ / ‖z - x‖` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `‖f'‖`. -/
lemma has_deriv_within_at.limsup_norm_slope_le
(hf : has_deriv_within_at f f' s x) (hr : ‖f'‖ < r) :
∀ᶠ z in 𝓝[s] x, ‖z - x‖⁻¹ * ‖f z - f x‖ < r :=
begin
have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr,
have A : ∀ᶠ z in 𝓝[s \ {x}] x, ‖(z - x)⁻¹ • (f z - f x)‖ ∈ Iio r,
from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (is_open.mem_nhds is_open_Iio hr),
have B : ∀ᶠ z in 𝓝[{x}] x, ‖(z - x)⁻¹ • (f z - f x)‖ ∈ Iio r,
from mem_of_superset self_mem_nhds_within
(singleton_subset_iff.2 $ by simp [hr₀]),
have C := mem_sup.2 ⟨A, B⟩,
rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup] at C,
filter_upwards [C.1],
simp only [norm_smul, mem_Iio, norm_inv],
exact λ _, id
end
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ‖f'‖` the ratio
`(‖f z‖ - ‖f x‖) / ‖z - x‖` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `‖f'‖`.
This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le`
where `‖f z‖ - ‖f x‖` is replaced by `‖f z - f x‖`. -/
lemma has_deriv_within_at.limsup_slope_norm_le
(hf : has_deriv_within_at f f' s x) (hr : ‖f'‖ < r) :
∀ᶠ z in 𝓝[s] x, ‖z - x‖⁻¹ * (‖f z‖ - ‖f x‖) < r :=
begin
apply (hf.limsup_norm_slope_le hr).mono,
assume z hz,
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz,
exact inv_nonneg.2 (norm_nonneg _)
end
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ‖f'‖` the ratio
`‖f z - f x‖ / ‖z - x‖` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `‖f'‖`. See also `has_deriv_within_at.limsup_norm_slope_le`
for a stronger version using limit superior and any set `s`. -/
lemma has_deriv_within_at.liminf_right_norm_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ‖f'‖ < r) :
∃ᶠ z in 𝓝[>] x, ‖z - x‖⁻¹ * ‖f z - f x‖ < r :=
(hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ‖f'‖` the ratio
`(‖f z‖ - ‖f x‖) / (z - x)` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `‖f'‖`.
See also
* `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using
limit superior and any set `s`;
* `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using
`‖f z - f x‖` instead of `‖f z‖ - ‖f x‖`. -/
lemma has_deriv_within_at.liminf_right_slope_norm_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ‖f'‖ < r) :
∃ᶠ z in 𝓝[>] x, (z - x)⁻¹ * (‖f z‖ - ‖f x‖) < r :=
begin
have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently,
refine this.mp (eventually.mono self_mem_nhds_within _),
assume z hxz hz,
rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz
end
end real_space
|
9d96f9ab63a846c9c59ce85df945d9f1f3d9483b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/analytic/isolated_zeros.lean | aef178e90decb112a8132cf98d375a2a374b4543 | [
"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 | 9,074 | lean | /-
Copyright (c) 2022 Vincent Beffara. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Vincent Beffara
-/
import analysis.analytic.basic
import analysis.calculus.dslope
import analysis.calculus.fderiv_analytic
import analysis.calculus.formal_multilinear_series
import topology.algebra.infinite_sum
import analysis.analytic.uniqueness
/-!
# Principle of isolated zeros
This file proves the fact that the zeros of a non-constant analytic function of one variable are
isolated. It also introduces a little bit of API in the `has_fpower_series_at` namespace that is
useful in this setup.
## Main results
* `analytic_at.eventually_eq_zero_or_eventually_ne_zero` is the main statement that if a function is
analytic at `z₀`, then either it is identically zero in a neighborhood of `z₀`, or it does not
vanish in a punctured neighborhood of `z₀`.
* `analytic_on.eq_on_of_preconnected_of_frequently_eq` is the identity theorem for analytic
functions: if a function `f` is analytic on a connected set `U` and is zero on a set with an
accumulation point in `U` then `f` is identically `0` on `U`.
-/
open_locale classical
open filter function nat formal_multilinear_series emetric set
open_locale topological_space big_operators
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {s : E}
{p q : formal_multilinear_series 𝕜 𝕜 E} {f g : 𝕜 → E}
{n : ℕ} {z z₀ : 𝕜} {y : fin n → 𝕜}
namespace has_sum
variables {a : ℕ → E}
lemma has_sum_at_zero (a : ℕ → E) : has_sum (λ n, (0:𝕜) ^ n • a n) (a 0) :=
by convert has_sum_single 0 (λ b h, _); simp [nat.pos_of_ne_zero h] <|> simp
lemma exists_has_sum_smul_of_apply_eq_zero (hs : has_sum (λ m, z ^ m • a m) s)
(ha : ∀ k < n, a k = 0) :
∃ t : E, z ^ n • t = s ∧ has_sum (λ m, z ^ m • a (m + n)) t :=
begin
obtain rfl | hn := n.eq_zero_or_pos,
{ simpa },
by_cases h : z = 0,
{ have : s = 0 := hs.unique (by simpa [ha 0 hn, h] using has_sum_at_zero a),
exact ⟨a n, by simp [h, hn, this], by simpa [h] using has_sum_at_zero (λ m, a (m + n))⟩ },
{ refine ⟨(z ^ n)⁻¹ • s, by field_simp [smul_smul], _⟩,
have h1 : ∑ i in finset.range n, z ^ i • a i = 0,
from finset.sum_eq_zero (λ k hk, by simp [ha k (finset.mem_range.mp hk)]),
have h2 : has_sum (λ m, z ^ (m + n) • a (m + n)) s,
by simpa [h1] using (has_sum_nat_add_iff' n).mpr hs,
convert @has_sum.const_smul E ℕ 𝕜 _ _ _ _ _ _ _ (z⁻¹ ^ n) h2,
{ field_simp [pow_add, smul_smul] },
{ simp only [inv_pow] } }
end
end has_sum
namespace has_fpower_series_at
lemma has_fpower_series_dslope_fslope (hp : has_fpower_series_at f p z₀) :
has_fpower_series_at (dslope f z₀) p.fslope z₀ :=
begin
have hpd : deriv f z₀ = p.coeff 1 := hp.deriv,
have hp0 : p.coeff 0 = f z₀ := hp.coeff_zero 1,
simp only [has_fpower_series_at_iff, apply_eq_pow_smul_coeff, coeff_fslope] at hp ⊢,
refine hp.mono (λ x hx, _),
by_cases h : x = 0,
{ convert has_sum_single 0 _; intros; simp [*] },
{ have hxx : ∀ (n : ℕ), x⁻¹ * x ^ (n + 1) = x ^ n := λ n, by field_simp [h, pow_succ'],
suffices : has_sum (λ n, x⁻¹ • x ^ (n + 1) • p.coeff (n + 1)) (x⁻¹ • (f (z₀ + x) - f z₀)),
{ simpa [dslope, slope, h, smul_smul, hxx] using this },
{ simpa [hp0] using ((has_sum_nat_add_iff' 1).mpr hx).const_smul } }
end
lemma has_fpower_series_iterate_dslope_fslope (n : ℕ) (hp : has_fpower_series_at f p z₀) :
has_fpower_series_at ((swap dslope z₀)^[n] f) (fslope^[n] p) z₀ :=
begin
induction n with n ih generalizing f p,
{ exact hp },
{ simpa using ih (has_fpower_series_dslope_fslope hp) }
end
lemma iterate_dslope_fslope_ne_zero (hp : has_fpower_series_at f p z₀) (h : p ≠ 0) :
(swap dslope z₀)^[p.order] f z₀ ≠ 0 :=
begin
rw [← coeff_zero (has_fpower_series_iterate_dslope_fslope p.order hp) 1],
simpa [coeff_eq_zero] using apply_order_ne_zero h
end
lemma eq_pow_order_mul_iterate_dslope (hp : has_fpower_series_at f p z₀) :
∀ᶠ z in 𝓝 z₀, f z = (z - z₀) ^ p.order • ((swap dslope z₀)^[p.order] f z) :=
begin
have hq := has_fpower_series_at_iff'.mp (has_fpower_series_iterate_dslope_fslope p.order hp),
filter_upwards [hq, has_fpower_series_at_iff'.mp hp] with x hx1 hx2,
have : ∀ k < p.order, p.coeff k = 0,
from λ k hk, by simpa [coeff_eq_zero] using apply_eq_zero_of_lt_order hk,
obtain ⟨s, hs1, hs2⟩ := has_sum.exists_has_sum_smul_of_apply_eq_zero hx2 this,
convert hs1.symm,
simp only [coeff_iterate_fslope] at hx1,
exact hx1.unique hs2
end
lemma locally_ne_zero (hp : has_fpower_series_at f p z₀) (h : p ≠ 0) :
∀ᶠ z in 𝓝[≠] z₀, f z ≠ 0 :=
begin
rw [eventually_nhds_within_iff],
have h2 := (has_fpower_series_iterate_dslope_fslope p.order hp).continuous_at,
have h3 := h2.eventually_ne (iterate_dslope_fslope_ne_zero hp h),
filter_upwards [eq_pow_order_mul_iterate_dslope hp, h3] with z e1 e2 e3,
simpa [e1, e2, e3] using pow_ne_zero p.order (sub_ne_zero.mpr e3),
end
lemma locally_zero_iff (hp : has_fpower_series_at f p z₀) :
(∀ᶠ z in 𝓝 z₀, f z = 0) ↔ p = 0 :=
⟨λ hf, hp.eq_zero_of_eventually hf, λ h, eventually_eq_zero (by rwa h at hp)⟩
end has_fpower_series_at
namespace analytic_at
/-- The *principle of isolated zeros* for an analytic function, local version: if a function is
analytic at `z₀`, then either it is identically zero in a neighborhood of `z₀`, or it does not
vanish in a punctured neighborhood of `z₀`. -/
theorem eventually_eq_zero_or_eventually_ne_zero (hf : analytic_at 𝕜 f z₀) :
(∀ᶠ z in 𝓝 z₀, f z = 0) ∨ (∀ᶠ z in 𝓝[≠] z₀, f z ≠ 0) :=
begin
rcases hf with ⟨p, hp⟩,
by_cases h : p = 0,
{ exact or.inl (has_fpower_series_at.eventually_eq_zero (by rwa h at hp)) },
{ exact or.inr (hp.locally_ne_zero h) }
end
lemma eventually_eq_or_eventually_ne (hf : analytic_at 𝕜 f z₀) (hg : analytic_at 𝕜 g z₀) :
(∀ᶠ z in 𝓝 z₀, f z = g z) ∨ (∀ᶠ z in 𝓝[≠] z₀, f z ≠ g z) :=
by simpa [sub_eq_zero] using (hf.sub hg).eventually_eq_zero_or_eventually_ne_zero
lemma frequently_zero_iff_eventually_zero {f : 𝕜 → E} {w : 𝕜} (hf : analytic_at 𝕜 f w) :
(∃ᶠ z in 𝓝[≠] w, f z = 0) ↔ (∀ᶠ z in 𝓝 w, f z = 0) :=
⟨hf.eventually_eq_zero_or_eventually_ne_zero.resolve_right,
λ h, (h.filter_mono nhds_within_le_nhds).frequently⟩
lemma frequently_eq_iff_eventually_eq (hf : analytic_at 𝕜 f z₀) (hg : analytic_at 𝕜 g z₀) :
(∃ᶠ z in 𝓝[≠] z₀, f z = g z) ↔ (∀ᶠ z in 𝓝 z₀, f z = g z) :=
by simpa [sub_eq_zero] using frequently_zero_iff_eventually_zero (hf.sub hg)
end analytic_at
namespace analytic_on
variables {U : set 𝕜}
/-- The *principle of isolated zeros* for an analytic function, global version: if a function is
analytic on a connected set `U` and vanishes in arbitrary neighborhoods of a point `z₀ ∈ U`, then
it is identically zero in `U`.
For higher-dimensional versions requiring that the function vanishes in a neighborhood of `z₀`,
see `eq_on_zero_of_preconnected_of_eventually_eq_zero`. -/
theorem eq_on_zero_of_preconnected_of_frequently_eq_zero
(hf : analytic_on 𝕜 f U) (hU : is_preconnected U)
(h₀ : z₀ ∈ U) (hfw : ∃ᶠ z in 𝓝[≠] z₀, f z = 0) :
eq_on f 0 U :=
hf.eq_on_zero_of_preconnected_of_eventually_eq_zero hU h₀
((hf z₀ h₀).frequently_zero_iff_eventually_zero.1 hfw)
theorem eq_on_zero_of_preconnected_of_mem_closure (hf : analytic_on 𝕜 f U) (hU : is_preconnected U)
(h₀ : z₀ ∈ U) (hfz₀ : z₀ ∈ closure ({z | f z = 0} \ {z₀})) :
eq_on f 0 U :=
hf.eq_on_zero_of_preconnected_of_frequently_eq_zero hU h₀
(mem_closure_ne_iff_frequently_within.mp hfz₀)
/-- The *identity principle* for analytic functions, global version: if two functions are
analytic on a connected set `U` and coincide at points which accumulate to a point `z₀ ∈ U`, then
they coincide globally in `U`.
For higher-dimensional versions requiring that the functions coincide in a neighborhood of `z₀`,
see `eq_on_of_preconnected_of_eventually_eq`. -/
theorem eq_on_of_preconnected_of_frequently_eq (hf : analytic_on 𝕜 f U) (hg : analytic_on 𝕜 g U)
(hU : is_preconnected U) (h₀ : z₀ ∈ U) (hfg : ∃ᶠ z in 𝓝[≠] z₀, f z = g z) :
eq_on f g U :=
begin
have hfg' : ∃ᶠ z in 𝓝[≠] z₀, (f - g) z = 0 := hfg.mono (λ z h, by rw [pi.sub_apply, h, sub_self]),
simpa [sub_eq_zero] using
λ z hz, (hf.sub hg).eq_on_zero_of_preconnected_of_frequently_eq_zero hU h₀ hfg' hz
end
theorem eq_on_of_preconnected_of_mem_closure (hf : analytic_on 𝕜 f U) (hg : analytic_on 𝕜 g U)
(hU : is_preconnected U) (h₀ : z₀ ∈ U) (hfg : z₀ ∈ closure ({z | f z = g z} \ {z₀})) :
eq_on f g U :=
hf.eq_on_of_preconnected_of_frequently_eq hg hU h₀ (mem_closure_ne_iff_frequently_within.mp hfg)
end analytic_on
|
8cd891261fb5a77547ebdf77d387cc1ae0ed0f0b | 29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f | /Exercises 9/32_lecture.lean | 8e24e641571c559f6a31c30b21005cf9b59b9178 | [] | 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 | 7,102 | lean | /- Lecture 3.2: Program Semantics — Hoare Logic -/
-- loads big-step semantics `(p, s) ⟹ t` over `state` as state space
import .x32_library
namespace lecture
open program
variables
{c : state → Prop} {f : state → ℕ} {n : string}
{p p₀ p₁ p₂ : program} {s s₀ s₁ s₂ t u : state}
{P P' P₁ P₂ P₃ Q Q' : state → Prop}
/- Hoare triples `{* P *} p {* Q *}` for partial correctness -/
def partial_hoare (P : state → Prop) (p : program) (Q : state → Prop) : Prop :=
∀s t, P s → (p, s) ⟹ t → Q t
notation `{* ` P : 1 ` *} ` p : 1 ` {* ` Q : 1 ` *}` := partial_hoare P p Q
/- Introduction rules for Hoare triples -/
namespace partial_hoare
lemma skip_intro :
{* P *} skip {* P *} :=
begin
intros s t hs hst,
cases hst,
assumption
end
lemma assign_intro (P : state → Prop) :
{* λs, P (s.update n (f s)) *} assign n f {* P *} :=
begin
intros s t P hst,
cases hst,
assumption
end
lemma seq_intro (h₁ : {* P₁ *} p₁ {* P₂ *}) (h₂ : {* P₂ *} p₂ {* P₃ *}) :
{* P₁ *} p₁ ;; p₂ {* P₃ *} :=
begin
intros s t P hst,
cases hst,
apply h₂ _ _ _ hst_h₂,
apply h₁ _ _ _ hst_h₁,
assumption
end
lemma ite_intro (h₁ : {* λs, P s ∧ c s *} p₁ {* Q *}) (h₂ : {* λs, P s ∧ ¬ c s *} p₂ {* Q *}) :
{* P *} ite c p₁ p₂ {* Q *} :=
begin
intros s t hs hst,
cases hst,
{ apply h₁ _ _ _ hst_h,
exact ⟨hs, hst_hs⟩ },
{ apply h₂ _ _ _ hst_h,
exact ⟨hs, hst_hs⟩ },
end
lemma while_intro (P : state → Prop) (h₁ : {* λs, P s ∧ c s *} p {* P *}) :
{* P *} while c p {* λs, P s ∧ ¬ c s *} :=
begin
intros s t hs,
generalize eq : (while c p, s) = ps,
intro hst,
induction hst generalizing s; cases eq,
{ apply hst_ih_hw hst_t _ rfl,
exact h₁ _ _ ⟨hs, hst_hs⟩ hst_hp },
{ exact ⟨hs, hst_hs⟩ }
end
lemma consequence (h : {* P *} p {* Q *}) (hp : ∀s, P' s → P s) (hq : ∀s, Q s → Q' s) :
{* P' *} p {* Q' *} :=
assume s t hs hst, hq _ $ h s t (hp s hs) hst
lemma consequence_left (P' : state → Prop) (h : {* P *} p {* Q *}) (hp : ∀s, P' s → P s) :
{* P' *} p {* Q *} :=
consequence h hp (assume s hs, hs)
lemma consequence_right (Q : state → Prop) (h : {* P *} p {* Q *}) (hq : ∀s, Q s → Q' s) :
{* P *} p {* Q' *} :=
consequence h (assume s hs, hs) hq
/- Many of the above rules are nonlinear (i.e. their conclusions contain repeated variables). This
makes them inconvenient to apply. We combine some of the previous rules with `consequence` to derive
linear rules. -/
lemma skip_intro' (h : ∀s, P s → Q s):
{* P *} skip {* Q *} :=
consequence skip_intro h (assume s hs, hs)
lemma assign_intro' (h : ∀s, P s → Q (s.update n (f s))):
{* P *} assign n f {* Q *} :=
consequence (assign_intro Q) h (assume s hs, hs)
lemma seq_intro' (h₂ : {* P₂ *} p₂ {* P₃ *}) (h₁ : {* P₁ *} p₁ {* P₂ *}) :
{* P₁ *} p₁ ;; p₂ {* P₃ *} :=
seq_intro h₁ h₂
lemma while_intro_inv (I : state → Prop)
(h₁ : {* λs, I s ∧ c s *} p {* I *}) (hp : ∀s, P s → I s) (hq : ∀s, ¬ c s → I s → Q s) :
{* P *} while c p {* Q *} :=
consequence (while_intro I h₁) hp (assume s ⟨hs, hnc⟩, hq s hnc hs)
end partial_hoare
/- Example: `SWAP`
Exchanges the values of variables `a` and `b`. -/
section SWAP
open partial_hoare
def SWAP : program :=
assign "t" (λs, s "a") ;;
assign "a" (λs, s "b") ;;
assign "b" (λs, s "t")
lemma SWAP_correct (x y : ℕ) :
{* λs, s "a" = x ∧ s "b" = y *} SWAP {* λs, s "a" = y ∧ s "b" = x *} :=
begin
apply seq_intro',
apply seq_intro',
apply assign_intro,
apply assign_intro,
apply assign_intro',
/- The remaining goal looks horrible. But `simp` can simplify it dramatically, and with contextual
rewriting (i.e. using assumptions in the goal as rewrite rules), it can solve it. -/
simp {contextual := tt},
end
end SWAP
/- Example: `ADD`
Computes `m + n`, leaving the result in `n`, using only these primitive operations: `n + 1`,
`n - 1`, and `n ≠ 0`. -/
section ADD
open partial_hoare
def ADD : program :=
while (λs, s "n" ≠ 0)
( assign "n" (λs, s "n" - 1) ;;
assign "m" (λs, s "m" + 1) )
lemma ADD_correct (n m : ℕ) :
{* λs, s "n" = n ∧ s "m" = m *} ADD {* λs, s "m" = n + m *} :=
begin
-- `refine` is like `exact`, but it lets us specify holes to be filled later
refine while_intro_inv (λs, s "n" + s "m" = n + m) _ _ _,
apply seq_intro',
apply assign_intro,
apply assign_intro',
{ simp,
-- puhh this looks much better: `simp` removed all `update`s
intros s hnm hn0,
rw ←hnm,
-- subtracting on `ℕ` is annoying
cases s "n",
{ contradiction },
{ simp [nat.succ_eq_add_one] } },
{ simp {contextual := tt} },
{ simp [not_not_iff] {contextual := tt} }
end
end ADD
/- Annotated while loop -/
def program.while_inv (I : state → Prop) (c : state → Prop) (p : program) : program :=
while c p
open program -- makes `program.while_inv` available as `while_inv`
namespace partial_hoare
/- `while_inv` rules use the invariant annotation -/
lemma while_inv_intro {I : state → Prop}
(h₁ : {* λs, I s ∧ c s *} p {* I *}) (hq : ∀s, ¬ c s → I s → Q s) :
{* I *} while_inv I c p {* Q *} :=
while_intro_inv I h₁ (assume s hs, hs) hq
lemma while_inv_intro' {I : state → Prop}
(h₁ : {* λs, I s ∧ c s *} p {* I *}) (hp : ∀s, P s → I s) (hq : ∀s, ¬ c s → I s → Q s) :
{* P *} while_inv I c p {* Q *} :=
while_intro_inv I h₁ hp hq
end partial_hoare
end lecture
namespace tactic.interactive
open lecture.partial_hoare lecture tactic
meta def is_meta {elab : bool} : expr elab → bool
| (expr.mvar _ _ _) := tt
| _ := ff
/- Verification condition generator -/
meta def vcg : tactic unit := do
t ← target,
match t with
| `({* %%P *} %%p {* _ *}) :=
match p with
| `(program.skip) := applyc (if is_meta P then ``skip_intro else ``skip_intro')
| `(program.assign _ _) := applyc (if is_meta P then ``assign_intro else ``assign_intro')
| `(program.ite _ _ _) := do applyc ``ite_intro; vcg
| `(program.seq _ _) := do applyc ``seq_intro'; vcg
| `(program.while_inv _ _ _) :=
do applyc (if is_meta P then ``while_inv_intro else ``while_inv_intro'); vcg
| _ := fail (to_fmt "cannot analyze " ++ to_fmt p)
end
| _ := skip -- do nothing if the goal is not a Hoare triple
end
end tactic.interactive
namespace lecture
open program
example (n m : ℕ) :
{* λs, s "n" = n ∧ s "m" = m *} ADD {* λs, s "n" = 0 ∧ s "m" = n + m *} :=
begin
-- use `show` to annotate the while loop with an invariant
show {* λs, s "n" = n ∧ s "m" = m *}
while_inv (λs, s "n" + s "m" = n + m) (λs, s "n" ≠ 0)
( assign "n" (λs, s "n" - 1) ;;
assign "m" (λs, s "m" + 1) )
{* λs, s "n" = 0 ∧ s "m" = n + m *},
vcg;
simp {contextual := tt},
intros s hnm hn,
rw ←hnm,
cases s "n",
{ contradiction },
{ simp [nat.succ_eq_add_one] }
end
end lecture
|
dee9f2fa5dc2af9ecf033e263b4df8403dc038a2 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/filter/ultrafilter.lean | 7e24c08f75ecfe20a69240596b51a08b76468470 | [
"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 | 12,497 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov
-/
import order.filter.cofinite
/-!
# Ultrafilters
An ultrafilter is a minimal (maximal in the set order) proper filter.
In this file we define
* `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter;
* `ultrafilter`: subtype of ultrafilters;
* `ultrafilter.pure`: `pure x` as an `ultrafiler`;
* `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters;
* `hyperfilter`: the ultrafilter extending the cofinite filter.
-/
universes u v
variables {α : Type u} {β : Type v}
open set zorn filter function
open_locale classical filter
/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/
@[protect_proj]
structure ultrafilter (α : Type*) extends filter α :=
(ne_bot' : ne_bot to_filter)
(le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g)
namespace ultrafilter
variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop}
instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩
instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩
lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f)
(hne : ne_bot g . tactic.apply_instance) : g = f :=
le_antisymm h $ f.le_of_le g hne h
instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot'
@[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl
lemma coe_injective : injective (coe : ultrafilter α → filter α)
| ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr
@[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g :=
⟨λ h, coe_injective $ g.unique h, λ h, h ▸ le_rfl⟩
@[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff
@[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g :=
coe_injective $ filter.ext h
lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g :=
le_of_inf_eq (f.unique inf_le_left hg)
lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g :=
f.le_of_inf_ne_bot $ by rwa inf_comm
@[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f :=
⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot
⟨λ h, hsc $ mem_sets_of_eq_bot $ by rwa compl_compl⟩, compl_not_mem_sets⟩
@[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x :=
compl_not_mem_iff
alias frequently_iff_eventually ↔ filter.frequently.eventually _
lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl]
lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f :=
inter_mem_sets_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem
/-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by
`ultrafilter.compl_not_mem_iff`. -/
def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α :=
{ to_filter := f,
ne_bot' := ⟨λ hf, by simpa [hf] using h⟩,
le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem_sets hs (hgf hsc) }
lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem_sets hs
lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty
@[simp] lemma empty_not_mem : ∅ ∉ f := empty_nmem_sets f
lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f :=
or_iff_not_imp_left.2 compl_mem_iff_not_mem.2
protected lemma em (f : ultrafilter α) (p : α → Prop) :
(∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x :=
f.mem_or_compl_mem {x | p x}
lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x :=
⟨λ H, (f.em p).imp_right $ λ hp, (H.and hp).mono $ λ x ⟨hx, hnx⟩, hx.resolve_left hnx,
λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩
lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := eventually_or
lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem
lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x :=
by simp only [imp_iff_not_or, eventually_or, eventually_not]
lemma finite_sUnion_mem_iff {s : set (set α)} (hs : finite s) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f :=
finite.induction_on hs (by simp) $ λ a s ha hs his,
by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib]
lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : finite is) :
(⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f :=
by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff]
/-- Pushforward for ultrafilters. -/
def map (m : α → β) (f : ultrafilter α) : ultrafilter β :=
of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s)
@[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) :
(map m f : filter β) = filter.map m ↑f := rfl
@[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} :
s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl
/-- The pullback of an ultrafilter along an injection whose range is large with respect to the given
ultrafilter. -/
def comap {m : α → β} (u : ultrafilter β) (inj : injective m)
(large : set.range m ∈ u) : ultrafilter α :=
{ to_filter := comap m u,
ne_bot' := u.ne_bot'.comap_of_range_mem large,
le_of_le := λ g hg hgu, by { resetI,
simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } }
/-- The principal ultrafilter associated to a point `x`. -/
instance : has_pure ultrafilter :=
⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩
@[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl
instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure (default _)⟩
/-- Monadic bind for ultrafilters, coming from the one on filters
defined in terms of map and join.-/
def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β :=
of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s,
by simp only [mem_bind_sets', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl]
instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩
instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map }
instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map }
section
local attribute [instance] filter.monad filter.is_lawful_monad
instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter :=
{ id_map := assume α f, coe_injective (id_map f.1),
pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)),
bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl),
bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) }
end
/-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/
lemma exists_le (f : filter α) [h : ne_bot f] : ∃u : ultrafilter α, ↑u ≤ f :=
begin
let τ := {f' // ne_bot f' ∧ f' ≤ f},
let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
haveI := nonempty_of_ne_bot f,
let top : τ := ⟨f, h, le_refl f⟩,
let sup : Π(c:set τ), chain r c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1,
infi_ne_bot_of_directed
(directed_of_chain $ chain_insert hc $ λ ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩,
have : ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have : (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩)
(assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
cases this with uτ hmin,
exact ⟨⟨uτ.val, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩, uτ.property.right⟩
end
alias exists_le ← filter.exists_ultrafilter_le
/-- Construct an ultrafilter extending a given filter.
The ultrafilter lemma is the assertion that such a filter exists;
we use the axiom of choice to pick one. -/
noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α :=
classical.some (exists_le f)
lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f)
lemma of_coe (f : ultrafilter α) : of ↑f = f :=
coe_inj.1 $ f.unique (of_le f)
lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α))
(cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) :
∃ F : ultrafilter α, S ⊆ F.sets :=
begin
suffices : ∃ F : filter α, ne_bot F ∧ S ⊆ F.sets,
{ rcases this with ⟨F, cond, hF⟩,
resetI,
obtain ⟨G : ultrafilter α, h1 : ↑G ≤ F⟩ := exists_le F,
exact ⟨G, λ T hT, h1 (hF hT)⟩ },
use filter.generate S,
refine ⟨_, λ T hT, filter.generate_sets.basic hT⟩,
rw ← forall_sets_nonempty_iff_ne_bot,
intros T hT,
rcases mem_generate_iff.mp hT with ⟨A, h1, h2, h3⟩,
let B := set.finite.to_finset h2,
rw (show A = ↑B, by simp) at *,
rcases cond B h1 with ⟨x, hx⟩,
exact ⟨x, h3 hx⟩,
end
end ultrafilter
namespace filter
open ultrafilter
lemma mem_iff_ultrafilter {s : set α} {f : filter α} :
s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g :=
begin
refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩,
set g : filter ↥sᶜ := comap coe f,
haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]),
simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g))
end
lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ :=
⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩
/-- A filter equals the intersection of all the ultrafilters which contain it. -/
lemma supr_ultrafilter_le_eq (f : filter α) :
(⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f :=
eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter]
/-- The `tendsto` relation can be checked on ultrafilters. -/
lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) :
tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ :=
by simpa only [tendsto_iff_comap] using le_iff_ultrafilter
lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f :=
⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩
lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) :
(∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f :=
begin
refine ⟨λ H f hf, H f f.ne_bot hf, _⟩,
introsI H f hf hfg,
exact hp (of_le f) (H _ ((of_le f).trans hfg))
end
section hyperfilter
variables (α) [infinite α]
/-- The ultrafilter extending the cofinite filter. -/
noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite
variable {α}
lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α :=
ultrafilter.of_le cofinite
@[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α :=
(by apply_instance : ne_bot ↑(hyperfilter α)).1.symm
theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α :=
λ hy, compl_not_mem_sets hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite
alias nmem_hyperfilter_of_finite ← set.finite.nmem_hyperfilter
theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) :
sᶜ ∈ hyperfilter α :=
compl_mem_iff_not_mem.2 hf.nmem_hyperfilter
alias compl_mem_hyperfilter_of_finite ← set.finite.compl_mem_hyperfilter
theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) :
s ∈ hyperfilter α :=
compl_compl s ▸ hf.compl_mem_hyperfilter
end hyperfilter
end filter
|
d70e5848f87353417848cbf904317a03b3177ad9 | c3328a282670ccadc2fdd248fa47ae671c984663 | /test/example.lean | 69781de1ec6e5e32041e98e03cce6578e7dcb5d1 | [
"Apache-2.0"
] | permissive | uwplse/leanup | ff481a7d4c0ffcde90927e5352881ca00588aab4 | c1c5b5b63b15de5503c8f70b95b88195d0f03de2 | refs/heads/master | 1,625,620,725,807 | 1,506,983,190,000 | 1,506,983,190,000 | 104,115,036 | 0 | 2 | null | 1,506,983,191,000 | 1,505,847,108,000 | Python | UTF-8 | Lean | false | false | 52 | lean | -- This should have some green squiggles
#check nat
|
15bda6fb4469c9ee2f3861b8e2884497d06b1999 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/mixed_tmp_non_tmp_universe_bug.lean | d21f0ea9868cee3fb4266a3153dfc23742c1a9bb | [
"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 | 79 | lean | eval default (bool × unit × nat)
eval default (bool × bool × bool × bool)
|
f7a5f9554ae0462cc2e44e9b667bef3abebe946e | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/init/tactic.lean | 739731e0e7e50a2626efeb3fa04b3a2403aebeb5 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,696 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.tactic
Author: Leonardo de Moura
This is just a trick to embed the 'tactic language' as a Lean
expression. We should view 'tactic' as automation that when execute
produces a term. tactic.builtin is just a "dummy" for creating the
definitions that are actually implemented in C++
-/
prelude
import init.datatypes init.reserved_notation
inductive tactic :
Type := builtin : tactic
namespace tactic
-- Remark the following names are not arbitrary, the tactic module
-- uses them when converting Lean expressions into actual tactic objects.
-- The bultin 'by' construct triggers the process of converting a
-- a term of type 'tactic' into a tactic that sythesizes a term
opaque definition and_then (t1 t2 : tactic) : tactic := builtin
opaque definition or_else (t1 t2 : tactic) : tactic := builtin
opaque definition append (t1 t2 : tactic) : tactic := builtin
opaque definition interleave (t1 t2 : tactic) : tactic := builtin
opaque definition par (t1 t2 : tactic) : tactic := builtin
opaque definition fixpoint (f : tactic → tactic) : tactic := builtin
opaque definition repeat (t : tactic) : tactic := builtin
opaque definition at_most (t : tactic) (k : num) : tactic := builtin
opaque definition discard (t : tactic) (k : num) : tactic := builtin
opaque definition focus_at (t : tactic) (i : num) : tactic := builtin
opaque definition try_for (t : tactic) (ms : num) : tactic := builtin
opaque definition now : tactic := builtin
opaque definition assumption : tactic := builtin
opaque definition eassumption : tactic := builtin
opaque definition state : tactic := builtin
opaque definition fail : tactic := builtin
opaque definition id : tactic := builtin
opaque definition beta : tactic := builtin
opaque definition info : tactic := builtin
opaque definition whnf : tactic := builtin
opaque definition rotate_left (k : num) := builtin
opaque definition rotate_right (k : num) := builtin
definition rotate (k : num) := rotate_left k
-- This is just a trick to embed expressions into tactics.
-- The nested expressions are "raw". They tactic should
-- elaborate them when it is executed.
inductive expr : Type :=
builtin : expr
opaque definition apply (e : expr) : tactic := builtin
opaque definition rapply (e : expr) : tactic := builtin
opaque definition fapply (e : expr) : tactic := builtin
opaque definition rename (a b : expr) : tactic := builtin
opaque definition intro (e : expr) : tactic := builtin
opaque definition generalize (e : expr) : tactic := builtin
opaque definition clear (e : expr) : tactic := builtin
opaque definition revert (e : expr) : tactic := builtin
opaque definition unfold (e : expr) : tactic := builtin
opaque definition exact (e : expr) : tactic := builtin
opaque definition trace (s : string) : tactic := builtin
opaque definition inversion (id : expr) : tactic := builtin
notation a `↦` b:max := rename a b
inductive expr_list : Type :=
nil : expr_list,
cons : expr → expr_list → expr_list
opaque definition inversion_with (id : expr) (ids : expr_list) : tactic := builtin
notation `cases` a:max := inversion a
notation `cases` a:max `with` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := inversion_with a l
opaque definition intro_lst (ids : expr_list) : tactic := builtin
notation `intros` := intro_lst expr_list.nil
notation `intros` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := intro_lst l
opaque definition generalize_lst (es : expr_list) : tactic := builtin
notation `generalizes` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := generalize_lst l
opaque definition clear_lst (ids : expr_list) : tactic := builtin
notation `clears` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := clear_lst l
opaque definition revert_lst (ids : expr_list) : tactic := builtin
notation `reverts` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := revert_lst l
opaque definition assert_hypothesis (id : expr) (e : expr) : tactic := builtin
notation `assert` `(` id `:` ty `)` := assert_hypothesis id ty
infixl `;`:15 := and_then
notation `[` h:10 `|`:10 r:(foldl:10 `|` (e r, or_else r e) h) `]` := r
definition try (t : tactic) : tactic := [t | id]
definition repeat1 (t : tactic) : tactic := t ; repeat t
definition focus (t : tactic) : tactic := focus_at t 0
definition determ (t : tactic) : tactic := at_most t 1
end tactic
|
1b7bedb797fc7ff477dd163a10486326b99a5ef7 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /archive/imo/imo1981_q3.lean | 1560499391ba114cd375a7a3d16a725fe7d6237a | [
"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 | 6,807 | lean | /-
Copyright (c) 2020 Kevin Lacker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker
-/
import data.nat.fib
import tactic.linarith
/-!
# IMO 1981 Q3
Determine the maximum value of `m ^ 2 + n ^ 2`, where `m` and `n` are integers in
`{1, 2, ..., 1981}` and `(n ^ 2 - m * n - m ^ 2) ^ 2 = 1`.
The trick to this problem is that `m` and `n` have to be consecutive Fibonacci numbers,
because you can reduce any solution to a smaller one using the Fibonacci recurrence.
-/
/-
First, define the problem in terms of finding the maximum of a set.
We first generalize the problem to `{1, 2, ..., N}` and specialize to `N = 1981` at the very end.
-/
open int nat set
section
variable (N : ℕ) -- N = 1981
@[mk_iff] structure problem_predicate (m n : ℤ) : Prop :=
(m_range : m ∈ Ioc 0 (N : ℤ))
(n_range : n ∈ Ioc 0 (N : ℤ))
(eq_one : (n ^ 2 - m * n - m ^ 2) ^ 2 = 1)
def specified_set : set ℤ :=
{k : ℤ | ∃ m : ℤ, ∃ n : ℤ, k = m ^ 2 + n ^ 2 ∧ problem_predicate N m n}
/-
We want to reduce every solution to a smaller solution. Specifically,
we show that when `(m, n)` is a solution, `(n - m, m)` is also a solution,
except for the base case of `(1, 1)`.
-/
namespace problem_predicate
variable {N}
lemma m_le_n {m n : ℤ} (h1 : problem_predicate N m n) : m ≤ n :=
begin
by_contradiction h2,
have h3 : 1 = (n * (n - m) - m ^ 2) ^ 2,
{ calc 1 = (n ^ 2 - m * n - m ^ 2) ^ 2 : h1.eq_one.symm
... = (n * (n - m) - m ^ 2) ^ 2 : by ring },
have h4 : n * (n - m) - m ^ 2 < -1, by nlinarith [h1.n_range.left],
have h5 : 1 < (n * (n - m) - m ^ 2) ^ 2, by nlinarith,
exact h5.ne h3
end
lemma eq_imp_1 {n : ℤ} (h1 : problem_predicate N n n) : n = 1 :=
begin
have : n * (n * (n * n)) = 1,
{ calc _ = (n ^ 2 - n * n - n ^ 2) ^ 2 : by simp [sq, mul_assoc]
... = 1 : h1.eq_one },
exact eq_one_of_mul_eq_one_right h1.m_range.left.le this,
end
lemma reduction {m n : ℤ} (h1 : problem_predicate N m n) (h2 : 1 < n) :
problem_predicate N (n - m) m :=
begin
obtain (rfl : m = n) | (h3 : m < n) := h1.m_le_n.eq_or_lt,
{ have h4 : m = 1, from h1.eq_imp_1,
exact absurd h4.symm h2.ne },
refine_struct { n_range := h1.m_range, .. },
-- m_range:
{ have h5 : 0 < n - m, from sub_pos.mpr h3,
have h6 : n - m < N,
{ calc _ < n : sub_lt_self n h1.m_range.left
... ≤ N : h1.n_range.right },
exact ⟨h5, h6.le⟩ },
-- eq_one:
{ calc _ = (n ^ 2 - m * n - m ^ 2) ^ 2 : by ring
... = 1 : h1.eq_one },
end
end problem_predicate
/-
It will be convenient to have the lemmas above in their natural number form.
Most of these can be proved with the `norm_cast` family of tactics.
-/
def nat_predicate (m n : ℕ) : Prop := problem_predicate N ↑m ↑n
namespace nat_predicate
variable {N}
lemma m_le_n {m n : ℕ} (h1 : nat_predicate N m n) : m ≤ n :=
by exact_mod_cast h1.m_le_n
lemma eq_imp_1 {n : ℕ} (h1 : nat_predicate N n n) : n = 1 :=
by exact_mod_cast h1.eq_imp_1
lemma reduction {m n : ℕ} (h1 : nat_predicate N m n) (h2 : 1 < n) :
nat_predicate N (n - m) m :=
have m ≤ n, from h1.m_le_n,
by exact_mod_cast h1.reduction (by exact_mod_cast h2)
lemma n_pos {m n : ℕ} (h1 : nat_predicate N m n) : 0 < n :=
by exact_mod_cast h1.n_range.left
lemma m_pos {m n : ℕ} (h1 : nat_predicate N m n) : 0 < m :=
by exact_mod_cast h1.m_range.left
lemma n_le_N {m n : ℕ} (h1 : nat_predicate N m n) : n ≤ N :=
by exact_mod_cast h1.n_range.right
/-
Now we can use induction to show that solutions must be Fibonacci numbers.
-/
lemma imp_fib {n : ℕ} : ∀ m : ℕ, nat_predicate N m n →
∃ k : ℕ, m = fib k ∧ n = fib (k + 1) :=
begin
apply nat.strong_induction_on n _,
intros n h1 m h2,
have h3 : m ≤ n, from h2.m_le_n,
obtain (rfl : 1 = n) | (h4 : 1 < n) := (succ_le_iff.mpr h2.n_pos).eq_or_lt,
{ use 1,
have h5 : 1 ≤ m, from succ_le_iff.mpr h2.m_pos,
simpa [fib_one, fib_two] using (h3.antisymm h5 : m = 1) },
{ obtain (rfl : m = n) | (h6 : m < n) := h3.eq_or_lt,
{ exact absurd h2.eq_imp_1 (ne_of_gt h4) },
{ have h7 : nat_predicate N (n - m) m, from h2.reduction h4,
obtain ⟨k : ℕ, hnm : n - m = fib k, rfl : m = fib (k+1)⟩ := h1 m h6 (n - m) h7,
use [k + 1, rfl],
rw [fib_succ_succ, ← hnm, tsub_add_cancel_of_le h3] } }
end
end nat_predicate
/-
Next, we prove that if `N < fib K + fib (K+1)`, then the largest `m` and `n`
satisfying `nat_predicate m n N` are `fib K` and `fib (K+1)`, respectively.
-/
variables {K : ℕ} (HK : N < fib K + fib (K+1)) {N}
include HK
lemma m_n_bounds {m n : ℕ} (h1 : nat_predicate N m n) : m ≤ fib K ∧ n ≤ fib (K+1) :=
begin
obtain ⟨k : ℕ, hm : m = fib k, hn : n = fib (k+1)⟩ := h1.imp_fib m,
by_cases h2 : k < K + 1,
{ have h3 : k ≤ K, from lt_succ_iff.mp h2,
split,
{ calc m = fib k : hm
... ≤ fib K : fib_mono h3, },
{ have h6 : k + 1 ≤ K + 1, from succ_le_succ h3,
calc n = fib (k+1) : hn
... ≤ fib (K+1) : fib_mono h6 } },
{ have h7 : N < n,
{ have h8 : K + 2 ≤ k + 1, from succ_le_succ (not_lt.mp h2),
calc N < fib (K+2) : HK
... ≤ fib (k+1) : fib_mono h8
... = n : hn.symm, },
have h9 : n ≤ N, from h1.n_le_N,
exact absurd h7 h9.not_lt }
end
/-
We spell out the consequences of this result for `specified_set N` here.
-/
variables {M : ℕ} (HM : M = (fib K) ^ 2 + (fib (K+1)) ^ 2)
include HM
lemma k_bound {m n : ℤ} (h1 : problem_predicate N m n) : m ^ 2 + n ^ 2 ≤ M :=
begin
have h2 : 0 ≤ m, from h1.m_range.left.le,
have h3 : 0 ≤ n, from h1.n_range.left.le,
rw [← nat_abs_of_nonneg h2, ← nat_abs_of_nonneg h3] at h1, clear h2 h3,
obtain ⟨h4 : m.nat_abs ≤ fib K, h5 : n.nat_abs ≤ fib (K+1)⟩ := m_n_bounds HK h1,
have h6 : m ^ 2 ≤ (fib K) ^ 2, from nat_abs_le_iff_sq_le.mp h4,
have h7 : n ^ 2 ≤ (fib (K+1)) ^ 2, from nat_abs_le_iff_sq_le.mp h5,
linarith
end
lemma solution_bound : ∀ {k : ℤ}, k ∈ specified_set N → k ≤ M
| _ ⟨_, _, rfl, h⟩ := k_bound HK HM h
theorem solution_greatest (H : problem_predicate N (fib K) (fib (K + 1))) :
is_greatest (specified_set N) M :=
⟨⟨fib K, fib (K+1), by simp [HM], H⟩, λ k h, solution_bound HK HM h⟩
end
/-
Now we just have to demonstrate that 987 and 1597 are in fact the largest Fibonacci
numbers in this range, and thus provide the maximum of `specified_set`.
-/
theorem imo1981_q3 : is_greatest (specified_set 1981) 3524578 :=
begin
have := λ h, @solution_greatest 1981 16 h 3524578,
simp only [show fib (16:ℕ) = 987 ∧ fib (16+1:ℕ) = 1597,
by norm_num [fib_succ_succ]] at this,
apply_mod_cast this; norm_num [problem_predicate_iff],
end
|
032d67ab0554041d589a276d1f8edd71fbb00cf8 | 13133fade54057ee588bc056e4eaa14a24773d23 | /Proofs/even_double_factorial_greater_than_zero.lean | 1f6c47238569068c472af07063e48d967778f8bc | [] | no_license | lkloh/lean-project-15815 | 444cbdca1d1a2dfa258c76c41a6ff846392e13d1 | 2cb657c0e41baa318193f7dce85974ff37d80883 | refs/heads/master | 1,611,402,038,933 | 1,432,020,760,000 | 1,432,020,760,000 | 33,372,120 | 0 | 0 | null | 1,431,932,928,000 | 1,428,078,840,000 | Lean | UTF-8 | Lean | false | false | 666 | lean | import data.nat
open nat
-- even factorial
-- #0 -> 0, 0!! = 1
-- #1 -> 2, 2!! = 2
-- #2 -> 4, 4!! = 8
-- #3 -> 6, 6!! = 48
-- ...
definition efac : nat → nat
| efac 0 := 1
| efac 1 := 2
| efac (n+2) := efac(n+1) * (2*(n+2))
eval efac 0
eval efac 1
eval efac 2
eval efac 3
example : efac 0 = 1 :=
rfl
example : efac 1 = 2 :=
rfl
-- fac is always positive
theorem efac_pos : ∀ n, 0 < efac n
| efac_pos 0 := show 0 < 1, from zero_lt_succ 0
| efac_pos 1 := show 0 < 2, from zero_lt_succ 1
| efac_pos (n+2) :=
have H1 : 0 < 2*(n+2), from !succ_pos,
calc
0 < efac(n+1) * (2*(n+2)) : mul_pos (efac_pos(n+1)) H1
... = efac(n+2) : rfl
|
c0f695d54d5203bbd581c442402b1acc6a434a3f | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/exercises_sources/thursday/afternoon/category_theory/exercise6.lean | 2dfa10cfe33f0afe008ca4400e475346d2ea9868 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 1,361 | lean | import category_theory.limits.shapes.pullbacks
/-!
Thanks to Markus Himmel for suggesting this question.
-/
open category_theory
open category_theory.limits
/-!
Let C be a category, X and Y be objects and f : X ⟶ Y be a morphism. Show that f is an epimorphism
if and only if the diagram
X --f--→ Y
| |
f 𝟙
| |
↓ ↓
Y --𝟙--→ Y
is a pushout.
-/
variables {C : Type*} [category C]
def pushout_of_epi {X Y : C} (f : X ⟶ Y) [epi f] :
is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) :=
-- Hint: you can start a proof with `fapply pushout_cocone.is_colimit.mk`
-- to save a little bit of work over just building a `is_colimit` structure directly.
sorry
theorem epi_of_pushout {X Y : C} (f : X ⟶ Y)
(is_colim : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f :=
-- Hint: You can use `pushout_cocone.mk` to conveniently construct a cocone over a cospan.
-- Hint: use `is_colim.desc` to construct the map from a colimit cocone to any other cocone.
-- Hint: use `is_colim.fac` to show that this map gives a factorisation of the cocone maps through the colimit cocone.
-- Hint: if `simp` won't correctly simplify `𝟙 X ≫ f`, try `dsimp, simp`.
sorry
/-!
There are some further hints in
`src/hints/thursday/afternoon/category_theory/exercise6/`
-/
|
b6164b6e70cf42d9ac19632e00b2f254fd8dda5a | d65db56b17d72b62013ed1f438f74457ad25b140 | /src/evens_and_odds.lean | 87f730820629cfbfe46c60046fe455473aec3ca3 | [] | no_license | swgillespie/proofs | cfa65722fdb4bb7d7910a0856d0cbea8e8b9a3f9 | 168ef7ef33d372ae0ed6ee4ca336137a52b89f8f | refs/heads/master | 1,585,700,692,028 | 1,540,162,775,000 | 1,540,162,775,000 | 152,695,805 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,758 | lean | /-
Some proofs of simple theorems around even and odd numbers.
Mostly practice for using proof tactics.
-/
open tactic
@[simp] def is_even (n : ℕ) := ∃ x, n = 2 * x
@[simp] def is_odd (n : ℕ) := ∃ x, n = 2 * x + 1
theorem even_plus_even_is_even {a b : ℕ} (h₁ : is_even a) (h₂ : is_even b) : is_even (a + b) :=
begin
simp,
cases h₁ with w₁ hw₁,
cases h₂ with w₂ hw₂,
existsi w₁ + w₂,
rw hw₁,
rw hw₂,
rw mul_add,
end
theorem even_plus_even_is_odd {a b : ℕ} (h₁ : is_even a) (h₂ : is_odd b) : is_odd (a + b) :=
begin
simp,
cases h₁ with w₁ hw₁,
cases h₂ with w₂ hw₂,
existsi w₁ + w₂,
rw hw₁,
rw hw₂,
simp,
rw mul_add
end
theorem odd_plus_odd_is_even {a b : ℕ} (h₁ : is_odd a) (h₂ : is_odd b) : is_even (a + b) :=
begin
simp,
cases h₁ with w₁ hw₁,
cases h₂ with w₂ hw₂,
existsi w₁ + w₂ + 1,
rw hw₁,
rw hw₂,
rw mul_add,
rw mul_add,
simp,
rw ←add_assoc,
end
theorem even_plus_two_is_even {a : ℕ} (h₁ : is_even a) : is_even (a + 2) :=
begin
simp, -- is_even a + 2 → ∃ x : a + 2 = 2 * x
apply even_plus_even_is_even, -- two subgoals: is_even a + is_even 2
assumption, -- is_even a is an assumption h₁
simp, -- is_even 2 → ∃ x : 2 = 2 * x
existsi 1, -- true for x == 1
trivial -- QED
end
-- Some additional proofs, useful for practicing tactics
section
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
include a
example : (∃ x : α, r) → r :=
begin
intro h,
cases h with a₁ ha₁, -- There exists some α such that r, call it a₁
show r, exact ha₁ -- Therefore, r for all a
end
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r :=
begin
apply iff.intro, -- two subgoals - forward and backwards directions of iff
{
-- Forward direction
intro h,
cases h with a ha, -- There exists an x such that h, call it a
cases ha, split, -- Both sides of the and must be true, split into 2 subgoals
existsi a, -- Intro the exists by proving that a is a witness
assumption, -- ... and that p a is true (a hypothesis)
assumption, -- Finally, r is true by the split hypothesis, so we are done
},
{
-- Backward direction
intro h,
cases h with left right,
cases left with a ha,
existsi a,
exact ⟨ha, right⟩
}
end
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
begin
apply iff.intro,
{
intro h,
cases h with a₁ ha₁,
apply or.elim,
assumption,
{
intro q,
apply or.intro_left,
existsi a₁,
assumption
},
{
intro q,
apply or.intro_right,
existsi a₁,
assumption
}
},
{
intro h,
apply or.elim,
assumption,
{
intro q,
cases q with a₁ ha₁,
existsi a₁,
apply or.intro_left,
assumption
},
{
intro q,
cases q with a₁ ha₁,
existsi a₁,
apply or.intro_right,
assumption,
}
}
end
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
begin
apply iff.intro,
{
intro h,
cases h with witness hwitness,
apply or.elim hwitness,
{
intro hp,
apply or.intro_left,
existsi witness,
assumption
},
{
intro hq,
apply or.intro_right,
existsi witness,
assumption
}
},
{
intro h,
apply or.elim h,
{
intro hp,
cases hp with witness hwitness,
existsi witness,
apply or.intro_left,
assumption,
},
{
intro hq,
cases hq with witness hwitness,
existsi witness,
apply or.intro_right,
assumption,
}
}
end
end |
b1b4df02bf00cae0229a3a4fbbf1481a2b2eab78 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/interactive/completionPrv.lean | b02bc4994a9c514614fd83bcccdb1fa608c5a3e1 | [
"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 | 390 | lean | private def blaBlaBoo := 2
#check blaB
--^ textDocument/completion
namespace Foo
private def booBoo := 3
#check booB
--^ textDocument/completion
end Foo
structure S where
field1 : Nat
private def S.getInc (s : S) : Nat :=
s.field1 + 1
def tst1 (s : S) : Nat :=
s.g
--^ textDocument/completion
def tst2 (s : S) : Nat :=
s.
--^ textDocument/completion
|
ebe6461dd93ab93f3a6360d854a4bed9ab8e659d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/special_functions/trigonometric/arctan.lean | def6b7a751d103b72516d647afbf2fa82b54ce08 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 7,260 | 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, Benjamin Davidson
-/
import analysis.special_functions.trigonometric.complex
/-!
# The `arctan` function.
Inequalities, derivatives,
and `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line.
-/
noncomputable theory
namespace real
open set filter
open_locale topological_space real
lemma tan_add {x y : ℝ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)
∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y = (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_add, complex.of_real_div,
complex.of_real_mul, complex.of_real_tan]
using @complex.tan_add (x:ℂ) (y:ℂ) (by convert h; norm_cast)
lemma tan_add' {x y : ℝ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
tan_add (or.inl h)
lemma tan_two_mul {x:ℝ} : tan (2 * x) = 2 * tan x / (1 - tan x ^ 2) :=
by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_div, complex.of_real_pow,
complex.of_real_mul, complex.of_real_tan, complex.of_real_bit0, complex.of_real_one]
using complex.tan_two_mul
lemma tan_ne_zero_iff {θ : ℝ} : tan θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π / 2 :=
by rw [← complex.of_real_ne_zero, complex.of_real_tan, complex.tan_ne_zero_iff]; norm_cast
lemma tan_eq_zero_iff {θ : ℝ} : tan θ = 0 ↔ ∃ k : ℤ, θ = k * π / 2 :=
by rw [← not_iff_not, not_exists, ← ne, tan_ne_zero_iff]
lemma tan_int_mul_pi_div_two (n : ℤ) : tan (n * π/2) = 0 :=
tan_eq_zero_iff.mpr (by use n)
lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} :=
begin
suffices : continuous_on (λ x, sin x / cos x) {x | cos x ≠ 0},
{ have h_eq : (λ x, sin x / cos x) = tan, by {ext1 x, rw tan_eq_sin_div_cos, },
rwa h_eq at this, },
exact continuous_on_sin.div continuous_on_cos (λ x, id),
end
@[continuity]
lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) :=
continuous_on_iff_continuous_restrict.1 continuous_on_tan
lemma continuous_on_tan_Ioo : continuous_on tan (Ioo (-(π/2)) (π/2)) :=
begin
refine continuous_on.mono continuous_on_tan (λ x, _),
simp only [and_imp, mem_Ioo, mem_set_of_eq, ne.def],
rw cos_eq_zero_iff,
rintros hx_gt hx_lt ⟨r, hxr_eq⟩,
cases le_or_lt 0 r,
{ rw lt_iff_not_ge at hx_lt,
refine hx_lt _,
rw [hxr_eq, ← one_mul (π / 2), mul_div_assoc, ge_iff_le, mul_le_mul_right (half_pos pi_pos)],
simp [h], },
{ rw lt_iff_not_ge at hx_gt,
refine hx_gt _,
rw [hxr_eq, ← one_mul (π / 2), mul_div_assoc, ge_iff_le, neg_mul_eq_neg_mul,
mul_le_mul_right (half_pos pi_pos)],
have hr_le : r ≤ -1, by rwa [int.lt_iff_add_one_le, ← le_neg_iff_add_nonpos_right] at h,
rw [← le_sub_iff_add_le, mul_comm, ← le_div_iff],
{ norm_num, rw [← int.cast_one, ← int.cast_neg], norm_cast, exact hr_le, },
{ exact zero_lt_two, }, },
end
lemma surj_on_tan : surj_on tan (Ioo (-(π / 2)) (π / 2)) univ :=
have _ := neg_lt_self pi_div_two_pos,
continuous_on_tan_Ioo.surj_on_of_tendsto (nonempty_Ioo.2 this)
(by simp [tendsto_tan_neg_pi_div_two, this]) (by simp [tendsto_tan_pi_div_two, this])
lemma tan_surjective : function.surjective tan :=
λ x, surj_on_tan.subset_range trivial
lemma image_tan_Ioo : tan '' (Ioo (-(π / 2)) (π / 2)) = univ :=
univ_subset_iff.1 surj_on_tan
/-- `real.tan` as an `order_iso` between `(-(π / 2), π / 2)` and `ℝ`. -/
def tan_order_iso : Ioo (-(π / 2)) (π / 2) ≃o ℝ :=
(strict_mono_on_tan.order_iso _ _).trans $ (order_iso.set_congr _ _ image_tan_Ioo).trans
order_iso.set.univ
/-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and
`arctan x < π / 2` -/
@[pp_nodot] noncomputable def arctan (x : ℝ) : ℝ :=
tan_order_iso.symm x
@[simp] lemma tan_arctan (x : ℝ) : tan (arctan x) = x :=
tan_order_iso.apply_symm_apply x
lemma arctan_mem_Ioo (x : ℝ) : arctan x ∈ Ioo (-(π / 2)) (π / 2) :=
subtype.coe_prop _
@[simp] lemma range_arctan : range arctan = Ioo (-(π / 2)) (π / 2) :=
((equiv_like.surjective _).range_comp _).trans subtype.range_coe
lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x :=
subtype.ext_iff.1 $ tan_order_iso.symm_apply_apply ⟨x, hx₁, hx₂⟩
lemma cos_arctan_pos (x : ℝ) : 0 < cos (arctan x) :=
cos_pos_of_mem_Ioo $ arctan_mem_Ioo x
lemma cos_sq_arctan (x : ℝ) : cos (arctan x) ^ 2 = 1 / (1 + x ^ 2) :=
by rw [one_div, ← inv_one_add_tan_sq (cos_arctan_pos x).ne', tan_arctan]
lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) :=
by rw [← tan_div_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan]
lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) :=
by rw [one_div, ← inv_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan]
lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 :=
(arctan_mem_Ioo x).2
lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x :=
(arctan_mem_Ioo x).1
lemma arctan_eq_arcsin (x : ℝ) : arctan x = arcsin (x / sqrt (1 + x ^ 2)) :=
eq.symm $ arcsin_eq_of_sin_eq (sin_arctan x) (mem_Icc_of_Ioo $ arctan_mem_Ioo x)
lemma arcsin_eq_arctan {x : ℝ} (h : x ∈ Ioo (-(1:ℝ)) 1) :
arcsin x = arctan (x / sqrt (1 - x ^ 2)) :=
begin
rw [arctan_eq_arcsin, div_pow, sq_sqrt, one_add_div, div_div,
← sqrt_mul, mul_div_cancel', sub_add_cancel, sqrt_one, div_one];
nlinarith [h.1, h.2],
end
@[simp] lemma arctan_zero : arctan 0 = 0 :=
by simp [arctan_eq_arcsin]
lemma arctan_eq_of_tan_eq {x y : ℝ} (h : tan x = y) (hx : x ∈ Ioo (-(π / 2)) (π / 2)) :
arctan y = x :=
inj_on_tan (arctan_mem_Ioo _) hx (by rw [tan_arctan, h])
@[simp] lemma arctan_one : arctan 1 = π / 4 :=
arctan_eq_of_tan_eq tan_pi_div_four $ by split; linarith [pi_pos]
@[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x :=
by simp [arctan_eq_arcsin, neg_div]
@[continuity]
lemma continuous_arctan : continuous arctan :=
continuous_subtype_coe.comp tan_order_iso.to_homeomorph.continuous_inv_fun
lemma continuous_at_arctan {x : ℝ} : continuous_at arctan x := continuous_arctan.continuous_at
/-- `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line. -/
def tan_local_homeomorph : local_homeomorph ℝ ℝ :=
{ to_fun := tan,
inv_fun := arctan,
source := Ioo (-(π / 2)) (π / 2),
target := univ,
map_source' := maps_to_univ _ _,
map_target' := λ y hy, arctan_mem_Ioo y,
left_inv' := λ x hx, arctan_tan hx.1 hx.2,
right_inv' := λ y hy, tan_arctan y,
open_source := is_open_Ioo,
open_target := is_open_univ,
continuous_to_fun := continuous_on_tan_Ioo,
continuous_inv_fun := continuous_arctan.continuous_on }
@[simp] lemma coe_tan_local_homeomorph : ⇑tan_local_homeomorph = tan := rfl
@[simp] lemma coe_tan_local_homeomorph_symm : ⇑tan_local_homeomorph.symm = arctan := rfl
end real
|
1eccabd569d53cf835d4a11fd5eea529f59e5493 | c8b4b578b2fe61d500fbca7480e506f6603ea698 | /src/unused/ideal_stuff.lean | f413ad6f7856b8ad3adf4cf8ccca26cc5ad644a8 | [] | no_license | leanprover-community/flt-regular | aa7e564f2679dfd2e86015a5a9674a6e1197f7cc | 67fb3e176584bbc03616c221a7be6fa28c5ccd32 | refs/heads/master | 1,692,188,905,751 | 1,691,766,312,000 | 1,691,766,312,000 | 421,021,216 | 19 | 4 | null | 1,694,532,115,000 | 1,635,166,136,000 | Lean | UTF-8 | Lean | false | false | 679 | lean | import ring_theory.fractional_ideal
open_locale big_operators
open polynomial finset module units fractional_ideal submodule
-- TODO redefine span_singleton as a monoid hom so we get this for free?
-- TODO this really shouldn't be necessary either?
@[simp]
lemma fractional_ideal.span_singleton_prod {R : Type*} {P ι : Type*} [comm_ring R] {S : submonoid R} [comm_ring P]
[algebra R P] [loc : is_localization S P] (T : finset ι) (I : ι → P) :
span_singleton S (∏ t in T, I t) = ∏ t in T, span_singleton S (I t) :=
begin
classical,
induction T using finset.induction with i T hiT ih,
{ simp, },
simp [hiT, span_singleton_mul_span_singleton, ih.symm],
end
|
543b0c46e39395723f876dc3b83eb823a1a8b0c3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/sigma/basic_auto.lean | 8ef7157da21e0bf83ba4a68c6688e76319f5d649 | [] | 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 | 6,344 | 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
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.lint.default
import Mathlib.tactic.ext
import Mathlib.PostPort
universes u_1 u_4 u_2 u_3 u_5 u_6
namespace Mathlib
namespace sigma
protected instance inhabited {α : Type u_1} {β : α → Type u_4} [Inhabited α]
[Inhabited (β Inhabited.default)] : Inhabited (sigma β) :=
{ default := mk Inhabited.default Inhabited.default }
protected instance decidable_eq {α : Type u_1} {β : α → Type u_4} [h₁ : DecidableEq α]
[h₂ : (a : α) → DecidableEq (β a)] : DecidableEq (sigma β) :=
sorry
@[simp] theorem mk.inj_iff {α : Type u_1} {β : α → Type u_4} {a₁ : α} {a₂ : α} {b₁ : β a₁}
{b₂ : β a₂} : mk a₁ b₁ = mk a₂ b₂ ↔ a₁ = a₂ ∧ b₁ == b₂ :=
sorry
@[simp] theorem eta {α : Type u_1} {β : α → Type u_4} (x : sigma fun (a : α) => β a) :
mk (fst x) (snd x) = x :=
cases_on x
fun (x_fst : α) (x_snd : β x_fst) =>
idRhs
(mk (fst (mk x_fst x_snd)) (snd (mk x_fst x_snd)) =
mk (fst (mk x_fst x_snd)) (snd (mk x_fst x_snd)))
rfl
theorem ext {α : Type u_1} {β : α → Type u_4} {x₀ : sigma β} {x₁ : sigma β} (h₀ : fst x₀ = fst x₁)
(h₁ : snd x₀ == snd x₁) : x₀ = x₁ :=
sorry
theorem ext_iff {α : Type u_1} {β : α → Type u_4} {x₀ : sigma β} {x₁ : sigma β} :
x₀ = x₁ ↔ fst x₀ = fst x₁ ∧ snd x₀ == snd x₁ :=
cases_on x₀
fun (x₀_fst : α) (x₀_snd : β x₀_fst) =>
cases_on x₁ fun (x₁_fst : α) (x₁_snd : β x₁_fst) => mk.inj_iff
@[simp] theorem forall {α : Type u_1} {β : α → Type u_4} {p : (sigma fun (a : α) => β a) → Prop} :
(∀ (x : sigma fun (a : α) => β a), p x) ↔ ∀ (a : α) (b : β a), p (mk a b) :=
sorry
@[simp] theorem exists {α : Type u_1} {β : α → Type u_4} {p : (sigma fun (a : α) => β a) → Prop} :
(∃ (x : sigma fun (a : α) => β a), p x) ↔ ∃ (a : α), ∃ (b : β a), p (mk a b) :=
sorry
/-- Map the left and right components of a sigma -/
def map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5} {β₂ : α₂ → Type u_6} (f₁ : α₁ → α₂)
(f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)) (x : sigma β₁) : sigma β₂ :=
mk (f₁ (fst x)) (f₂ (fst x) (snd x))
end sigma
theorem sigma_mk_injective {α : Type u_1} {β : α → Type u_4} {i : α} :
function.injective (sigma.mk i) :=
sorry
theorem function.injective.sigma_map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5}
{β₂ : α₂ → Type u_6} {f₁ : α₁ → α₂} {f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)}
(h₁ : function.injective f₁) (h₂ : ∀ (a : α₁), function.injective (f₂ a)) :
function.injective (sigma.map f₁ f₂) :=
sorry
theorem function.surjective.sigma_map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5}
{β₂ : α₂ → Type u_6} {f₁ : α₁ → α₂} {f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)}
(h₁ : function.surjective f₁) (h₂ : ∀ (a : α₁), function.surjective (f₂ a)) :
function.surjective (sigma.map f₁ f₂) :=
sorry
/-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. -/
def sigma.curry {α : Type u_1} {β : α → Type u_4} {γ : (a : α) → β a → Type u_2}
(f : (x : sigma β) → γ (sigma.fst x) (sigma.snd x)) (x : α) (y : β x) : γ x y :=
f (sigma.mk x y)
/-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x` -/
def sigma.uncurry {α : Type u_1} {β : α → Type u_4} {γ : (a : α) → β a → Type u_2}
(f : (x : α) → (y : β x) → γ x y) (x : sigma β) : γ (sigma.fst x) (sigma.snd x) :=
f (sigma.fst x) (sigma.snd x)
/-- Convert a product type to a Σ-type. -/
@[simp] def prod.to_sigma {α : Type u_1} {β : Type u_2} : α × β → sigma fun (_x : α) => β := sorry
@[simp] theorem prod.fst_to_sigma {α : Type u_1} {β : Type u_2} (x : α × β) :
sigma.fst (prod.to_sigma x) = prod.fst x :=
prod.cases_on x fun (x_fst : α) (x_snd : β) => Eq.refl (sigma.fst (prod.to_sigma (x_fst, x_snd)))
@[simp] theorem prod.snd_to_sigma {α : Type u_1} {β : Type u_2} (x : α × β) :
sigma.snd (prod.to_sigma x) = prod.snd x :=
prod.cases_on x fun (x_fst : α) (x_snd : β) => Eq.refl (sigma.snd (prod.to_sigma (x_fst, x_snd)))
namespace psigma
/-- Nondependent eliminator for `psigma`. -/
def elim {α : Sort u_1} {β : α → Sort u_2} {γ : Sort u_3} (f : (a : α) → β a → γ) (a : psigma β) :
γ :=
cases_on a f
@[simp] theorem elim_val {α : Sort u_1} {β : α → Sort u_2} {γ : Sort u_3} (f : (a : α) → β a → γ)
(a : α) (b : β a) : elim f (mk a b) = f a b :=
rfl
protected instance inhabited {α : Sort u_1} {β : α → Sort u_2} [Inhabited α]
[Inhabited (β Inhabited.default)] : Inhabited (psigma β) :=
{ default := mk Inhabited.default Inhabited.default }
protected instance decidable_eq {α : Sort u_1} {β : α → Sort u_2} [h₁ : DecidableEq α]
[h₂ : (a : α) → DecidableEq (β a)] : DecidableEq (psigma β) :=
sorry
theorem mk.inj_iff {α : Sort u_1} {β : α → Sort u_2} {a₁ : α} {a₂ : α} {b₁ : β a₁} {b₂ : β a₂} :
mk a₁ b₁ = mk a₂ b₂ ↔ a₁ = a₂ ∧ b₁ == b₂ :=
sorry
theorem ext {α : Sort u_1} {β : α → Sort u_2} {x₀ : psigma β} {x₁ : psigma β} (h₀ : fst x₀ = fst x₁)
(h₁ : snd x₀ == snd x₁) : x₀ = x₁ :=
sorry
theorem ext_iff {α : Sort u_1} {β : α → Sort u_2} {x₀ : psigma β} {x₁ : psigma β} :
x₀ = x₁ ↔ fst x₀ = fst x₁ ∧ snd x₀ == snd x₁ :=
cases_on x₀
fun (x₀_fst : α) (x₀_snd : β x₀_fst) =>
cases_on x₁ fun (x₁_fst : α) (x₁_snd : β x₁_fst) => mk.inj_iff
/-- Map the left and right components of a sigma -/
def map {α₁ : Sort u_3} {α₂ : Sort u_4} {β₁ : α₁ → Sort u_5} {β₂ : α₂ → Sort u_6} (f₁ : α₁ → α₂)
(f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ :=
sorry
end Mathlib |
147b21edb42636a1aaf5e3a1bd6de86de00a1a2b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/invariant_basis_number.lean | de2c532e57ac445b0be2a14263e1d27636a07ce8 | [
"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 | 808 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import linear_algebra.matrix.to_lin
import linear_algebra.invariant_basis_number
/-!
# Invertible matrices over a ring with invariant basis number are square.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {n m : Type*} [fintype n] [decidable_eq n] [fintype m] [decidable_eq m]
variables {R : Type*} [semiring R] [invariant_basis_number R]
open_locale matrix
lemma matrix.square_of_invertible
(M : matrix n m R) (N : matrix m n R) (h : M ⬝ N = 1) (h' : N ⬝ M = 1) :
fintype.card n = fintype.card m :=
card_eq_of_lequiv R (matrix.to_linear_equiv_right'_of_inv h' h)
|
0a32fdb2ba7820ae5f16b2e8f67eeb306cfa2067 | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world10/level14.lean | d7b1ae55aad16cbea5eb94addd5c605df71c64b5 | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 134 | lean | theorem add_le_add_left {a b : mynat} (h : a ≤ b) (t : mynat) :
t + a ≤ t + b :=
begin
cases h with d hd,
use d,
rw hd,
cc,
end
|
85cb77c80972b68251a41fcbd2697c80569923a0 | 6b10c15e653d49d146378acda9f3692e9b5b1950 | /examples/basic_skills/unnamed_760.lean | e87aca02e564d7acbee60bf51bb00d64fa6fbb21 | [] | no_license | gebner/mathematics_in_lean | 3cf7f18767208ea6c3307ec3a67c7ac266d8514d | 6d1462bba46d66a9b948fc1aef2714fd265cde0b | refs/heads/master | 1,655,301,945,565 | 1,588,697,505,000 | 1,588,697,505,000 | 261,523,603 | 0 | 0 | null | 1,588,695,611,000 | 1,588,695,610,000 | null | UTF-8 | Lean | false | false | 190 | lean | namespace my_ring
variables {R : Type*} [ring R]
-- BEGIN
theorem sub_eq_add_neg (a b : R) : a - b = a + -b :=
rfl
example (a b : R) : a - b = a + -b :=
by reflexivity
-- END
end my_ring |
b0eb8bde4bff7a1224f2bcce85b4183e445cf0e4 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/pstate.lean | 0f0dc69a8c9c948c59cef8dbc36b51c6cd4cf8f4 | [
"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 | 114 | lean | import logic
theorem foo {A : Type} (a b c : A) : a = b → b = c → a = c :=
assume h₁ h₂, eq.trans h₁ _
|
a4a13c9dfd314aaab8cdbadf9ea95f93610d9039 | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /stage0/src/Lean/Parser/Term.lean | e48c8d90e6e57025dfbebe8a8c7b1c724c94140b | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 16,993 | 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.Attr
import Lean.Parser.Level
namespace Lean
namespace Parser
namespace Command
def commentBody : Parser :=
{ fn := rawFn (fun c s => finishCommentBlock s.pos 1 c s) (trailingWs := true) }
@[combinatorParenthesizer Lean.Parser.Command.commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken
@[combinatorFormatter Lean.Parser.Command.commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous
def docComment := leading_parser ppDedent $ "/--" >> commentBody >> ppLine
end Command
builtin_initialize
registerBuiltinParserAttribute `builtinTacticParser `tactic LeadingIdentBehavior.both
registerBuiltinDynamicParserAttribute `tacticParser `tactic
@[inline] def tacticParser (rbp : Nat := 0) : Parser :=
categoryParser `tactic rbp
namespace Tactic
def tacticSeq1Indented : Parser :=
leading_parser many1Indent (group (ppLine >> tacticParser >> optional ";"))
def tacticSeqBracketed : Parser :=
leading_parser "{" >> many (group (ppLine >> tacticParser >> optional ";")) >> ppDedent (ppLine >> "}")
def tacticSeq :=
nodeWithAntiquot "tacticSeq" `Lean.Parser.Tactic.tacticSeq (tacticSeqBracketed <|> tacticSeq1Indented)
/- Raw sequence for quotation and grouping -/
def seq1 :=
node `Lean.Parser.Tactic.seq1 $ sepBy1 tacticParser ";\n" (allowTrailingSep := true)
end Tactic
def darrow : Parser := " => "
namespace Term
/- Built-in parsers -/
@[builtinTermParser] def byTactic := leading_parser:leadPrec "by " >> Tactic.tacticSeq
def optSemicolon (p : Parser) : Parser := ppDedent $ optional ";" >> ppLine >> p
-- `checkPrec` necessary for the pretty printer
@[builtinTermParser] def ident := checkPrec maxPrec >> Parser.ident
@[builtinTermParser] def num : Parser := checkPrec maxPrec >> numLit
@[builtinTermParser] def scientific : Parser := checkPrec maxPrec >> scientificLit
@[builtinTermParser] def str : Parser := checkPrec maxPrec >> strLit
@[builtinTermParser] def char : Parser := checkPrec maxPrec >> charLit
@[builtinTermParser] def type := leading_parser "Type" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec)
@[builtinTermParser] def sort := leading_parser "Sort" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec)
@[builtinTermParser] def prop := leading_parser "Prop"
@[builtinTermParser] def hole := leading_parser "_"
@[builtinTermParser] def syntheticHole := leading_parser "?" >> (ident <|> hole)
@[builtinTermParser] def «sorry» := leading_parser "sorry"
@[builtinTermParser] def cdot := leading_parser symbol "·" <|> "."
@[builtinTermParser] def emptyC := leading_parser "∅" <|> (symbol "{" >> "}")
def typeAscription := leading_parser " : " >> termParser
def tupleTail := leading_parser ", " >> sepBy1 termParser ", "
def parenSpecial : Parser := optional (tupleTail <|> typeAscription)
@[builtinTermParser] def paren := leading_parser "(" >> ppDedent (withoutPosition (withoutForbidden (optional (termParser >> parenSpecial)))) >> ")"
@[builtinTermParser] def anonymousCtor := leading_parser "⟨" >> sepBy termParser ", " >> "⟩"
def optIdent : Parser := optional (atomic (ident >> " : "))
def fromTerm := leading_parser " from " >> termParser
def haveAssign := leading_parser " := " >> termParser
def haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)
@[builtinTermParser] def «have» := leading_parser:leadPrec withPosition ("have " >> haveDecl) >> optSemicolon termParser
def sufficesDecl := leading_parser optIdent >> termParser >> (fromTerm <|> byTactic)
@[builtinTermParser] def «suffices» := leading_parser:leadPrec withPosition ("suffices " >> sufficesDecl) >> optSemicolon termParser
@[builtinTermParser] def «show» := leading_parser:leadPrec "show " >> termParser >> (fromTerm <|> byTactic)
def structInstArrayRef := leading_parser "[" >> termParser >>"]"
def structInstLVal := leading_parser (ident <|> fieldIdx <|> structInstArrayRef) >> many (group ("." >> (ident <|> fieldIdx)) <|> structInstArrayRef)
def structInstField := ppGroup $ leading_parser structInstLVal >> " := " >> termParser
def optEllipsis := leading_parser optional ".."
@[builtinTermParser] def structInst := leading_parser "{" >> ppHardSpace >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optEllipsis
>> optional (" : " >> termParser) >> " }"
def typeSpec := leading_parser " : " >> termParser
def optType : Parser := optional typeSpec
@[builtinTermParser] def explicit := leading_parser "@" >> termParser maxPrec
@[builtinTermParser] def inaccessible := leading_parser ".(" >> termParser >> ")"
def binderIdent : Parser := ident <|> hole
def binderType (requireType := false) : Parser := if requireType then node nullKind (" : " >> termParser) else optional (" : " >> termParser)
def binderTactic := leading_parser atomic (symbol " := " >> " by ") >> Tactic.tacticSeq
def binderDefault := leading_parser " := " >> termParser
def explicitBinder (requireType := false) := ppGroup $ leading_parser "(" >> many1 binderIdent >> binderType requireType >> optional (binderTactic <|> binderDefault) >> ")"
def implicitBinder (requireType := false) := ppGroup $ leading_parser "{" >> many1 binderIdent >> binderType requireType >> "}"
def instBinder := ppGroup $ leading_parser "[" >> optIdent >> termParser >> "]"
def bracketedBinder (requireType := false) := withAntiquot (mkAntiquot "bracketedBinder" none (anonymous := false)) <|
explicitBinder requireType <|> implicitBinder requireType <|> instBinder
/-
It is feasible to support dependent arrows such as `{α} → α → α` without sacrificing the quality of the error messages for the longer case.
`{α} → α → α` would be short for `{α : Type} → α → α`
Here is the encoding:
```
def implicitShortBinder := node `Lean.Parser.Term.implicitBinder $ "{" >> many1 binderIdent >> pushNone >> "}"
def depArrowShortPrefix := try (implicitShortBinder >> unicodeSymbol " → " " -> ")
def depArrowLongPrefix := bracketedBinder true >> unicodeSymbol " → " " -> "
def depArrowPrefix := depArrowShortPrefix <|> depArrowLongPrefix
@[builtinTermParser] def depArrow := leading_parser depArrowPrefix >> termParser
```
Note that no changes in the elaborator are needed.
We decided to not use it because terms such as `{α} → α → α` may look too cryptic.
Note that we did not add a `explicitShortBinder` parser since `(α) → α → α` is really cryptic as a short for `(α : Type) → α → α`.
-/
@[builtinTermParser] def depArrow := leading_parser:25 bracketedBinder true >> unicodeSymbol " → " " -> " >> termParser
def simpleBinder := leading_parser many1 binderIdent >> optType
@[builtinTermParser]
def «forall» := leading_parser:leadPrec unicodeSymbol "∀" "forall" >> many1 (ppSpace >> (simpleBinder <|> bracketedBinder)) >> ", " >> termParser
def matchAlt (rhsParser : Parser := termParser) : Parser :=
nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $
"| " >> ppIndent (sepBy1 termParser ", " >> darrow >> checkColGe "alternative right-hand-side to start in a column greater than or equal to the corresponding '|'" >> rhsParser)
/--
Useful for syntax quotations. Note that generic patterns such as `` `(matchAltExpr| | ... => $rhs) `` should also
work with other `rhsParser`s (of arity 1). -/
def matchAltExpr := matchAlt
def matchAlts (rhsParser : Parser := termParser) : Parser :=
leading_parser ppDedent $ withPosition $ many1Indent (ppLine >> matchAlt rhsParser)
def matchDiscr := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser
@[builtinTermParser] def «match» := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts
@[builtinTermParser] def «nomatch» := leading_parser:leadPrec "nomatch " >> termParser
def funImplicitBinder := atomic (lookahead ("{" >> many1 binderIdent >> (symbol " : " <|> "}"))) >> implicitBinder
def funSimpleBinder := atomic (lookahead (many1 binderIdent >> " : ")) >> simpleBinder
def funBinder : Parser := funImplicitBinder <|> instBinder <|> funSimpleBinder <|> termParser maxPrec
-- NOTE: we use `nodeWithAntiquot` to ensure that `fun $b => ...` remains a `term` antiquotation
def basicFun : Parser := nodeWithAntiquot "basicFun" `Lean.Parser.Term.basicFun (many1 (ppSpace >> funBinder) >> darrow >> termParser)
@[builtinTermParser] def «fun» := leading_parser:maxPrec unicodeSymbol "λ" "fun" >> (basicFun <|> matchAlts)
def optExprPrecedence := optional (atomic ":" >> termParser maxPrec)
@[builtinTermParser] def «leading_parser» := leading_parser:leadPrec "leading_parser " >> optExprPrecedence >> termParser
@[builtinTermParser] def «trailing_parser» := leading_parser:leadPrec "trailing_parser " >> optExprPrecedence >> optExprPrecedence >> termParser
@[builtinTermParser] def borrowed := leading_parser "@&" >> termParser leadPrec
@[builtinTermParser] def quotedName := leading_parser nameLit
@[builtinTermParser] def doubleQuotedName := leading_parser "`" >> checkNoWsBefore >> nameLit
def simpleBinderWithoutType := nodeWithAntiquot "simpleBinder" `Lean.Parser.Term.simpleBinder (anonymous := true)
(many1 binderIdent >> pushNone)
/- Remark: we use `checkWsBefore` to ensure `let x[i] := e; b` is not parsed as `let x [i] := e; b` where `[i]` is an `instBinder`. -/
def letIdLhs : Parser := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType
def letIdDecl := nodeWithAntiquot "letIdDecl" `Lean.Parser.Term.letIdDecl $ atomic (letIdLhs >> " := ") >> termParser
def letPatDecl := nodeWithAntiquot "letPatDecl" `Lean.Parser.Term.letPatDecl $ atomic (termParser >> pushNone >> optType >> " := ") >> termParser
def letEqnsDecl := nodeWithAntiquot "letEqnsDecl" `Lean.Parser.Term.letEqnsDecl $ letIdLhs >> matchAlts
-- Remark: we use `nodeWithAntiquot` here to make sure anonymous antiquotations (e.g., `$x`) are not `letDecl`
def letDecl := nodeWithAntiquot "letDecl" `Lean.Parser.Term.letDecl (notFollowedBy (nonReservedSymbol "rec") "rec" >> (letIdDecl <|> letPatDecl <|> letEqnsDecl))
@[builtinTermParser] def «let» := leading_parser:leadPrec withPosition ("let " >> letDecl) >> optSemicolon termParser
@[builtinTermParser] def «let_fun» := leading_parser:leadPrec withPosition ((symbol "let_fun " <|> "let_λ") >> letDecl) >> optSemicolon termParser
@[builtinTermParser] def «let_delayed» := leading_parser:leadPrec withPosition ("let_delayed " >> letDecl) >> optSemicolon termParser
def «scoped» := leading_parser "scoped "
def «local» := leading_parser "local "
def attrKind := leading_parser optional («scoped» <|> «local»)
def attrInstance := ppGroup $ leading_parser attrKind >> attrParser
def attributes := leading_parser "@[" >> sepBy1 attrInstance ", " >> "]"
def letRecDecl := leading_parser optional Command.docComment >> optional «attributes» >> letDecl
def letRecDecls := leading_parser sepBy1 letRecDecl ", "
@[builtinTermParser]
def «letrec» := leading_parser:leadPrec withPosition (group ("let " >> nonReservedSymbol "rec ") >> letRecDecls) >> optSemicolon termParser
@[runBuiltinParserAttributeHooks]
def whereDecls := leading_parser "where " >> many1Indent (group (letRecDecl >> optional ";"))
@[runBuiltinParserAttributeHooks]
def matchAltsWhereDecls := leading_parser matchAlts >> optional whereDecls
@[builtinTermParser] def noindex := leading_parser "no_index " >> termParser maxPrec
@[builtinTermParser] def binrel := leading_parser "binrel% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec
@[builtinTermParser] def forInMacro := leading_parser "forIn% " >> termParser maxPrec >> termParser maxPrec >> termParser maxPrec
@[builtinTermParser] def typeOf := leading_parser "typeOf% " >> termParser maxPrec
@[builtinTermParser] def ensureTypeOf := leading_parser "ensureTypeOf% " >> termParser maxPrec >> strLit >> termParser
@[builtinTermParser] def ensureExpectedType := leading_parser "ensureExpectedType% " >> strLit >> termParser maxPrec
@[builtinTermParser] def noImplicitLambda := leading_parser "noImplicitLambda% " >> termParser maxPrec
def namedArgument := leading_parser atomic ("(" >> ident >> " := ") >> termParser >> ")"
def ellipsis := leading_parser ".."
def argument :=
checkWsBefore "expected space" >>
checkColGt "expected to be indented" >>
(namedArgument <|> ellipsis <|> termParser argPrec)
-- `app` precedence is `lead` (cannot be used as argument)
-- `lhs` precedence is `max` (i.e. does not accept `arg` precedence)
-- argument precedence is `arg` (i.e. does not accept `lead` precedence)
@[builtinTermParser] def app := trailing_parser:leadPrec:maxPrec many1 argument
@[builtinTermParser] def proj := trailing_parser checkNoWsBefore >> "." >> checkNoWsBefore >> (fieldIdx <|> ident)
@[builtinTermParser] def completion := trailing_parser checkNoWsBefore >> "."
@[builtinTermParser] def arrayRef := trailing_parser checkNoWsBefore >> "[" >> termParser >>"]"
@[builtinTermParser] def arrow := trailing_parser checkPrec 25 >> unicodeSymbol " → " " -> " >> termParser 25
def isIdent (stx : Syntax) : Bool :=
-- antiquotations should also be allowed where an identifier is expected
stx.isAntiquot || stx.isIdent
@[builtinTermParser] def explicitUniv : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '.{'" >> ".{" >> sepBy1 levelParser ", " >> "}"
@[builtinTermParser] def namedPattern : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '@'" >> "@" >> termParser maxPrec
@[builtinTermParser] def pipeProj := trailing_parser:minPrec " |>." >> checkNoWsBefore >> (fieldIdx <|> ident) >> many argument
@[builtinTermParser] def pipeCompletion := trailing_parser:minPrec " |>."
@[builtinTermParser] def subst := trailing_parser:75 " ▸ " >> sepBy1 (termParser 75) " ▸ "
-- NOTE: Doesn't call `categoryParser` directly in contrast to most other "static" quotations, so call `evalInsideQuot` explicitly
@[builtinTermParser] def funBinder.quot : Parser := leading_parser "`(funBinder|" >> toggleInsideQuot (evalInsideQuot ``funBinder funBinder) >> ")"
def bracketedBinderF := bracketedBinder -- no default arg
@[builtinTermParser] def bracketedBinder.quot : Parser := leading_parser "`(bracketedBinder|" >> toggleInsideQuot (evalInsideQuot ``bracketedBinderF bracketedBinder) >> ")"
@[builtinTermParser] def matchDiscr.quot : Parser := leading_parser "`(matchDiscr|" >> toggleInsideQuot (evalInsideQuot ``matchDiscr matchDiscr) >> ")"
@[builtinTermParser] def attr.quot : Parser := leading_parser "`(attr|" >> toggleInsideQuot attrParser >> ")"
@[builtinTermParser] def panic := leading_parser:leadPrec "panic! " >> termParser
@[builtinTermParser] def unreachable := leading_parser:leadPrec "unreachable!"
@[builtinTermParser] def dbgTrace := leading_parser:leadPrec withPosition ("dbg_trace" >> ((interpolatedStr termParser) <|> termParser)) >> optSemicolon termParser
@[builtinTermParser] def assert := leading_parser:leadPrec withPosition ("assert! " >> termParser) >> optSemicolon termParser
def macroArg := termParser maxPrec
def macroDollarArg := leading_parser "$" >> termParser 10
def macroLastArg := macroDollarArg <|> macroArg
-- Macro for avoiding exponentially big terms when using `STWorld`
@[builtinTermParser] def stateRefT := leading_parser "StateRefT" >> macroArg >> macroLastArg
@[builtinTermParser] def dynamicQuot := leading_parser "`(" >> ident >> "|" >> toggleInsideQuot (parserOfStack 1) >> ")"
end Term
@[builtinTermParser default+1] def Tactic.quot : Parser := leading_parser "`(tactic|" >> toggleInsideQuot tacticParser >> ")"
@[builtinTermParser] def Tactic.quotSeq : Parser := leading_parser "`(tactic|" >> toggleInsideQuot Tactic.seq1 >> ")"
@[builtinTermParser] def Level.quot : Parser := leading_parser "`(level|" >> toggleInsideQuot levelParser >> ")"
builtin_initialize
register_parser_alias "letDecl" Term.letDecl
register_parser_alias "haveDecl" Term.haveDecl
register_parser_alias "sufficesDecl" Term.sufficesDecl
register_parser_alias "letRecDecls" Term.letRecDecls
register_parser_alias "hole" Term.hole
register_parser_alias "syntheticHole" Term.syntheticHole
register_parser_alias "matchDiscr" Term.matchDiscr
register_parser_alias "bracketedBinder" Term.bracketedBinder
register_parser_alias "attrKind" Term.attrKind
end Parser
end Lean
|
f3b1cabe2a1dd218e6aa5a62cc11ca1d040c6bd8 | db5883ff1bc38a1433ebf33b20d78352c2de4982 | /LEAN/demo.lean | 210675f0fa00b294263c0baf6cfd1007b8057fc5 | [
"MIT"
] | permissive | FiveEyes/SoftwareFoundationsSolution | 416d72e2c30e5ad085313d2965fc81904b95d538 | d66c636107ac6fd7276504324c6da28c4775dd75 | refs/heads/master | 1,629,128,378,858 | 1,511,178,214,000 | 1,511,178,214,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,237 | lean | def even(n : ℕ) : Prop := ∃ m, n = 2 * m
#check even 10
example : even 10 := ⟨ 5, rfl ⟩
theorem and_commutative (p q : Prop) : p ∧ q → q ∧ p :=
assume hpq : p ∧ q,
have hp : p, from and.left hpq,
have hq : q, from and.right hpq,
show q ∧ p, from and.intro hq hp
#check and_commutative
#print and_commutative
theorem and_commutative' (p q : Prop) : p ∧ q → q ∧ p :=
begin
intro hp,
apply and.intro,
exact and.right hp,
exact and.left hp,
end
#check and_commutative'
#print and_commutative'
#check prod
#print prod
#check list
universe u
constant α : Type u
#check α
#check fun x : nat, x + 5
#check λ x : nat, x + 5
constants (a : α) (b : β)
#reduce (λ x : α, x) a
#eval (λ x : α, x) a
def foo : (ℕ → ℕ) → ℕ := λ f, f 0
#check foo
#check (ℕ → ℕ) → ℕ
#print foo
def curry (α β γ : Type) (f : α × β → γ) : α → β → γ := λ x y, f (x, y)
#check curry
#print curry
#check let y := 2 + 2, z := y + y in z * z
#reduce let y := 2 + 2, z := y + y in z * z
def foo1 := let a := nat in λ x : a, x + 2
#check foo1
/-
def bar := (λ a, λ x : a, x + 2) nat
#check bar
-/
#check curry
#print curry
#check 0 - 1
#reduce 0 + 1
#reduce 0 - 1
|
53e9c54ec2708e346b133df2a38561cb3dde10f7 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/algebra/uniform_field.lean | fad8c7b2a4335f755e3ca82e945da1672fe41957 | [
"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 | 6,548 | lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.algebra.uniform_ring
import topology.algebra.field
/-!
# Completion of topological fields
The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 :
The completion `hat K` of a Hausdorff topological field is a field if the image under
the mapping `x ↦ x⁻¹` of every Cauchy filter (with respect to the additive uniform structure)
which does not have a cluster point at `0` is a Cauchy filter
(with respect to the additive uniform structure).
Bourbaki does not give any detail here, he refers to the general discussion of extending
functions defined on a dense subset with values in a complete Hausdorff space. In particular
the subtlety about clustering at zero is totally left to readers.
Note that the separated completion of a non-separated topological field is the zero ring, hence
the separation assumption is needed. Indeed the kernel of the completion map is the closure of
zero which is an ideal. Hence it's either zero (and the field is separated) or the full field,
which implies one is sent to zero and the completion ring is trivial.
The main definition is `completable_top_field` which packages the assumptions as a Prop-valued
type class and the main results are the instances `field_completion` and
`topological_division_ring_completion`.
-/
noncomputable theory
open_locale classical uniformity topological_space
open set uniform_space uniform_space.completion filter
variables (K : Type*) [field K] [uniform_space K]
local notation `hat` := completion
@[priority 100]
instance [separated_space K] : nontrivial (hat K) :=
⟨⟨0, 1, λ h, zero_ne_one $ (uniform_embedding_coe K).inj h⟩⟩
/--
A topological field is completable if it is separated and the image under
the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure)
which does not have a cluster point at 0 is a Cauchy filter
(with respect to the additive uniform structure). This ensures the completion is
a field.
-/
class completable_top_field extends separated_space K : Prop :=
(nice : ∀ F : filter K, cauchy F → 𝓝 0 ⊓ F = ⊥ → cauchy (map (λ x, x⁻¹) F))
variables {K}
/-- extension of inversion to the completion of a field. -/
def hat_inv : hat K → hat K := dense_inducing_coe.extend (λ x : K, (coe x⁻¹ : hat K))
lemma continuous_hat_inv [completable_top_field K] {x : hat K} (h : x ≠ 0) :
continuous_at hat_inv x :=
begin
haveI : regular_space (hat K) := completion.regular_space K,
refine dense_inducing_coe.continuous_at_extend _,
apply mem_of_superset (compl_singleton_mem_nhds h),
intros y y_ne,
rw mem_compl_singleton_iff at y_ne,
apply complete_space.complete,
rw ← filter.map_map,
apply cauchy.map _ (completion.uniform_continuous_coe K),
apply completable_top_field.nice,
{ haveI := dense_inducing_coe.comap_nhds_ne_bot y,
apply cauchy_nhds.comap,
{ rw completion.comap_coe_eq_uniformity,
exact le_rfl } },
{ have eq_bot : 𝓝 (0 : hat K) ⊓ 𝓝 y = ⊥,
{ by_contradiction h,
exact y_ne (eq_of_nhds_ne_bot $ ne_bot_iff.mpr h).symm },
erw [dense_inducing_coe.nhds_eq_comap (0 : K), ← comap_inf, eq_bot],
exact comap_bot },
end
/-
The value of `hat_inv` at zero is not really specified, although it's probably zero.
Here we explicitly enforce the `inv_zero` axiom.
-/
instance completion.has_inv : has_inv (hat K) := ⟨λ x, if x = 0 then 0 else hat_inv x⟩
variables [topological_division_ring K]
lemma hat_inv_extends {x : K} (h : x ≠ 0) : hat_inv (x : hat K) = coe (x⁻¹ : K) :=
dense_inducing_coe.extend_eq_at
((continuous_coe K).continuous_at.comp (topological_division_ring.continuous_inv x h))
variables [completable_top_field K]
@[norm_cast]
lemma coe_inv (x : K) : (x : hat K)⁻¹ = ((x⁻¹ : K) : hat K) :=
begin
by_cases h : x = 0,
{ rw [h, inv_zero],
dsimp [has_inv.inv],
norm_cast,
simp },
{ conv_lhs { dsimp [has_inv.inv] },
rw if_neg,
{ exact hat_inv_extends h },
{ exact λ H, h (dense_embedding_coe.inj H) } }
end
variables [uniform_add_group K]
lemma mul_hat_inv_cancel {x : hat K} (x_ne : x ≠ 0) : x*hat_inv x = 1 :=
begin
haveI : t1_space (hat K) := t2_space.t1_space,
let f := λ x : hat K, x*hat_inv x,
let c := (coe : K → hat K),
change f x = 1,
have cont : continuous_at f x,
{ letI : topological_space (hat K × hat K) := prod.topological_space,
have : continuous_at (λ y : hat K, ((y, hat_inv y) : hat K × hat K)) x,
from continuous_id.continuous_at.prod (continuous_hat_inv x_ne),
exact (_root_.continuous_mul.continuous_at.comp this : _) },
have clo : x ∈ closure (c '' {0}ᶜ),
{ have := dense_inducing_coe.dense x,
rw [← image_univ, show (univ : set K) = {0} ∪ {0}ᶜ,
from (union_compl_self _).symm, image_union] at this,
apply mem_closure_of_mem_closure_union this,
rw image_singleton,
exact compl_singleton_mem_nhds x_ne },
have fxclo : f x ∈ closure (f '' (c '' {0}ᶜ)) := mem_closure_image cont clo,
have : f '' (c '' {0}ᶜ) ⊆ {1},
{ rw image_image,
rintros _ ⟨z, z_ne, rfl⟩,
rw mem_singleton_iff,
rw mem_compl_singleton_iff at z_ne,
dsimp [c, f],
rw hat_inv_extends z_ne,
norm_cast,
rw mul_inv_cancel z_ne,
norm_cast },
replace fxclo := closure_mono this fxclo,
rwa [closure_singleton, mem_singleton_iff] at fxclo
end
instance field_completion : field (hat K) :=
{ exists_pair_ne := ⟨0, 1, λ h, zero_ne_one ((uniform_embedding_coe K).inj h)⟩,
mul_inv_cancel := λ x x_ne, by { dsimp [has_inv.inv],
simp [if_neg x_ne, mul_hat_inv_cancel x_ne], },
inv_zero := show ((0 : K) : hat K)⁻¹ = ((0 : K) : hat K), by rw [coe_inv, inv_zero],
..completion.has_inv,
..(by apply_instance : comm_ring (hat K)) }
instance topological_division_ring_completion : topological_division_ring (hat K) :=
{ continuous_inv := begin
intros x x_ne,
have : {y | hat_inv y = y⁻¹ } ∈ 𝓝 x,
{ have : {(0 : hat K)}ᶜ ⊆ {y : hat K | hat_inv y = y⁻¹ },
{ intros y y_ne,
rw mem_compl_singleton_iff at y_ne,
dsimp [has_inv.inv],
rw if_neg y_ne },
exact mem_of_superset (compl_singleton_mem_nhds x_ne) this },
exact continuous_at.congr (continuous_hat_inv x_ne) this
end,
..completion.top_ring_compl }
|
66502699bf1429f7f59b7d1697b85bdc9b92699f | 618003631150032a5676f229d13a079ac875ff77 | /src/linear_algebra/multilinear.lean | 9fb9d49775170f3084c19f60ae18b60d3b5ed827 | [
"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 | 33,806 | 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 linear_algebra.basic
import tactic.omega
import data.fintype.card
/-!
# Multilinear maps
We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each
coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type
(although some statements will require it to be a fintype). This space, denoted by
`multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication.
## Main definitions
* `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`.
* `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate.
* `f.map_add` is the additivity of the multilinear map `f` along each coordinate.
* `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time,
writing `f (λi, c i • m i)` as `univ.prod c • f m`.
* `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing
`f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`.
* `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions.
We also register isomorphisms corresponding to currying or uncurrying variables, transforming a
multilinear function `f` on `n+1` variables into a linear function taking values in multilinear
functions in `n` variables, and into a multilinear function in `n` variables taking values in linear
functions. These operations are called `f.curry_left` and `f.curry_right` respectively
(with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences
between spaces of multilinear functions in `n+1` variables and spaces of linear functions into
multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values
in linear functions), called respectively `multilinear_curry_left_equiv` and
`multilinear_curry_right_equiv`.
## Implementation notes
Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed
can be done in two (equivalent) different ways:
* fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate
* fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate
The second way is more artificial as the value of `m` at `i` is not relevant, but it has the
advantage of avoiding subtype inclusion issues. This is the definition we use, based on
`function.update` that allows to change the value of `m` at `i`.
-/
open function fin set
universes u v v' v₁ v₂ v₃ w u'
variables {R : Type u} {ι : Type u'} {n : ℕ}
{M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'}
[decidable_eq ι]
/-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules
over `R`. -/
structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w)
[decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)]
[semimodule R M₂] :=
(to_fun : (Πi, M₁ i) → M₂)
(add : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i),
to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y))
(smul : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i),
to_fun (update m i (c • x)) = c • to_fun (update m i x))
namespace multilinear_map
section semiring
variables [semiring R]
[∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃]
[add_comm_monoid M']
[∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M']
(f f' : multilinear_map R M₁ M₂)
instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩
@[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
by cases f; cases f'; congr'; exact funext H
@[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.add m i x y
@[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) :
f (update m i (c • x)) = c • f (update m i x) :=
f.smul m i c x
lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 :=
begin
have : (0 : R) • (0 : M₁ i) = 0, by simp,
rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul]
end
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
begin
obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι,
exact map_coord_zero f i rfl
end
instance : has_add (multilinear_map R M₁ M₂) :=
⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
instance : has_zero (multilinear_map R M₁ M₂) :=
⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩
instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl
instance : add_comm_monoid (multilinear_map R M₁ M₂) :=
by refine {zero := 0, add := (+), ..};
intros; ext; simp [add_comm, add_left_comm]
@[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂)
(m : Πi, M₁ i) : ∀ {s : finset α}, (s.sum f) m = s.sum (λ a, f a m) :=
begin
classical,
apply finset.induction,
{ rw finset.sum_empty, simp },
{ assume a s has H, rw finset.sum_insert has, simp [H, has] }
end
/-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all
coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/
def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ :=
{ to_fun := λx, f (update m i x),
add := λx y, by simp,
smul := λc x, by simp }
/-- The cartesian product of two multilinear maps, as a multilinear map. -/
def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) :
multilinear_map R M₁ (M₂ × M₃) :=
{ to_fun := λ m, (f m, g m),
add := λ m i x y, by simp,
smul := λ m i c x, by simp }
/-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k`
of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing
the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a
proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that
we use is the canonical (increasing) bijection. -/
noncomputable def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n))
(hk : s.card = k) (z : M') :
multilinear_map R (λ i : fin k, M') M₂ :=
{ to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z),
add := λ v i x y,
by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp },
smul := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } }
variable {R}
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c • x) m) = c • f (cons x m) :=
by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) :
f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) :=
by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma snoc_smul (f : multilinear_map R M M₂)
(m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) :
f (snoc m (c • x)) = c • f (snoc m x) :=
by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last]
/- If `R` and `M₂` are implicit in the next definition, Lean is never able to infer them, even
given `g` and `f`. Therefore, we make them explicit. -/
variables (R M₂)
/-- If `g` is multilinear and `f` is linear, then `g (f m₁, ..., f mₙ)` is again a multilinear
function, that we call `g.comp_linear_map f`. -/
def comp_linear_map (g : multilinear_map R (λ (i : ι), M₂) M₃) (f : M' →ₗ[R] M₂) :
multilinear_map R (λ (i : ι), M') M₃ :=
{ to_fun := λ m, g (f ∘ m),
add := λ m i x y, by simp [comp_update],
smul := λ m i c x, by simp [comp_update] }
variables {R M₂}
/-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then
the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of
`t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in
`map_add_univ`, although it can be useful in its own right as it does not require the index set `ι`
to be finite.-/
lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) :
f (t.piecewise (m + m') m') = t.powerset.sum (λs, f (s.piecewise m m')) :=
begin
revert m',
refine finset.induction_on t (by simp) _,
assume i t hit Hrec m',
have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) :=
t.piecewise_insert _ _ _,
have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m',
{ ext j,
by_cases h : j = i,
{ rw h, simp [hit] },
{ simp [h] } },
let m'' := update m' i (m i),
have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', hit] },
{ by_cases h' : j ∈ t; simp [h, hit, m'', h'] } },
rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm],
congr' 1,
apply finset.sum_congr rfl (λs hs, _),
have : (insert i s).piecewise m m' = s.piecewise m m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] },
{ by_cases h' : j ∈ s; simp [h, m'', h'] } },
rw this
end
/-- Additivity of a multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) :
f (m + m') = (finset.univ : finset (finset ι)).sum (λs, f (s.piecewise m m')) :=
by simpa using f.map_piecewise_add m m' finset.univ
section apply_sum
variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
open_locale classical
open fintype finset
/-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead
`map_sum_finset`. -/
lemma map_sum_finset_aux {n : ℕ} (h : finset.univ.sum (λ i, (A i).card) = n) :
f (λ i, (A i).sum (g i)) = (pi_finset A).sum (λ r, f (λ i, g i (r i))) :=
begin
unfreezeI,
induction n using nat.strong_induction_on with n IH generalizing A,
-- If one of the sets is empty, then all the sums are zero
by_cases Ai_empty : ∃ i, A i = ∅,
{ rcases Ai_empty with ⟨i, hi⟩,
have : (A i).sum (λ j, g i j) = 0, by convert sum_empty,
rw f.map_coord_zero i this,
have : pi_finset A = ∅,
{ apply finset.eq_empty_of_forall_not_mem (λ r hr, _),
have : r i ∈ A i := mem_pi_finset.mp hr i,
rwa hi at this },
convert sum_empty.symm },
push_neg at Ai_empty,
-- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result
-- is again straightforward
by_cases Ai_singleton : ∀ i, (A i).card ≤ 1,
{ have Ai_card : ∀ i, (A i).card = 1,
{ assume i,
have : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i],
have : finset.card (A i) ≤ 1 := Ai_singleton i,
omega },
have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, (A i).sum (λ j, g i j)),
{ assume r hr,
unfold_coes,
congr,
ext i,
have : ∀ j ∈ A i, g i j = g i (r i),
{ assume j hj,
congr,
apply finset.card_le_one_iff.1 (Ai_singleton i) hj,
exact mem_pi_finset.mp hr i },
simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i,
one_nsmul] },
simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul,
sum_const] },
-- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2.
-- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i`
-- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding
-- parts to get the sum for `A`.
push_neg at Ai_singleton,
obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton,
obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ :=
finset.one_lt_card_iff.1 hi₀,
let B := function.update A i₀ (A i₀ \ {j₂}),
let C := function.update A i₀ {j₂},
have B_subset_A : ∀ i, B i ⊆ A i,
{ assume i,
by_cases hi : i = i₀,
{ rw hi, simp only [B, sdiff_subset, update_same]},
{ simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
have C_subset_A : ∀ i, C i ⊆ A i,
{ assume i,
by_cases hi : i = i₀,
{ rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
-- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity.
have A_eq_BC : (λ i, (A i).sum (g i)) =
function.update (λ i, (A i).sum (g i)) i₀ ((B i₀).sum (g i₀) + (C i₀).sum (g i₀)),
{ ext i,
by_cases hi : i = i₀,
{ rw [hi],
simp only [function.update_same],
have : A i₀ = B i₀ ∪ C i₀,
{ simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union],
symmetry,
simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] },
rw this,
apply finset.sum_union,
apply finset.disjoint_right.2 (λ j hj, _),
have : j = j₂, by { dsimp [C] at hj, simpa using hj },
rw this,
dsimp [B],
simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton,
update_same, and_false] },
{ simp [hi] } },
have Beq : function.update (λ i, (A i).sum (g i)) i₀ ((B i₀).sum (g i₀)) =
(λ i, finset.sum (B i) (g i)),
{ ext i,
by_cases hi : i = i₀,
{ rw hi, simp only [update_same] },
{ simp only [hi, B, update_noteq, ne.def, not_false_iff] } },
have Ceq : function.update (λ i, (A i).sum (g i)) i₀ ((C i₀).sum (g i₀)) =
(λ i, finset.sum (C i) (g i)),
{ ext i,
by_cases hi : i = i₀,
{ rw hi, simp only [update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff] } },
-- Express the inductive assumption for `B`
have Brec : f (λ i, finset.sum (B i) (g i)) = (pi_finset B).sum (λ r, f (λ i, g i (r i))),
{ have : finset.univ.sum (λ i, finset.card (B i)) < finset.univ.sum (λ i, finset.card (A i)),
{ refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i))
⟨i₀, finset.mem_univ _, _⟩,
have : {j₂} ⊆ A i₀, by simp [hj₂],
simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton],
exact nat.pred_lt (ne_of_gt (lt_trans zero_lt_one hi₀)) },
rw h at this,
exact IH _ this B rfl },
-- Express the inductive assumption for `C`
have Crec : f (λ i, finset.sum (C i) (g i)) = (pi_finset C).sum (λ r, f (λ i, g i (r i))),
{ have : finset.univ.sum (λ i, finset.card (C i)) < finset.univ.sum (λ i, finset.card (A i)) :=
finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i))
⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩,
rw h at this,
exact IH _ this C rfl },
have D : disjoint (pi_finset B) (pi_finset C),
{ have : disjoint (B i₀) (C i₀), by simp [B, C],
exact pi_finset_disjoint_of_disjoint B C this },
have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C,
{ apply finset.subset.antisymm,
{ assume r hr,
by_cases hri₀ : r i₀ = j₂,
{ apply finset.mem_union_right,
apply mem_pi_finset.2 (λ i, _),
by_cases hi : i = i₀,
{ have : r i₀ ∈ C i₀, by simp [C, hri₀],
convert this },
{ simp [C, hi, mem_pi_finset.1 hr i] } },
{ apply finset.mem_union_left,
apply mem_pi_finset.2 (λ i, _),
by_cases hi : i = i₀,
{ have : r i₀ ∈ B i₀,
by simp [B, hri₀, mem_pi_finset.1 hr i₀],
convert this },
{ simp [B, hi, mem_pi_finset.1 hr i] } } },
{ exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i))
(pi_finset_subset _ _ (λ i, C_subset_A i)) } },
rw A_eq_BC,
simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC],
rw ← finset.sum_union D,
end
/-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset :
f (λ i, (A i).sum (g i)) = (pi_finset A).sum (λ r, f (λ i, g i (r i))) :=
f.map_sum_finset_aux _ _ rfl
/-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [∀ i, fintype (α i)] :
f (λ i, finset.univ.sum (g i)) = finset.univ.sum (λ (r : Π i, α i), f (λ i, g i (r i))) :=
f.map_sum_finset g (λ i, finset.univ)
end apply_sum
end semiring
section comm_semiring
variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂]
[∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂]
(f f' : multilinear_map R M₁ M₂)
/-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear
map is multiplied by `s.prod c`. This is mainly an auxiliary statement to prove the result when
`s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not
require the index set `ι` to be finite. -/
lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) :
f (s.piecewise (λi, c i • m i) m) = s.prod c • f m :=
begin
refine s.induction_on (by simp) _,
assume j s j_not_mem_s Hrec,
have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) =
s.piecewise (λi, c i • m i) m,
{ ext i,
by_cases h : i = j,
{ rw h, simp [j_not_mem_s] },
{ simp [h] } },
rw [s.piecewise_insert, f.map_smul, A, Hrec],
simp [j_not_mem_s, mul_smul]
end
/-- Multiplicativity of a multilinear map along all coordinates at the same time,
writing `f (λi, c i • m i)` as `univ.prod c • f m`. -/
lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) :
f (λi, c i • m i) = finset.univ.prod c • f m :=
by simpa using map_piecewise_smul f c m finset.univ
instance : has_scalar R (multilinear_map R M₁ M₂) := ⟨λ c f,
⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [smul_smul, mul_comm]⟩⟩
@[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl
variables (R ι)
/-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of
all the `m i` (multiplied by a fixed reference element `z` in the target module) -/
protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ :=
{ to_fun := λm, finset.univ.prod m • z,
add := λ m i x y, by simp [finset.prod_update_of_mem, add_mul, add_smul],
smul := λ m i c x, by { rw [smul_eq_mul], simp [finset.prod_update_of_mem, smul_smul, mul_assoc] } }
variables {R ι}
@[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) :
(multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = finset.univ.prod m • z := rfl
lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) :
multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f :=
begin
ext m,
have : m = (λi, m i • 1), by { ext j, simp },
conv_rhs { rw [this, f.map_smul_univ] },
refl
end
end comm_semiring
section ring
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, semimodule R (M₁ i)] [semimodule R M₂]
(f : multilinear_map R M₁ M₂)
@[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
by { simp only [map_add, add_left_inj, sub_eq_add_neg, (neg_one_smul R y).symm, map_smul], simp }
instance : has_neg (multilinear_map R M₁ M₂) :=
⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : add_comm_group (multilinear_map R M₁ M₂) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp [add_comm, add_left_comm]
end ring
section comm_ring
variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, semimodule R (M₁ i)] [semimodule R M₂]
variables (R ι M₁ M₂)
/-- The space of multilinear maps is a module over `R`, for the pointwise addition and scalar
multiplication. -/
instance semimodule : semimodule R (multilinear_map R M₁ M₂) :=
semimodule.of_core $ by refine { smul := (•), ..};
intros; ext; simp [smul_add, add_smul, smul_smul]
-- This instance should not be needed!
instance semimodule_ring : semimodule R (multilinear_map R (λ (i : ι), R) M₂) :=
multilinear_map.semimodule _ _ (λ (i : ι), R) _
/-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`,
as such a multilinear map is completely determined by its value on the constant vector made of ones.
We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/
protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) :=
{ to_fun := λ z, multilinear_map.mk_pi_ring R ι z,
inv_fun := λ f, f (λi, 1),
add := λ z z', by { ext m, simp [smul_add] },
smul := λ c z, by { ext m, simp [smul_smul, mul_comm] },
left_inv := λ z, by simp,
right_inv := λ f, f.mk_pi_ring_apply_one_eq_self }
end comm_ring
end multilinear_map
namespace linear_map
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃]
[∀i, module R (M₁ i)] [module R M₂] [module R M₃]
/-- Composing a multilinear map with a linear map gives again a multilinear map. -/
def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ :=
{ to_fun := λ m, g (f m),
add := λ m i x y, by simp,
smul := λ m i c x, by simp }
end linear_map
section currying
/-!
### Currying
We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two
curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values
in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n`
variables taking values in linear maps on `E 0`). In both constructions, the variable that is
singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`.
The inverse operations are called `uncurry_left` and `uncurry_right`.
We also register linear equiv versions of these correspondences, in
`multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`.
-/
open multilinear_map
variables {R M M₂}
[comm_ring R] [∀i, add_comm_group (M i)] [add_comm_group M'] [add_comm_group M₂]
[∀i, module R (M i)] [module R M'] [module R M₂]
/-! #### Left currying -/
/-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables,
construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m ↦ f (m 0) (tail m)`-/
def linear_map.uncurry_left
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) :
multilinear_map R M M₂ :=
{ to_fun := λm, f (m 0) (tail m),
add := λm i x y, begin
by_cases h : i = 0,
{ revert x y,
rw h,
assume x y,
rw [update_same, update_same, update_same, f.map_add, add_apply,
tail_update_zero, tail_update_zero, tail_update_zero] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x y,
rw ← succ_pred i h,
assume x y,
rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] }
end,
smul := λm i c x, begin
by_cases h : i = 0,
{ revert x,
rw h,
assume x,
rw [update_same, update_same, tail_update_zero, tail_update_zero,
← smul_apply, f.map_smul] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x,
rw ← succ_pred i h,
assume x,
rw [tail_update_succ, tail_update_succ, map_smul] }
end }
@[simp] lemma linear_map.uncurry_left_apply
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) :
f.uncurry_left m = f (m 0) (tail m) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain
a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/
def multilinear_map.curry_left
(f : multilinear_map R M M₂) :
M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) :=
{ to_fun := λx,
{ to_fun := λm, f (cons x m),
add := λm i y y', by simp,
smul := λm i y c, by simp },
add := λx y, by { ext m, exact cons_add f m x y },
smul := λc x, by { ext m, exact cons_smul f m c x } }
@[simp] lemma multilinear_map.curry_left_apply
(f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) :
f.curry_left x m = f (cons x m) := rfl
@[simp] lemma linear_map.curry_uncurry_left
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) :
f.uncurry_left.curry_left = f :=
begin
ext m x,
simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply],
rw cons_zero
end
@[simp] lemma multilinear_map.uncurry_curry_left
(f : multilinear_map R M M₂) :
f.curry_left.uncurry_left = f :=
by { ext m, simp }
variables (R M M₂)
/-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from `M 0` to the space of multilinear maps on
`Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a
linear isomorphism in `multilinear_curry_left_equiv R M M₂`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_left_equiv :
(M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) :=
{ to_fun := linear_map.uncurry_left,
add := λf₁ f₂, by { ext m, refl },
smul := λc f, by { ext m, refl },
inv_fun := multilinear_map.curry_left,
left_inv := linear_map.curry_uncurry_left,
right_inv := multilinear_map.uncurry_curry_left }
variables {R M M₂}
/-! #### Right currying -/
/-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to
`M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m ↦ f (init m) (m (last n))`-/
def multilinear_map.uncurry_right
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) :
multilinear_map R M M₂ :=
{ to_fun := λm, f (init m) (m (last n)),
add := λm i x y, begin
by_cases h : i.val < n,
{ have : last n ≠ i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this, update_noteq this],
revert x y,
rw [(cast_succ_cast_lt i h).symm],
assume x y,
rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ,
linear_map.add_apply] },
{ revert x y,
rw eq_last_of_not_lt h,
assume x y,
rw [init_update_last, init_update_last, init_update_last,
update_same, update_same, update_same, linear_map.map_add] }
end,
smul := λm i c x, begin
by_cases h : i.val < n,
{ have : last n ≠ i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this],
revert x,
rw [(cast_succ_cast_lt i h).symm],
assume x,
rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] },
{ revert x,
rw eq_last_of_not_lt h,
assume x,
rw [update_same, update_same, init_update_last, init_update_last,
linear_map.map_smul] }
end }
@[simp] lemma multilinear_map.uncurry_right_apply
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) :
f.uncurry_right m = f (init m) (m (last n)) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain
a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by
`m ↦ (x ↦ f (snoc m x))`. -/
def multilinear_map.curry_right (f : multilinear_map R M M₂) :
multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) :=
{ to_fun := λm,
{ to_fun := λx, f (snoc m x),
add := λx y, by rw f.snoc_add,
smul := λc x, by rw f.snoc_smul },
add := λm i x y, begin
ext z,
change f (snoc (update m i (x + y)) z)
= f (snoc (update m i x) z) + f (snoc (update m i y) z),
rw [snoc_update, snoc_update, snoc_update, f.map_add]
end,
smul := λm i c x, begin
ext z,
change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z),
rw [snoc_update, snoc_update, f.map_smul]
end }
@[simp] lemma multilinear_map.curry_right_apply
(f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) :
f.curry_right m x = f (snoc m x) := rfl
@[simp] lemma multilinear_map.curry_uncurry_right
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) :
f.uncurry_right.curry_right = f :=
begin
ext m x,
simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply],
rw init_snoc
end
@[simp] lemma multilinear_map.uncurry_curry_right
(f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f :=
by { ext m, simp }
variables (R M M₂)
/-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the
space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism
as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_right_equiv :
(multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))
≃ₗ[R] (multilinear_map R M M₂) :=
{ to_fun := multilinear_map.uncurry_right,
add := λf₁ f₂, by { ext m, refl },
smul := λc f, by { ext m, rw [smul_apply], refl },
inv_fun := multilinear_map.curry_right,
left_inv := multilinear_map.curry_uncurry_right,
right_inv := multilinear_map.uncurry_curry_right }
end currying
|
a12842ecc0c06aee37f392f8f8ed86856ef25a41 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/control/ulift.lean | 8c228a6ce1890df8200e8bf8640edb81cd088c4c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,992 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Jannis Limperg
-/
/-!
# Monadic instances for `ulift` and `plift`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/638
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `monad` and `is_lawful_monad` instances on `plift` and `ulift`. -/
universes u v
namespace plift
variables {α : Sort u} {β : Sort v}
/-- Functorial action. -/
protected def map (f : α → β) (a : plift α) : plift β :=
plift.up (f a.down)
@[simp] lemma map_up (f : α → β) (a : α) : (plift.up a).map f = plift.up (f a) := rfl
/-- Embedding of pure values. -/
@[simp] protected def pure : α → plift α := up
/-- Applicative sequencing. -/
protected def seq (f : plift (α → β)) (x : plift α) : plift β :=
plift.up (f.down x.down)
@[simp] lemma seq_up (f : α → β) (x : α) : (plift.up f).seq (plift.up x) = plift.up (f x) := rfl
/-- Monadic bind. -/
protected def bind (a : plift α) (f : α → plift β) : plift β := f a.down
@[simp] lemma bind_up (a : α) (f : α → plift β) : (plift.up a).bind f = f a := rfl
instance : monad plift :=
{ map := @plift.map,
pure := @plift.pure,
seq := @plift.seq,
bind := @plift.bind }
instance : is_lawful_functor plift :=
{ id_map := λ α ⟨x⟩, rfl,
comp_map := λ α β γ g h ⟨x⟩, rfl }
instance : is_lawful_applicative plift :=
{ pure_seq_eq_map := λ α β g ⟨x⟩, rfl,
map_pure := λ α β g x, rfl,
seq_pure := λ α β ⟨g⟩ x, rfl,
seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl }
instance : is_lawful_monad plift :=
{ bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl,
bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl,
pure_bind := λ α β x f, rfl,
bind_assoc := λ α β γ ⟨x⟩ f g, rfl }
@[simp] lemma rec.constant {α : Sort u} {β : Type v} (b : β) :
@plift.rec α (λ _, β) (λ _, b) = λ _, b :=
funext (λ x, plift.cases_on x (λ a, eq.refl (plift.rec (λ a', b) {down := a})))
end plift
namespace ulift
variables {α : Type u} {β : Type v}
/-- Functorial action. -/
protected def map (f : α → β) (a : ulift α) : ulift β :=
ulift.up (f a.down)
@[simp] lemma map_up (f : α → β) (a : α) : (ulift.up a).map f = ulift.up (f a) := rfl
/-- Embedding of pure values. -/
@[simp] protected def pure : α → ulift α := up
/-- Applicative sequencing. -/
protected def seq (f : ulift (α → β)) (x : ulift α) : ulift β :=
ulift.up (f.down x.down)
@[simp] lemma seq_up (f : α → β) (x : α) : (ulift.up f).seq (ulift.up x) = ulift.up (f x) := rfl
/-- Monadic bind. -/
protected def bind (a : ulift α) (f : α → ulift β) : ulift β := f a.down
@[simp] lemma bind_up (a : α) (f : α → ulift β) : (ulift.up a).bind f = f a := rfl
instance : monad ulift :=
{ map := @ulift.map,
pure := @ulift.pure,
seq := @ulift.seq,
bind := @ulift.bind }
instance : is_lawful_functor ulift :=
{ id_map := λ α ⟨x⟩, rfl,
comp_map := λ α β γ g h ⟨x⟩, rfl }
instance : is_lawful_applicative ulift :=
{ to_is_lawful_functor := ulift.is_lawful_functor,
pure_seq_eq_map := λ α β g ⟨x⟩, rfl,
map_pure := λ α β g x, rfl,
seq_pure := λ α β ⟨g⟩ x, rfl,
seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl }
instance : is_lawful_monad ulift :=
{ bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl,
bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl,
pure_bind := λ α β x f,
by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl },
bind_assoc := λ α β γ ⟨x⟩ f g,
by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } }
@[simp] lemma rec.constant {α : Type u} {β : Sort v} (b : β) :
@ulift.rec α (λ _, β) (λ _, b) = λ _, b :=
funext (λ x, ulift.cases_on x (λ a, eq.refl (ulift.rec (λ a', b) {down := a})))
end ulift
|
4351e2655812007c531d0f1e2c81d797517a1789 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/order/directed.lean | 8468aa61c0e8729a2d4facfee758d28c6031c143 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 8,131 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.set.basic
import order.lattice
import order.max
/-!
# Directed indexed families and sets
This file defines directed indexed families and directed sets. An indexed family/set is
directed iff each pair of elements has a shared upper bound.
## Main declarations
* `directed r f`: Predicate stating that the indexed family `f` is `r`-directed.
* `directed_on r s`: Predicate stating that the set `s` is `r`-directed.
* `is_directed α r`: Prop-valued mixin stating that `α` is `r`-directed. Follows the style of the
unbundled relation classes such as `is_total`.
-/
open function
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w} (r s : α → α → Prop)
local infix ` ≼ ` : 50 := r
/-- A family of elements of α is directed (with respect to a relation `≼` on α)
if there is a member of the family `≼`-above any pair in the family. -/
def directed (f : ι → α) := ∀ x y, ∃ z, f x ≼ f z ∧ f y ≼ f z
/-- A subset of α is directed if there is an element of the set `≼`-above any
pair of elements in the set. -/
def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃ z ∈ s, x ≼ z ∧ y ≼ z
variables {r}
theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) :=
by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl)
alias directed_on_iff_directed ↔ directed_on.directed_coe _
theorem directed_on_image {s} {f : β → α} :
directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s :=
by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage]
theorem directed_on.mono {s : set α} (h : directed_on r s)
{r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) :
directed_on r' s :=
λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩
theorem directed_comp {ι} {f : ι → β} {g : β → α} :
directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl
theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α}
(H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f :=
λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩
theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α}
(hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) :
directed rb (g ∘ f) :=
directed_comp.2 $ hf.mono hg
/-- A monotone function on a sup-semilattice is directed. -/
lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop}
(H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f :=
λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩
lemma monotone.directed_le [semilattice_sup α] [preorder β] {f : α → β} :
monotone f → directed (≤) f :=
directed_of_sup
/-- A set stable by supremum is `≤`-directed. -/
lemma directed_on_of_sup_mem [semilattice_sup α] {S : set α}
(H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊔ j ∈ S) : directed_on (≤) S :=
λ a ha b hb, ⟨a ⊔ b, H ha hb, le_sup_left, le_sup_right⟩
lemma directed.extend_bot [preorder α] [order_bot α] {e : ι → β} {f : ι → α}
(hf : directed (≤) f) (he : function.injective e) :
directed (≤) (function.extend e f ⊥) :=
begin
intros a b,
rcases (em (∃ i, e i = a)).symm with ha | ⟨i, rfl⟩,
{ use b, simp [function.extend_apply' _ _ _ ha] },
rcases (em (∃ i, e i = b)).symm with hb | ⟨j, rfl⟩,
{ use e i, simp [function.extend_apply' _ _ _ hb] },
rcases hf i j with ⟨k, hi, hj⟩,
use (e k),
simp only [function.extend_apply he, *, true_and]
end
/-- An antitone function on an inf-semilattice is directed. -/
lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β}
(hf : ∀ a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f :=
λ x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩
/-- A set stable by infimum is `≥`-directed. -/
lemma directed_on_of_inf_mem [semilattice_inf α] {S : set α}
(H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊓ j ∈ S) : directed_on (≥) S :=
λ a ha b hb, ⟨a ⊓ b, H ha hb, inf_le_left, inf_le_right⟩
/-- `is_directed α r` states that for any elements `a`, `b` there exists an element `c` such that
`r a c` and `r b c`. -/
class is_directed (α : Type*) (r : α → α → Prop) : Prop :=
(directed (a b : α) : ∃ c, r a c ∧ r b c)
lemma directed_of (r : α → α → Prop) [is_directed α r] (a b : α) : ∃ c, r a c ∧ r b c :=
is_directed.directed _ _
lemma directed_id [is_directed α r] : directed r id := by convert directed_of r
lemma directed_id_iff : directed r id ↔ is_directed α r := ⟨λ h, ⟨h⟩, @directed_id _ _⟩
lemma directed_on_univ [is_directed α r] : directed_on r set.univ :=
λ a _ b _, let ⟨c, hc⟩ := directed_of r a b in ⟨c, trivial, hc⟩
lemma directed_on_univ_iff : directed_on r set.univ ↔ is_directed α r :=
⟨λ h, ⟨λ a b, let ⟨c, _, hc⟩ := h a trivial b trivial in ⟨c, hc⟩⟩, @directed_on_univ _ _⟩
@[priority 100] -- see Note [lower instance priority]
instance is_total.to_is_directed [is_total α r] : is_directed α r :=
⟨λ a b, or.cases_on (total_of r a b) (λ h, ⟨b, h, refl _⟩) (λ h, ⟨a, refl _, h⟩)⟩
lemma is_directed_mono [is_directed α r] (h : ∀ ⦃a b⦄, r a b → s a b) : is_directed α s :=
⟨λ a b, let ⟨c, ha, hb⟩ := is_directed.directed a b in ⟨c, h ha, h hb⟩⟩
lemma exists_ge_ge [has_le α] [is_directed α (≤)] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c :=
directed_of (≤) a b
lemma exists_le_le [has_le α] [is_directed α (≥)] (a b : α) : ∃ c, c ≤ a ∧ c ≤ b :=
directed_of (≥) a b
instance order_dual.is_directed_ge [has_le α] [is_directed α (≤)] : is_directed αᵒᵈ (≥) :=
by assumption
instance order_dual.is_directed_le [has_le α] [is_directed α (≥)] : is_directed αᵒᵈ (≤) :=
by assumption
section preorder
variables [preorder α] {a : α}
protected lemma is_min.is_bot [is_directed α (≥)] (h : is_min a) : is_bot a :=
λ b, let ⟨c, hca, hcb⟩ := exists_le_le a b in (h hca).trans hcb
protected lemma is_max.is_top [is_directed α (≤)] (h : is_max a) : is_top a :=
h.to_dual.is_bot
lemma is_top_or_exists_gt [is_directed α (≤)] (a : α) : is_top a ∨ (∃ b, a < b) :=
(em (is_max a)).imp is_max.is_top not_is_max_iff.mp
lemma is_bot_or_exists_lt [is_directed α (≥)] (a : α) : is_bot a ∨ (∃ b, b < a) :=
@is_top_or_exists_gt αᵒᵈ _ _ a
lemma is_bot_iff_is_min [is_directed α (≥)] : is_bot a ↔ is_min a :=
⟨is_bot.is_min, is_min.is_bot⟩
lemma is_top_iff_is_max [is_directed α (≤)] : is_top a ↔ is_max a := ⟨is_top.is_max, is_max.is_top⟩
variables (β) [partial_order β]
theorem exists_lt_of_directed_ge [is_directed β (≥)] [nontrivial β] : ∃ a b : β, a < b :=
begin
rcases exists_pair_ne β with ⟨a, b, hne⟩,
rcases is_bot_or_exists_lt a with ha|⟨c, hc⟩,
exacts [⟨a, b, (ha b).lt_of_ne hne⟩, ⟨_, _, hc⟩]
end
theorem exists_lt_of_directed_le [is_directed β (≤)] [nontrivial β] : ∃ a b : β, a < b :=
let ⟨a, b, h⟩ := exists_lt_of_directed_ge βᵒᵈ in ⟨b, a, h⟩
end preorder
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup.to_is_directed_le [semilattice_sup α] : is_directed α (≤) :=
⟨λ a b, ⟨a ⊔ b, le_sup_left, le_sup_right⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf.to_is_directed_ge [semilattice_inf α] : is_directed α (≥) :=
⟨λ a b, ⟨a ⊓ b, inf_le_left, inf_le_right⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance order_top.to_is_directed_le [has_le α] [order_top α] : is_directed α (≤) :=
⟨λ a b, ⟨⊤, le_top, le_top⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance order_bot.to_is_directed_ge [has_le α] [order_bot α] : is_directed α (≥) :=
⟨λ a b, ⟨⊥, bot_le, bot_le⟩⟩
|
4346feb84850b92d76dbbca693658416fdd58f8e | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/combinatorics/simple_graph/degree_sum.lean | 9d874fffb28b34f8faba40db246cf6963927b3b4 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,295 | lean | /-
Copyright (c) 2020 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import combinatorics.simple_graph.basic
import algebra.big_operators.basic
import data.nat.parity
import data.zmod.parity
/-!
# Degree-sum formula and handshaking lemma
The degree-sum formula is that the sum of the degrees of the vertices in
a finite graph is equal to twice the number of edges. The handshaking lemma,
a corollary, is that the number of odd-degree vertices is even.
## Main definitions
- A `dart` is a directed edge, consisting of an ordered pair of adjacent vertices,
thought of as being a directed edge.
- `simple_graph.sum_degrees_eq_twice_card_edges` is the degree-sum formula.
- `simple_graph.even_card_odd_degree_vertices` is the handshaking lemma.
- `simple_graph.odd_card_odd_degree_vertices_ne` is that the number of odd-degree
vertices different from a given odd-degree vertex is odd.
- `simple_graph.exists_ne_odd_degree_of_exists_odd_degree` is that the existence of an
odd-degree vertex implies the existence of another one.
## Implementation notes
We give a combinatorial proof by using the facts that (1) the map from
darts to vertices is such that each fiber has cardinality the degree
of the corresponding vertex and that (2) the map from darts to edges is 2-to-1.
## Tags
simple graphs, sums, degree-sum formula, handshaking lemma
-/
open finset
open_locale big_operators
namespace simple_graph
universes u
variables {V : Type u} (G : simple_graph V)
/-- A dart is a directed edge, consisting of an ordered pair of adjacent vertices. -/
@[ext, derive decidable_eq]
structure dart :=
(fst snd : V)
(is_adj : G.adj fst snd)
instance dart.fintype [fintype V] [decidable_rel G.adj] : fintype G.dart :=
fintype.of_equiv (Σ v, G.neighbor_set v)
{ to_fun := λ s, ⟨s.fst, s.snd, s.snd.property⟩,
inv_fun := λ d, ⟨d.fst, d.snd, d.is_adj⟩,
left_inv := λ s, by ext; simp,
right_inv := λ d, by ext; simp }
variables {G}
/-- The edge associated to the dart. -/
def dart.edge (d : G.dart) : sym2 V := ⟦(d.fst, d.snd)⟧
@[simp] lemma dart.edge_mem (d : G.dart) : d.edge ∈ G.edge_set :=
d.is_adj
/-- The dart with reversed orientation from a given dart. -/
def dart.rev (d : G.dart) : G.dart :=
⟨d.snd, d.fst, G.symm d.is_adj⟩
@[simp] lemma dart.rev_edge (d : G.dart) : d.rev.edge = d.edge :=
sym2.eq_swap
@[simp] lemma dart.rev_rev (d : G.dart) : d.rev.rev = d :=
dart.ext _ _ rfl rfl
@[simp] lemma dart.rev_involutive : function.involutive (dart.rev : G.dart → G.dart) :=
dart.rev_rev
lemma dart.rev_ne (d : G.dart) : d.rev ≠ d :=
begin
cases d with f s h,
simp only [dart.rev, not_and, ne.def],
rintro rfl,
exact false.elim (G.loopless _ h),
end
lemma dart_edge_eq_iff (d₁ d₂ : G.dart) :
d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.rev :=
begin
cases d₁ with s₁ t₁ h₁,
cases d₂ with s₂ t₂ h₂,
simp only [dart.edge, dart.rev_edge, dart.rev],
rw sym2.eq_iff,
end
variables (G)
/-- For a given vertex `v`, this is the bijective map from the neighbor set at `v`
to the darts `d` with `d.fst = v`. --/
def dart_of_neighbor_set (v : V) (w : G.neighbor_set v) : G.dart :=
⟨v, w, w.property⟩
lemma dart_of_neighbor_set_injective (v : V) : function.injective (G.dart_of_neighbor_set v) :=
λ e₁ e₂ h, by { injection h with h₁ h₂, exact subtype.ext h₂ }
instance dart.inhabited [inhabited V] [inhabited (G.neighbor_set (default _))] :
inhabited G.dart := ⟨G.dart_of_neighbor_set (default _) (default _)⟩
section degree_sum
variables [fintype V] [decidable_rel G.adj]
lemma dart_fst_fiber [decidable_eq V] (v : V) :
univ.filter (λ d : G.dart, d.fst = v) = univ.image (G.dart_of_neighbor_set v) :=
begin
ext d,
simp only [mem_image, true_and, mem_filter, set_coe.exists, mem_univ, exists_prop_of_true],
split,
{ rintro rfl,
exact ⟨_, d.is_adj, dart.ext _ _ rfl rfl⟩, },
{ rintro ⟨e, he, rfl⟩,
refl, },
end
lemma dart_fst_fiber_card_eq_degree [decidable_eq V] (v : V) :
(univ.filter (λ d : G.dart, d.fst = v)).card = G.degree v :=
begin
have hh := card_image_of_injective univ (G.dart_of_neighbor_set_injective v),
rw [finset.card_univ, card_neighbor_set_eq_degree] at hh,
rwa dart_fst_fiber,
end
lemma dart_card_eq_sum_degrees : fintype.card G.dart = ∑ v, G.degree v :=
begin
haveI h : decidable_eq V, { classical, apply_instance },
simp only [←card_univ, ←dart_fst_fiber_card_eq_degree],
exact card_eq_sum_card_fiberwise (by simp),
end
variables {G} [decidable_eq V]
lemma dart.edge_fiber (d : G.dart) :
(univ.filter (λ (d' : G.dart), d'.edge = d.edge)) = {d, d.rev} :=
finset.ext (λ d', by simpa using dart_edge_eq_iff d' d)
variables (G)
lemma dart_edge_fiber_card (e : sym2 V) (h : e ∈ G.edge_set) :
(univ.filter (λ (d : G.dart), d.edge = e)).card = 2 :=
begin
refine quotient.ind (λ p h, _) e h,
cases p with v w,
let d : G.dart := ⟨v, w, h⟩,
convert congr_arg card d.edge_fiber,
rw [card_insert_of_not_mem, card_singleton],
rw [mem_singleton],
exact d.rev_ne.symm,
end
lemma dart_card_eq_twice_card_edges : fintype.card G.dart = 2 * G.edge_finset.card :=
begin
rw ←card_univ,
rw @card_eq_sum_card_fiberwise _ _ _ dart.edge _ G.edge_finset
(λ d h, by { rw mem_edge_finset, apply dart.edge_mem }),
rw [←mul_comm, sum_const_nat],
intros e h,
apply G.dart_edge_fiber_card e,
rwa ←mem_edge_finset,
end
/-- The degree-sum formula. This is also known as the handshaking lemma, which might
more specifically refer to `simple_graph.even_card_odd_degree_vertices`. -/
theorem sum_degrees_eq_twice_card_edges : ∑ v, G.degree v = 2 * G.edge_finset.card :=
G.dart_card_eq_sum_degrees.symm.trans G.dart_card_eq_twice_card_edges
end degree_sum
/-- The handshaking lemma. See also `simple_graph.sum_degrees_eq_twice_card_edges`. -/
theorem even_card_odd_degree_vertices [fintype V] [decidable_rel G.adj] :
even (univ.filter (λ v, odd (G.degree v))).card :=
begin
classical,
have h := congr_arg ((λ n, ↑n) : ℕ → zmod 2) G.sum_degrees_eq_twice_card_edges,
simp only [zmod.nat_cast_self, zero_mul, nat.cast_mul] at h,
rw [nat.cast_sum, ←sum_filter_ne_zero] at h,
rw @sum_congr _ _ _ _ (λ v, (G.degree v : zmod 2)) (λ v, (1 : zmod 2)) _ rfl at h,
{ simp only [filter_congr_decidable, mul_one, nsmul_eq_mul, sum_const, ne.def] at h,
rw ←zmod.eq_zero_iff_even,
convert h,
ext v,
rw ←zmod.ne_zero_iff_odd,
congr' },
{ intros v,
simp only [true_and, mem_filter, mem_univ, ne.def],
rw [zmod.eq_zero_iff_even, zmod.eq_one_iff_odd, nat.odd_iff_not_even, imp_self],
trivial }
end
lemma odd_card_odd_degree_vertices_ne [fintype V] [decidable_eq V] [decidable_rel G.adj]
(v : V) (h : odd (G.degree v)) :
odd (univ.filter (λ w, w ≠ v ∧ odd (G.degree w))).card :=
begin
rcases G.even_card_odd_degree_vertices with ⟨k, hg⟩,
have hk : 0 < k,
{ have hh : (filter (λ (v : V), odd (G.degree v)) univ).nonempty,
{ use v,
simp only [true_and, mem_filter, mem_univ],
use h, },
rwa [←card_pos, hg, zero_lt_mul_left] at hh,
exact zero_lt_two, },
have hc : (λ (w : V), w ≠ v ∧ odd (G.degree w)) = (λ (w : V), odd (G.degree w) ∧ w ≠ v),
{ ext w,
rw and_comm, },
simp only [hc, filter_congr_decidable],
rw [←filter_filter, filter_ne', card_erase_of_mem],
{ use k - 1,
rw [nat.pred_eq_succ_iff, hg, mul_tsub, tsub_add_eq_add_tsub, eq_comm,
tsub_eq_iff_eq_add_of_le],
{ ring },
{ exact add_le_add_right (zero_le _) 2 },
{ exact nat.mul_le_mul_left _ hk } },
{ simpa only [true_and, mem_filter, mem_univ] },
end
lemma exists_ne_odd_degree_of_exists_odd_degree [fintype V] [decidable_rel G.adj]
(v : V) (h : odd (G.degree v)) :
∃ (w : V), w ≠ v ∧ odd (G.degree w) :=
begin
haveI : decidable_eq V, { classical, apply_instance },
rcases G.odd_card_odd_degree_vertices_ne v h with ⟨k, hg⟩,
have hg' : (filter (λ (w : V), w ≠ v ∧ odd (G.degree w)) univ).card > 0,
{ rw hg,
apply nat.succ_pos, },
rcases card_pos.mp hg' with ⟨w, hw⟩,
simp only [true_and, mem_filter, mem_univ, ne.def] at hw,
exact ⟨w, hw⟩,
end
end simple_graph
|
feb4f2c6096b979c740355bd68604ff74b238120 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/check_failure.lean | c71b78ec9b4cba00ec9bf0a85ddd1d04effd743d | [
"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 | 109 | lean | -- #check_failure should not ignore stuck TC problems.
#check_failure (inferInstance : Inhabited (Nat × _))
|
0fa0e341e1f94e4841bfaff85251cbb5cde8a425 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Data/FormatMacro.lean | bd30c8ba6c3e1c990582774636796b79a222b8b4 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 360 | 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.Data.Format
namespace Lean
syntax:max "f!" interpolatedStr(term) : term
macro_rules
| `(f! $interpStr) => do interpStr.expandInterpolatedStr (← `(Format)) (← `(fmt))
end Lean
|
48b45f14a8af1c31cec117c124a1a153827226a7 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Init/System/IOError.lean | 63ad083a02c17a60120ad0ac636911934f2477a7 | [
"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 | 8,947 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
prelude
import Init.Core
import Init.Data.UInt
import Init.Data.ToString.Basic
import Init.Data.String.Basic
/--
Imitate the structure of IOErrorType in Haskell:
https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Error.html#t:IOErrorType
-/
inductive IO.Error where
| alreadyExists (filename : Option String) (osCode : UInt32) (details : String) -- EEXIST, EINPROGRESS, EISCONN
| otherError (osCode : UInt32) (details : String) -- EFAULT, default
| resourceBusy (osCode : UInt32) (details : String)
-- EADDRINUSE, EBUSY, EDEADLK, ETXTBSY
| resourceVanished (osCode : UInt32) (details : String)
-- ECONNRESET, EIDRM, ENETDOWN, ENETRESET,
-- ENOLINK, EPIPE
| unsupportedOperation (osCode : UInt32) (details : String)
-- EADDRNOTAVAIL, EAFNOSUPPORT, ENODEV, ENOPROTOOPT
-- ENOSYS, EOPNOTSUPP, ERANGE, ESPIPE, EXDEV
| hardwareFault (osCode : UInt32) (details : String) -- EIO
| unsatisfiedConstraints (osCode : UInt32) (details : String) -- ENOTEMPTY
| illegalOperation (osCode : UInt32) (details : String) -- ENOTTY
| protocolError (osCode : UInt32) (details : String)
-- EPROTO, EPROTONOSUPPORT, EPROTOTYPE
| timeExpired (osCode : UInt32) (details : String)
-- ETIME, ETIMEDOUT
| interrupted (filename : String) (osCode : UInt32) (details : String) -- EINTR
| noFileOrDirectory (filename : String) (osCode : UInt32) (details : String) -- ENOENT
| invalidArgument (filename : Option String) (osCode : UInt32) (details : String)
-- ELOOP, ENAMETOOLONG, EDESTADDRREQ, EILSEQ, EINVAL, EDOM, EBADF
-- ENOEXEC, ENOSTR, ENOTCONN, ENOTSOCK
| permissionDenied (filename : Option String) (osCode : UInt32) (details : String)
-- EACCES, EROFS, ECONNABORTED, EFBIG, EPERM
| resourceExhausted (filename : Option String) (osCode : UInt32) (details : String)
-- EMFILE, ENFILE, ENOSPC, E2BIG, EAGAIN, EMLINK:
-- EMSGSIZE, ENOBUFS, ENOLCK, ENOMEM, ENOSR:
| inappropriateType (filename : Option String) (osCode : UInt32) (details : String)
-- EISDIR, EBADMSG, ENOTDIR:
| noSuchThing (filename : Option String) (osCode : UInt32) (details : String)
-- ENXIO, EHOSTUNREACH, ENETUNREACH, ECHILD, ECONNREFUSED,
-- ENODATA, ENOMSG, ESRCH
| unexpectedEof
| userError (msg : String)
deriving Inhabited
@[export lean_mk_io_user_error]
def IO.userError (s : String) : IO.Error :=
IO.Error.userError s
instance : Coe String IO.Error := ⟨IO.userError⟩
namespace IO.Error
@[export lean_mk_io_error_already_exists_file]
def mkAlreadyExistsFile : String → UInt32 → String → IO.Error :=
alreadyExists ∘ some
@[export lean_mk_io_error_eof]
def mkEofError : Unit → IO.Error := fun _ =>
unexpectedEof
@[export lean_mk_io_error_inappropriate_type_file]
def mkInappropriateTypeFile : String → UInt32 → String → IO.Error :=
inappropriateType ∘ some
@[export lean_mk_io_error_interrupted]
def mkInterrupted : String → UInt32 → String → IO.Error :=
interrupted
@[export lean_mk_io_error_invalid_argument_file]
def mkInvalidArgumentFile : String → UInt32 → String → IO.Error :=
invalidArgument ∘ some
@[export lean_mk_io_error_no_file_or_directory]
def mkNoFileOrDirectory : String → UInt32 → String → IO.Error :=
noFileOrDirectory
@[export lean_mk_io_error_no_such_thing_file]
def mkNoSuchThingFile : String → UInt32 → String → IO.Error :=
noSuchThing ∘ some
@[export lean_mk_io_error_permission_denied_file]
def mkPermissionDeniedFile : String → UInt32 → String → IO.Error :=
permissionDenied ∘ some
@[export lean_mk_io_error_resource_exhausted_file]
def mkResourceExhaustedFile : String → UInt32 → String → IO.Error :=
resourceExhausted ∘ some
@[export lean_mk_io_error_unsupported_operation]
def mkUnsupportedOperation : UInt32 → String → IO.Error :=
unsupportedOperation
@[export lean_mk_io_error_resource_exhausted]
def mkResourceExhausted : UInt32 → String → IO.Error :=
resourceExhausted none
@[export lean_mk_io_error_already_exists]
def mkAlreadyExists : UInt32 → String → IO.Error :=
alreadyExists none
@[export lean_mk_io_error_inappropriate_type]
def mkInappropriateType : UInt32 → String → IO.Error :=
inappropriateType none
@[export lean_mk_io_error_no_such_thing]
def mkNoSuchThing : UInt32 → String → IO.Error :=
noSuchThing none
@[export lean_mk_io_error_resource_vanished]
def mkResourceVanished : UInt32 → String → IO.Error :=
resourceVanished
@[export lean_mk_io_error_resource_busy]
def mkResourceBusy : UInt32 → String → IO.Error :=
resourceBusy
@[export lean_mk_io_error_invalid_argument]
def mkInvalidArgument : UInt32 → String → IO.Error :=
invalidArgument none
@[export lean_mk_io_error_other_error]
def mkOtherError : UInt32 → String → IO.Error :=
otherError
@[export lean_mk_io_error_permission_denied]
def mkPermissionDenied : UInt32 → String → IO.Error :=
permissionDenied none
@[export lean_mk_io_error_hardware_fault]
def mkHardwareFault : UInt32 → String → IO.Error :=
hardwareFault
@[export lean_mk_io_error_unsatisfied_constraints]
def mkUnsatisfiedConstraints : UInt32 → String → IO.Error :=
unsatisfiedConstraints
@[export lean_mk_io_error_illegal_operation]
def mkIllegalOperation : UInt32 → String → IO.Error :=
illegalOperation
@[export lean_mk_io_error_protocol_error]
def mkProtocolError : UInt32 → String → IO.Error :=
protocolError
@[export lean_mk_io_error_time_expired]
def mkTimeExpired : UInt32 → String → IO.Error :=
timeExpired
private def downCaseFirst (s : String) : String := s.modify 0 Char.toLower
def fopenErrorToString (gist fn : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")\n file: " ++ fn
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")\n file: " ++ fn
def otherErrorToString (gist : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")"
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")"
@[export lean_io_error_to_string]
def toString : IO.Error → String
| unexpectedEof => "end of file"
| inappropriateType (some fn) code details => fopenErrorToString "inappropriate type" fn code details
| inappropriateType none code details => otherErrorToString "inappropriate type" code details
| interrupted fn code details => fopenErrorToString "interrupted system call" fn code details
| invalidArgument (some fn) code details => fopenErrorToString "invalid argument" fn code details
| invalidArgument none code details => otherErrorToString "invalid argument" code details
| noFileOrDirectory fn code _ => fopenErrorToString "no such file or directory" fn code none
| noSuchThing (some fn) code details => fopenErrorToString "no such thing" fn code details
| noSuchThing none code details => otherErrorToString "no such thing" code details
| permissionDenied (some fn) code details => fopenErrorToString details fn code none
| permissionDenied none code details => otherErrorToString details code none
| resourceExhausted (some fn) code details => fopenErrorToString "resource exhausted" fn code details
| resourceExhausted none code details => otherErrorToString "resource exhausted" code details
| alreadyExists none code details => otherErrorToString "already exists" code details
| alreadyExists (some fn) code details => fopenErrorToString "already exists" fn code details
| otherError code details => otherErrorToString details code none
| resourceBusy code details => otherErrorToString "resource busy" code details
| resourceVanished code details => otherErrorToString "resource vanished" code details
| hardwareFault code _ => otherErrorToString "hardware fault" code none
| illegalOperation code details => otherErrorToString "illegal operation" code details
| protocolError code details => otherErrorToString "protocol error" code details
| timeExpired code details => otherErrorToString "time expired" code details
| unsatisfiedConstraints code _ => otherErrorToString "directory not empty" code none
| unsupportedOperation code details => otherErrorToString "unsupported operation" code details
| userError msg => msg
instance : ToString IO.Error := ⟨ IO.Error.toString ⟩
end IO.Error
|
52d6e22ad812b320da02fdbeaa30230d578c39f4 | d8820d2c92be8052d13f9c8f8c483a6e15c5f566 | /src/M40001/M40001_C2.lean | 4f0b36dff656e3e33c45375194b8726b9788b3d5 | [] | no_license | JasonKYi/M4000x_LEAN_formalisation | 4a19b84f6d0fe2e214485b8532e21cd34996c4b1 | 6e99793f2fcbe88596e27644f430e46aa2a464df | refs/heads/master | 1,599,755,414,708 | 1,589,494,604,000 | 1,589,494,604,000 | 221,759,483 | 8 | 1 | null | 1,589,494,605,000 | 1,573,755,201,000 | Lean | UTF-8 | Lean | false | false | 24,638 | lean | -- begin header
import M40001.M40001_C1
import data.real.basic
namespace M40001
open function
universe u
-- end header
/- Section
Functions
-/
/- Sub-section
2.2.1 Function Composition
-/
/- Definition
Given two functions $f : A → B$, $g : B → C$ where $A, B, C$ are sets, then $(g ∘ f)(x)$ (the composition of $g$ and $f$) is $g(f(x))$.
-/
def my_composition {A B C : Type u} (f : A → B) (g : B → C) := λ x : A, g (f x)
/-
Remark. Here, to define $\tt{my\\_composition}$ we used something called lambda abstraction $\tt{λ x : A, g (f x)}$.
This is essentially saying we are mapping $\tt{x}$ with type $\tt{A}$ to $\tt{g(f(x))}$.
Read more about lambda abstraction <a href = "shorturl.at/hGPX1">here</a> or <a href = "https://en.wikipedia.org/wiki/Lambda_calculus">here</a>.
-/
/- Sub-section
2.3 Injectivity, Surjectivity and Bijectivity
-/
/- Definition
A function $f : X → Y$ is called injective if distinct elements of $X$ get mapped to distinct elements of $Y$. More formally, $f$ is injective if $∀ a, b ∈ X, f(a) = f(b) ⇒ a = b$.
-/
def my_injective {X Y : Type u} (f : X → Y) := ∀ a b : X, f(a) = f(b) → a = b
/- Definition
A function $f : X → Y$ is called surjective if every element of $Y$ gets "hit" by $f$. More formally, $f$ is surjective if $∀ y ∈ Y, ∃ x ∈ X$ such that $f(x) = y$.
-/
def my_surjective {X Y : Type u} (f : X → Y) := ∀ y : Y, ∃ x : X, f(x) = y
/- Definition
A function $f : X → Y$ is called bijective if it is both injective and surjective.
-/
def my_bijective {X Y : Type u} (f : X → Y) := injective f ∧ surjective f
/-
Remark. Although we have defined some lovely properties for our functions, it turns out that these definitions are already defined in the LEAN maths library.
So while our effort might be wasted, we can now use some theorems already written without going through them ourselves!
-/
/- Section
Bijectivity and Composition
-/
/-Theorem
Let $f : X → Y$ and $g : Y → Z$ be functions, then if $f$ and $g$ are both injective, then so is $g ∘ f$.
-/
theorem both_injective
(X Y Z : Type u) (f : X → Y) (g : Y → Z) : injective f ∧ injective g → injective (g ∘ f) :=
begin
-- Suppose that $f$ and $g$ are injective functions, we need to show that $g ∘ f$ is also injective, i.e. if $(g ∘ f)(a) = (g ∘ f)(b)$, then $a = b$.
intros h a b ha,
-- Since $g$ is injective, we have $f(a) = f(b)$.
apply h.left,
-- Similarly, since $f$ is injective, $a = b$, which is exactly what we wanted!
apply h.right,
assumption
end
/-
Remark. Notice that in step 2, LEAN knew that by definition, $(g ∘ f)(x) = g(f(x))$, so we have $g (f(a)) = g (f(b))$, how smart is that!
-/
/-Theorem
Let $f : X → Y$ and $g : Y → Z$ be functions, then if $f$ and $g$ are both surjective, then so is $g ∘ f$.
-/
theorem both_surjective
(X Y Z : Type u) (f : X → Y) (g : Y → Z) : surjective f ∧ surjective g → surjective (g ∘ f) :=
begin
-- Suppose that $f$ and $g$ are surjective functions, we need to show that $g ∘ f$ is also surjective, i.e. $∀ z ∈ Z, ∃ x ∈ X, (g ∘ f)(x) = z$.
intros h z,
-- Since $g$ is surjective, there is a $y ∈ Y$ such that $g(y) = z$.
have ha : ∃ y : Y, g(y) = z, apply h.right,
cases ha with y hy,
-- Similarly, as $f$ is surjective, there is a $x ∈ X$ such that $f(x) = y$.
have hb : ∃ x : X, f(x) = y, apply h.left,
cases hb with x hx,
-- But by definition, $(g ∘ f)(x) = g(f(x)) = g(y) = z$ So we are done!
existsi x,
rwa [←hy, ←hx]
end
/-Theorem
Let $f : X → Y$ and $g : Y → Z$ be functions, then if $f$ and $g$ are both bijective, then so is $g ∘ f$.
-/
theorem both_bijective
(X Y Z : Type u) (f : X → Y) (g : Y → Z) : bijective f ∧ bijective g → bijective (g ∘ f) :=
begin
-- Since $f$ and $g$ are bijective, they are also injective and surjective.
rintro ⟨⟨hfi, hfs⟩, hgi, hgs⟩,
split,
-- But since $f$ and $g$ are injective, $g ∘ f$ is injective by our previous theorem.
apply both_injective,
split,
repeat {assumption},
-- Similarly, since $f$ and $g$ surjective, $g ∘ f$ is surjective.
apply both_surjective,
split,
-- Hence, since $g ∘ f$ is injective and surjective, $g ∘ f$ is bijective.
repeat {assumption}
end
/-Sub-section
2.4 Inverses
-/
/- Definition
By digging through $\tt{functions}$, it turns out that the brilliant people of LEAN has not yet defined two sided inverse as the time of writting this.
So let's define $g : Y → X$ to be the two sided inverse of $f : X → Y$ if and only if $∀ x ∈ X, (g ∘ f)(x) = x$ and $∀ y ∈ Y, (f ∘ g)(y) = y$.
-/
def two_sided_inverse {X Y : Type u} (f : X → Y) (g : Y → X) := (∀ x : X, (g ∘ f)(x) = x) ∧ (∀ y : Y, (f ∘ g)(y) = y)
/-Theorem
A function $f : X → Y$ has a two-sided inverse if and only if it is a bijection.
-/
theorem exist_two_sided_inverse
(X Y : Type u) (f : X → Y) : (∃ g : Y → X, two_sided_inverse f g) ↔ bijective f :=
begin
-- Again, since the question is in the form of 'if and only if', we need to prove both sides of the implications.
split,
-- $(⇒)$ Suppose the function $f : X → Y$ has a two sided inverse $g$, we need to show that $f$ is bijective, i.e. it is injective and surjective.
rintro ⟨g, ⟨hlinv, hrinv⟩⟩,
-- So lets first show that $f$ is injective.
have hfinj : injective f,
-- Suppose we have $f(p) = f(q)$ for some $p q ∈ X$, then $f$ is injective if $p = q$.
intros p q hf,
-- Since $f(p) = f(q)$, we have $g(f(p)) = g(f(q))$.
replace hf : g (f p) = g (f q), rw hf,
-- But since $g$ is a double sided inverse of $f$, $∀ x ∈ X, g(f(x)) = x$, hence $p = g(f(p))= g(f(q)) = q$ which is exactly what we need!
have ha : g (f p) = p := hlinv p,
have hb : g (f q) = q := hlinv q,
rw [ha, hb] at hf,
assumption,
-- Now we need to show that $f$ is surjective, i.e. $∀ y ∈ Y, ∃ x ∈ X, f(x) = y$.
have hfbsur : surjective f,
intro y,
-- Since we have $g(y) ∈ X$, suppose we choose $x$ to be $g(y)$.
existsi g y,
-- But, as $g$ is a double inverse of $f$, $f(g(y)) = y$ which is exactly what we need!
exact hrinv y,
-- Thus, as $f$ is both injective and surjective, $f$ is bijective!
split,
all_goals {try {assumption}},
-- $(⇐)$ Now lets prove the reverse implication, i.e. if $f$ is bijective, then $f$ has a two-sided inverse.
rintro ⟨hfinj, hfsur⟩,
-- Since $f$ is surjective, $∀ y ∈ Y, ∃ x ∈ X$ such that $f(x) = y$, lets choose this $x$ to be our output of $g(y)$.
choose g hg using hfsur,
existsi g,
-- Now we need to show that $g$ is a double sided inverse of $f$ so let's first show that $g$ is a left inverse of $f$.
split,
intro a,
-- Consider that since, by definition of $g$, $∀ y ∈ Y, f(g(y)) = y$ we have $f(g(f(a))) = f(a)$,
have ha : f (g (f a)) = f a,
rw hg (f a),
-- therefore, as $f$ is injective, we have $f(g(f(a))) = f(a) ⇒ g(f(a)) = f(a)$. Thus, $g$ is a left inverse of $f$.
exact hfinj ha,
-- Now, all we have left to prove is that $g$ is a right inverse of $f$. But that is true by definition, so we are done!
assumption
end
/-Sub-section
2.5 Binary Relations
-/
variables {X V : Type u}
/- Definition
A binary relation $R$ on a set $X$ is a function $R : X^2 → \tt{Prop}$.
-/
def bin_rel (X) := X → X → Prop
/- Sub-section
2.6 Common Predicates on Binary Relations
-/
/- Definition
A binary relation $R$ on $X$ is called relfexive if $∀ x ∈ X, R(x, x)$.
-/
def reflexive (r : bin_rel X) := ∀ x : X, r x x
/- Theorem
$≤$ is reflexive on $ℝ$.
-/
@[simp] theorem le_refl : reflexive ((≤) : ℝ → ℝ → Prop) :=
begin
-- To prove that the binary relation $≤$ on $ℝ$ is reflexive, we need to show given arbitary $x ∈ ℝ$, $x ≤ x$.
intro,
-- But this obviously true, so we're done!
refl
end
/- Definition
A binary relation $R$ on $X$ is called symmetric if $∀a, b ∈ X, R(a, b) ⇒ R(b, a)$.
-/
def symmetric (r : bin_rel X) := ∀ x y : X, r x y → r y x
/- Theorem
$=$ is symmetric on $ℝ$.
-/
theorem eq_symm : symmetric ((=) : ℝ → ℝ → Prop) :=
begin
-- To prove that $=$ is a symmetric binary relation on $ℝ$, we need to show that given $x = y$, $y = x$.
intros x y h,
-- But if $x = y$, then we can re-write $y$ as $x$ and $x$ as $y$, thus, $y = x$.
rwa h
end
/- Definition
A binary relation $R$ on $X$ is called antisymmetric if $∀ a, b ∈ X, R(a, b) ∧ R(b, a) ⇒ a = b$.
-/
def antisymmetric (r : bin_rel X) := ∀ x y : X, r x y ∧ r y x → x = y
/- Theorem
$≤$ is anti-symmetric on $R$.
-/
@[simp] theorem le_antisymm : antisymmetric ((≤) : ℝ → ℝ → Prop) :=
begin
-- Suppose we have $x, y ∈ ℝ$ where $x ≤ y$ and $y ≤ x$, then we need to show that $x = y$.
intros x y h,
have h0 : (x < y ∨ x = y) ∧ (y < x ∨ y = x),
repeat {rw ←le_iff_lt_or_eq}, assumption,
-- By the trichotomy axioms, either $x < y$, $y < x$ or $x = y$.
cases lt_trichotomy x y with ha hb,
-- Let's first suppose that $x < y$, then obviously $¬ (y < x)$. But since we have $y ≤ x$, $x$ must therefore equal to $y$!
{suffices : ¬ (y < x),
cases h0.right with hc hd, contradiction, rwa hd,
simp, from h.left},
{cases hb with he hf,
-- Let's now consider the other two cases. If $x = y$ then there is nothing left to prove so lets suppose $y < x$.
{assumption},
-- Similar to before, $(y < x) ⇒ ¬ (x < y)$. But $(x ≤ y)$, therefore $x = y$!
{suffices : ¬ (x < y),
cases h0.left with hc hd, contradiction, rwa hd,
simp, from h.right}
}
end
/-
Remark. Notice that in the above proof I used a lot of curly bracket. This will limit the tactic state to only show the the goal within the brackets and thus also limit clutter.
Read more about how to structure LEAN proofs nicely <a href = "https://leanprover.github.io/theorem_proving_in_lean/tactics.html#structuring-tactic-proofs">here</a>.
-/
/- Definition
A binary relation $R$ on $X$ is called transitive if $∀ a, b, c ∈ X, R(a, b) ∧ R(b, c) ⇒ R(a, c)$.
-/
def transitive (r : bin_rel X) := ∀ x y z : X, r x y ∧ r y z → r x z
/- Theorem
$⇒$ is transitive on the set of propositions.
-/
theorem imply_trans : transitive ((→) : Prop → Prop → Prop) :=
begin
-- Let $P, Q, R$ be propositions such that $P ⇒ Q$ and $Q ⇒ R$. We then need to prove that $P ⇒ R$. Suppose $P$ is true.
intros P Q R h hp,
-- Then as $P ⇒ Q$, $Q$ must also be true. And again as $Q ⇒ R$, $R$ must also be true. Thus $P ⇒ R$, and we are done!
from h.right (h.left hp)
end
/- Theorem
$≤$ is transitive on $ℝ$.
-/
@[simp] theorem le_trans : transitive ((≤) : ℝ → ℝ → Prop) :=
begin
-- This one is a bit tricky and require us to delve into how ordering is defined on the reals in LEAN.
intros x y z h,
-- However, with the power that is mathlib, we see that there is something called $\tt{le_trans}$, so why don't we just steal that for our use here!
from le_trans h.left h.right
end
/- Sub-section
2.7 Partial and Total Orders
-/
/-
Let $R$ be a binary relation on the set $X$.
-/
/- Definition
We call $R$ a partial order if it is reflexive, antisymmetric, and transitive.
-/
def partial_order (r : bin_rel X) := reflexive r ∧ antisymmetric r ∧ transitive r
/- Definition
We call $R$ total if $∀ a, b ∈ X, R(a, b) ∨ R(b, a)$.
-/
def total (r : bin_rel X) := ∀ x y : X, r x y ∨ r y x
/- Definition
We call $R$ a total order if it is total and a partial order.
-/
def total_order (r : bin_rel X) := partial_order r ∧ total r
/-
Let's now prove that $≤$ is a total order. As we already have already proven that $≤$ is reflexive, symmetric, and transitive, i.e. its a partial order, we only need to show $≤$ is total to prove that $≤$ is a total order.
-/
/- Lemma
$≤$ is total on $ℝ$.
-/
@[simp] theorem le_total : total ((≤) : ℝ → ℝ → Prop) :=
begin
-- Suppose we have $x, y ∈ ℝ$, by the trichotomy axiom, either $x < y$, $y < x$ or $x = y$.
intros x y,
cases lt_trichotomy x y,
-- If $x < y$ then $x ≤ y$.
repeat {rw le_iff_lt_or_eq},
{left, left, assumption},
-- If $x = y$ then also $x ≤ y$. However, if $y > x$, then we have $y ≤ x$. Thus, by considering all the cases, we see either $x ≤ y$ or $y ≤ x$.
{cases h, repeat { {left, assumption} <|> right <|> assumption }, rwa h}
end
/-
Remark. The last line of this LEAN proof uses something called $\tt{tactic combinators}$. Read about is <a href = "https://leanprover.github.io/theorem_proving_in_lean/tactics.html#tactic-combinators">here</a>.
-/
/- Theorem
$≤$ is a total order on $ℝ$.
-/
theorem le_total_order : total_order ((≤) : ℝ → ℝ → Prop) :=
begin
-- As $≤$ is a partial order and is total, it is a total order!
repeat {split},
repeat {simp}
end
/-
Remark. Notice how I tagged some of the theorems above with $\tt{@[simp]}$? This tells LEAN to try to uses theses theorems whenever I use the tactive $\tt{simp}$. Read more about it <a href = "https://leanprover.github.io/theorem_proving_in_lean/tactics.html#using-the-simplifier">here</a>.
-/
/- Sub-section
2.7 Equivalence Relations
-/
/- Definition
A binary relation $R$ on the set $X$ is called an equivalence relation if it is reflexive, symmetric, and transitive.
-/
def equivalence (r : bin_rel X) := reflexive r ∧ symmetric r ∧ transitive r
/-
We'll present some examples of equivalence relations below.
-/
/- Definition
Suppose we define a binary relation $R(m, n)$, $m, n ∈ ℤ$, where $R(m, n)$ is true if and only if $m - n$ is even.
-/
def R (m n : ℤ) := 2 ∣ (m - n)
/- Lemma
(1) $R$ is reflexive.
-/
lemma R_refl : reflexive R :=
begin
-- We have for any $m ∈ ℝ$, $m - m = 0$.
intro,
unfold R,
-- As $2 ∣ 0$, we have $R(m, m)$ is true!
simp,
end
/- Lemma
(2) $R$ is symmetric.
-/
lemma R_symm : symmetric R :=
begin
-- Suppose we have $m, n ∈ ℝ$ such that $R(m, n)$ is true.
intros m n,
-- As $R(m, n)$ implies $2 ∣ m - n$, $∃ x ∈ ℤ, 2 x = m - n$.
rintro ⟨x, hx⟩,
existsi -x,
-- But this means $2 (-x) = n - m$, i.e. $2 ∣ n - m$, thus $R(n, m)$ is also true!
simp, rw ←hx, ring,
end
/- Lemma
(3) $R$ is transitive.
-/
lemma R_trans : transitive R :=
begin
-- Suppose we have $l, m, n ∈ ℝ$ such that $R(m, l)$ and $R(l, n)$, we need to show $R(m, n)$ is true.
intros l m n,
-- Since $R(m, l)$ and $R(l, n)$ implies $2 ∣ m - l$ and $2 ∣ l - n$, $∃ x, y ∈ ℤ, 2 x = m - l, 2 y = l - n$.
rintro ⟨⟨x, hx⟩, ⟨y, hy⟩⟩,
existsi x + y,
-- But then $2 (x + y) = 2 x + 2 y = m - l + l - n = m - n$. Thus $2 ∣ m - n$, i.e. $R(m, n)$.
ring, rw [←hx, ←hy], ring,
end
/- Theorem
$R$ is an equivalence relation.
-/
theorem R_equiv : equivalence R :=
begin
-- This follows directly from lemma (1), (2), and (3).
repeat {split},
{from R_refl},
{from R_symm},
{from R_trans}
end
/- Definition
Let $X$ be a set of sets, where $A, B ∈ X$. Let's define $<\mathtt{\sim}$ such that $A <~ B$ if an only if $∃ g: A → B$, $g$ is an injection.
-/
def brel (A B : Type*) := ∃ g : A → B, function.bijective g
infix ` <~ `: 50 := brel
/- Lemma
$<\mathtt{\sim}$ is reflexive.
-/
@[simp] lemma brel_refl : reflexive (<~) :=
begin
-- To prove $<\mathtt{\sim}$ is reflexive we need to show there exists a bijection between a set $X$ and itself.
intro X,
-- Luckily, we can simply choose the identity function!
let g : X → X := id,
existsi g,
-- Since the identity function is bijective, $<\mathtt{\sim}$ is reflexive as required.
from function.bijective_id
end
/- Lemma
$<\mathtt{\sim}$ is symmetric.
-/
@[simp] lemma brel_symm : symmetric (<~) :=
begin
-- To prove $<\mathtt{\sim}$ is symmetric we need to show that, for sets $X, Y$, $X <~ Y ⇒ Y <~ X$.
intros X Y,
-- Suppose $X <~ Y$, then by definition, $∃ f : X → Y$, where $f$ is bijective.
rintro ⟨f, hf⟩,
-- As proven ealier, $f$ is bijective implies $f$ has a two sided inverse $g$, let's choose that as our function.
have hg : ∃ g : Y → X, two_sided_inverse f g,
{rwa exist_two_sided_inverse
},
{cases hg with g hg,
existsi g,
-- Since $g$ is bijective if and only if $g$ has a two sided inverse, it suffices to prove that such an inverse exist.
rw ←exist_two_sided_inverse,
-- But as $g$ is the two sided inverse of $f$ by construction, we have $f$ is the two sided inverse of $g$ by definition, thus such an inverse does exist!
existsi f,
split,
{from hg.right},
{from hg.left}
}
end
/- Lemma
$<\mathtt{\sim}$ is transitive.
-/
@[simp] lemma brel_trans : transitive (<~) :=
begin
-- Given three sets $X, Y, Z$ where $X <~ Y$ and $Y <~ Z$ we need to show that $X <~ Z$.
intros X Y Z,
-- Since $X <~ Y$ and $Y <~ Z$ there exists bijective functions $f : X → Y$ and $g : Y → Z$.
rintro ⟨⟨f, hf⟩, g, hg⟩,
-- But as proven ealier, the composition of two bijective functions is also bijective. Thus, $g ∘ f : X → Z$ is a bijective function which is exactly what we need!
existsi (g ∘ f),
apply both_bijective,
split, repeat {assumption}
end
/-
With that, we can conclude that $<\mathtt{\sim}$ is an equivalence relation!
-/
/- Theorem
$<\mathtt{\sim}$ is an equivalence relation
-/
theorem brel_equiv : equivalence (<~) :=
begin
-- This follows as $<\mathtt{\sim}$ is reflexive, symmetric and transitive!
repeat {split},
repeat {simp}
end
/-
Exercise. I have defined one more binary relation $\mathtt{\sim}>$. Can you try to prove it <a href = "https://leanprover-community.github.io/lean-web-editor/#url=https%3A%2F%2Fraw.githubusercontent.com%2FJasonKYi%2FM4000x_LEAN_formalisation%2Fmaster%2Fsrc%2FExercises%2FExercies3.lean">here</a>?
-/
/- Sub-section
2.9 Quotients and Equivalence Classes
-/
/- Sub-section
2.9.1 Equivalence Classes
-/
/- Definition
Let $X$ be a set and let $\mathtt{\sim}$ be an equivalence relation on $X$. Let $s ∈ X$ be an arbitrary element. We define the equivalence class of $s$, written $cl(s)$ as $cl(s) = \{x ∈ X ∣ s \mathtt{\sim} x\}.
-/
def cls (r : bin_rel X) (s : X) := {x : X | r s x}
/- Lemma
(1) Let $X$ be a set and let $R$ be an equivalence relation on $X$. Then, for $s, t ∈ X$, $R(s, t) ⇒ cl(t) ⊆ cl(s)$.
-/
lemma class_relate_lem_a
(s t : X) (R : bin_rel X) (h : equivalence R) : R s t → cls R t ⊆ cls R s :=
begin
-- Given that $R$ is an equivalence relation, we know that it is reflexive, symmetric and transitive.
rcases h with ⟨href, ⟨hsym, htrans⟩⟩,
-- Thus, given an element $x$ in $cl(t)$ (i.e. $R(t, x)$ is true), we have, by transitivit, $R(s, x)$.
intros ha x hb,
have hc : R t x := hb,
replace hc : R s t ∧ R t x, by {split, repeat {assumption}},
replace hc : R s x := htrans s t x hc,
-- Hence $x ∈ cl(s)$ by definition.
from hc
end
/-
With lemma (1) in place, it is quite easy to see that, not only is $cl(t) ⊆ cl(s)$, in fact, $cl(t) = cl(s)$.
-/
/- Lemma
(2) Let $X$ be a set and let $R$ be an equivalence relation on $X$. Then, for $s, t ∈ X$, $R(s, t) ⇒ cl(t) = cl(s)$.
-/
lemma class_relate_lem_b
(s t : X) (R : bin_rel X) (h : equivalence R) : R s t → cls R t = cls R s :=
begin
-- By lemma (1), $cl(t) ⊆ cl(s), and thus, we only need to prove that $cl(s) ⊆ cl(t)$ in order for $cl(t) = cl(s)$.
intro h0,
rw le_antisymm_iff,
split,
all_goals {apply class_relate_lem_a,
repeat {assumption}
},
-- But, since $R$ is and equivalence relation, it is symmetric.
{rcases h with ⟨href, ⟨hsym, htrans⟩⟩,
-- Hence, $R(s, t) ↔ R(t, s)$ which by lemma (1) implies $cl(s) ⊆ cl(t)$ as required.
from hsym s t h0
}
end
/- Lemma
(3) Let $X$ be a set and let $R$ be an equivalence relation on $X$. Then, for $s, t ∈ X$, $¬ R(s, t) ⇒ cl(t) ∩ cl(s) = ∅$.
-/
lemma class_not_relate
(s t : X) (R : bin_rel X) (h : equivalence R) : ¬ R s t → cls R t ∩ cls R s = ∅ :=
begin
have : (cls R t ∩ cls R s = ∅) ↔ ¬ ¬ (cls R t ∩ cls R s = ∅), rwa classical.not_not, rw this,
-- We prove by contradiction. Suppose $cl(t) ∩ cl(s) ≠ ∅$.
intros ha hb,
-- Then, there must be some $x$ in $cl(t) ∩ cl(s)$.
have hx : ∃ x, x ∈ cls R t ∩ cls R s := set.ne_empty_iff_nonempty.1 hb,
rcases hx with ⟨x, ⟨hα, hβ⟩⟩,
-- Thus, by definition, $R(t, x)$ and $R(s, t)$ must both be true!
rcases h with ⟨href, ⟨hsym, htrans⟩⟩,
have hc : R s x ∧ R x t, by {split,
from hβ,
apply hsym, from hα},
-- But this means $R(s, t)$ must also be true by transitivity, a contradiction to $¬ R(s, t)$!
have hd : R s t, by {from htrans s x t hc},
contradiction,
end
/-
We now formally define a partition of a set $X$
-/
/-
Partition of a set $X$ is a set $A$ of non-empty subsets of $X$ with the property that each element of $X$ is in exacctly one of the subsets.
-/
def partition (A : set (set X)) : Prop := (∀ x : X, (∃ B ∈ A, x ∈ B ∧ ∀ C ∈ A, x ∈ C → B = C)) ∧ ∅ ∉ A
lemma equiv_refl (R : bin_rel X) (h : equivalence R) (x : X): R x x :=
by {rcases h with ⟨href, ⟨hsym, htrans⟩⟩, from href x}
lemma equiv_symm (R : bin_rel X) (h : equivalence R) (x y : X): R x y ↔ R y x :=
by {rcases h with ⟨href, ⟨hsym, htrans⟩⟩, split, from hsym x y, from hsym y x}
lemma equiv_trans (R : bin_rel X) (h : equivalence R) (x y z : X): R x y ∧ R y z → R x z :=
by {rcases h with ⟨href, ⟨hsym, htrans⟩⟩, from htrans x y z}
lemma itself_in_cls (R : bin_rel X) (h : equivalence R) (x : X) : x ∈ cls R x :=
by {unfold cls, rw set.mem_set_of_eq, from equiv_refl R h x}
/- Theorem
Let $X$ be a set and let $R$ be an equivalence relation on $X$. Then the set $V$ of equivalence classes $\{cl(s) | s ∈ X\}$ for $R$ is a partition of $X$.
-/
theorem equiv_relation_partition -- or replace the set with (set.range (cls R))
(R : bin_rel X) (h : equivalence R) : partition {a : set X | ∃ s : X, a = cls R s} :=
begin
-- To show that the equivalence classes of $R$ form a partition of $X$, we need to show that every $x ∈ X$ is in exactly one equivalence class of $R$, AND, none of the equivalence classes are empty.
split,
-- So let's first show that every $x ∈ X$ is in exactly one equivalence class of $R$. Let $y$ be and element of $X$.
{simp, intro y,
existsi cls R y,
split,
-- Then obviously $y ∈ cl(y)$ since $R(y, y)$ is true by reflexivity.
{use y},
{split,
{from itself_in_cls R h y},
-- Okay. So now we need to prove uniqueness. Suppose there is a $x ∈ X$, $x ∈ cl(y)$, we then need to show $cl(y) = cl(x)$.
{intros C x hC hy_in_C, rw hC,
-- But this is true by lemma (2)!
apply class_relate_lem_b, assumption,
have : y ∈ cls R x, rwa ←hC,
unfold cls at this,
rwa set.mem_set_of_eq at this}
}
},
-- Now we have to prove that none of the equivalence classes are empty. But this is quite simple. Suppose there is an equivalence class $cl(x)$ where $x ∈ X$ that is empty.
{simp, intros x hx,
-- But then $x ∈ cl(x)$ as $R(x, x)$ is true by reflexivity. Ah ha! Contradiction! Hence, such empty equivalence class does not in fact exist! And we are done.
rw set.empty_def at hx,
have : x ∈ {x : X | false}, by {rw hx, from itself_in_cls R h x},
rwa set.mem_set_of_eq at this
}
end
def rs (A : set (set(X))) (s t : X) := ∃ B ∈ A, s ∈ B ∧ t ∈ B
/-
Bonus Exercise. Furthermore, it turns out that if $X$ is a set and $R$ an equivalence relation on $X$. Then any partition of $X$ can form a equivalence relation. Try to prove it <a href = "https://leanprover-community.github.io/lean-web-editor/#url=https%3A%2F%2Fraw.githubusercontent.com%2FJasonKYi%2FM4000x_LEAN_formalisation%2Fmaster%2Fsrc%2FExercises%2FExercies4.lean">here</a> and if you get stuck, <a href = "https://raw.githubusercontent.com/JasonKYi/M4000x_LEAN_formalisation/master/src/Exercises/Exercies4_sol.lean">here</a> are the solutions.
-/
end M40001 |
86af77c961508505d84589dc3a3a03223e63941a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/exterior_algebra_auto.lean | 7b6b162f12fdc2f600a4ceb917d2b496bcbf0754 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,895 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ring_quot
import Mathlib.linear_algebra.tensor_algebra
import Mathlib.linear_algebra.alternating
import Mathlib.group_theory.perm.sign
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Exterior Algebras
We construct the exterior algebra of a semimodule `M` over a commutative semiring `R`.
## Notation
The exterior algebra of the `R`-semimodule `M` is denoted as `exterior_algebra R M`.
It is endowed with the structure of an `R`-algebra.
Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that
`cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism,
which is denoted `exterior_algebra.lift R f cond`.
The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`.
## Theorems
The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property
of the exterior algebra.
1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`.
2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1.
## Definitions
* `ι_multi` is the `alternating_map` corresponding to the wedge product of `ι R m` terms.
## Implementation details
The exterior algebra of `M` is constructed as a quotient of the tensor algebra, as follows.
1. We define a relation `exterior_algebra.rel R M` on `tensor_algebra R M`.
This is the smallest relation which identifies squares of elements of `M` with `0`.
2. The exterior algebra is the quotient of the tensor algebra by this relation.
-/
namespace exterior_algebra
/-- `rel` relates each `ι m * ι m`, for `m : M`, with `0`.
The exterior algebra of `M` is defined as the quotient modulo this relation.
-/
inductive rel (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] :
tensor_algebra R M → tensor_algebra R M → Prop
where
| of : ∀ (m : M), rel R M (coe_fn (tensor_algebra.ι R) m * coe_fn (tensor_algebra.ι R) m) 0
end exterior_algebra
/--
The exterior algebra of an `R`-semimodule `M`.
-/
def exterior_algebra (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M]
[semimodule R M] :=
ring_quot sorry
namespace exterior_algebra
-- typeclass resolution times out here, so we give it a hand
protected instance ring {M : Type u_2} [add_comm_monoid M] {S : Type u_1} [comm_ring S]
[semimodule S M] : ring (exterior_algebra S M) :=
let i : ring (tensor_algebra S M) := infer_instance;
ring_quot.ring (rel S M)
/--
The canonical linear map `M →ₗ[R] exterior_algebra R M`.
-/
def ι (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] :
linear_map R M (exterior_algebra R M) :=
linear_map.comp (alg_hom.to_linear_map (ring_quot.mk_alg_hom R (rel R M))) (tensor_algebra.ι R)
/-- As well as being linear, `ι m` squares to zero -/
@[simp] theorem ι_square_zero {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] (m : M) : coe_fn (ι R) m * coe_fn (ι R) m = 0 :=
sorry
@[simp] theorem comp_ι_square_zero {R : Type u_1} [comm_semiring R] {M : Type u_2}
[add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A]
(g : alg_hom R (exterior_algebra R M) A) (m : M) :
coe_fn g (coe_fn (ι R) m) * coe_fn g (coe_fn (ι R) m) = 0 :=
sorry
/--
Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition:
`cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras
from `exterior_algebra R M` to `A`.
-/
def lift (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M]
{A : Type u_3} [semiring A] [algebra R A] :
(Subtype fun (f : linear_map R M A) => ∀ (m : M), coe_fn f m * coe_fn f m = 0) ≃
alg_hom R (exterior_algebra R M) A :=
equiv.mk
(fun (f : Subtype fun (f : linear_map R M A) => ∀ (m : M), coe_fn f m * coe_fn f m = 0) =>
coe_fn (ring_quot.lift_alg_hom R)
{ val := coe_fn (tensor_algebra.lift R) ↑f, property := sorry })
(fun (F : alg_hom R (exterior_algebra R M) A) =>
{ val := linear_map.comp (alg_hom.to_linear_map F) (ι R), property := sorry })
sorry sorry
@[simp] theorem ι_comp_lift (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A)
(cond : ∀ (m : M), coe_fn f m * coe_fn f m = 0) :
linear_map.comp (alg_hom.to_linear_map (coe_fn (lift R) { val := f, property := cond })) (ι R) =
f :=
iff.mp subtype.mk_eq_mk (equiv.symm_apply_apply (lift R) { val := f, property := cond })
@[simp] theorem lift_ι_apply (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A)
(cond : ∀ (m : M), coe_fn f m * coe_fn f m = 0) (x : M) :
coe_fn (coe_fn (lift R) { val := f, property := cond }) (coe_fn (ι R) x) = coe_fn f x :=
iff.mp linear_map.ext_iff (ι_comp_lift R f cond) x
@[simp] theorem lift_unique (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A)
(cond : ∀ (m : M), coe_fn f m * coe_fn f m = 0) (g : alg_hom R (exterior_algebra R M) A) :
linear_map.comp (alg_hom.to_linear_map g) (ι R) = f ↔
g = coe_fn (lift R) { val := f, property := cond } :=
sorry
-- Marking `exterior_algebra` irreducible makes our `ring` instances inaccessible.
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241
-- For now, we avoid this by not marking it irreducible.
@[simp] theorem lift_comp_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {A : Type u_3} [semiring A] [algebra R A]
(g : alg_hom R (exterior_algebra R M) A) :
coe_fn (lift R)
{ val := linear_map.comp (alg_hom.to_linear_map g) (ι R),
property := comp_ι_square_zero g } =
g :=
sorry
/-- See note [partially-applied ext lemmas]. -/
theorem hom_ext {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M]
{A : Type u_3} [semiring A] [algebra R A] {f : alg_hom R (exterior_algebra R M) A}
{g : alg_hom R (exterior_algebra R M) A}
(h :
linear_map.comp (alg_hom.to_linear_map f) (ι R) =
linear_map.comp (alg_hom.to_linear_map g) (ι R)) :
f = g :=
sorry
/-- The left-inverse of `algebra_map`. -/
def algebra_map_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] : alg_hom R (exterior_algebra R M) R :=
coe_fn (lift R) { val := 0, property := sorry }
theorem algebra_map_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] :
function.left_inverse ⇑algebra_map_inv ⇑(algebra_map R (exterior_algebra R M)) :=
sorry
/-- The left-inverse of `ι`.
As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable
algebra structure. -/
def ι_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] :
linear_map R (exterior_algebra R M) M :=
linear_map.comp (triv_sq_zero_ext.snd_hom R M)
(alg_hom.to_linear_map
(coe_fn (lift R) { val := triv_sq_zero_ext.inr_hom R M, property := sorry }))
theorem ι_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] : function.left_inverse ⇑ι_inv ⇑(ι R) :=
sorry
@[simp] theorem ι_add_mul_swap {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] (x : M) (y : M) :
coe_fn (ι R) x * coe_fn (ι R) y + coe_fn (ι R) y * coe_fn (ι R) x = 0 :=
sorry
theorem ι_mul_prod_list {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {n : ℕ} (f : fin n → M) (i : fin n) :
coe_fn (ι R) (f i) * list.prod (list.of_fn fun (i : fin n) => coe_fn (ι R) (f i)) = 0 :=
sorry
/-- The product of `n` terms of the form `ι R m` is an alternating map.
This is a special case of `multilinear_map.mk_pi_algebra_fin` -/
def ι_multi (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M]
(n : ℕ) : alternating_map R M (exterior_algebra R M) (fin n) :=
let F : multilinear_map R (fun (i : fin n) => M) (exterior_algebra R M) :=
multilinear_map.comp_linear_map (multilinear_map.mk_pi_algebra_fin R n (exterior_algebra R M))
fun (i : fin n) => ι R;
alternating_map.mk ⇑F sorry sorry sorry
theorem ι_multi_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] {n : ℕ} (v : fin n → M) :
coe_fn (ι_multi R n) v = list.prod (list.of_fn fun (i : fin n) => coe_fn (ι R) (v i)) :=
rfl
end exterior_algebra
namespace tensor_algebra
/-- The canonical image of the `tensor_algebra` in the `exterior_algebra`, which maps
`tensor_algebra.ι R x` to `exterior_algebra.ι R x`. -/
def to_exterior {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] : alg_hom R (tensor_algebra R M) (exterior_algebra R M) :=
coe_fn (lift R) (exterior_algebra.ι R)
@[simp] theorem to_exterior_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M]
[semimodule R M] (m : M) :
coe_fn to_exterior (coe_fn (ι R) m) = coe_fn (exterior_algebra.ι R) m :=
sorry
end Mathlib |
250c25d94b6e6ddf1b9c59f6514c7de55f76f81c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/LCNF/Check.lean | 677748dcddd0175c440e67726680d461ca8cab27 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 12,592 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.InferType
import Lean.Compiler.LCNF.PrettyPrinter
import Lean.Compiler.LCNF.CompatibleTypes
namespace Lean.Compiler.LCNF
/-!
# Note: Type compatibility checking for LCNF
We used to have a type compatibility relation `≃` for LCNF types.
It treated erased types/values as wildcards. Examples:
- `List Nat ≃ List ◾`
- `(List ◾ → List ◾) ≃ (List Nat → List Bool)`
We used this relation to sanity check compiler passes, and detect
buggy transformations that broke type compatibility. For example,
given an application `f a`, we would check whether `a`s type as
compatible with the type expected by `f`.
However, the type compatibility relation is not transitive. Example:
- `List Nat ≃ List ◾`, `List ◾ ≃ List String`, but `List Nat` and `List String` are **not** compatible.
We tried address the issue above by adding casts, which required us
to then add `cast` elimination simplifications, and generated a significant overhead in
the code generator.
Here is an example of transformation that would require the insertion of a cast operation.
```
def foo (g : List A → List A) (a : List B) :=
fun f (x : List ◾) :=
let _x.1 := g x
...
let _x.2 := f a
...
```
The code above would not trigger any type compatibility issue, but
by inlining `f` without adding cast operations, we would get the
following type incorrect code.
```
def foo (g : List A → List A) (a : List B) :=
let _x.2 := g a -- Type error
...
```
We have considered using a reflexive and transitive subtype relation `≺`.
- `A ≺ A`
- `(Nat × Nat) ≺ (Nat × ◾) ≺ (◾ × ◾) ≺ ◾`
- `List Nat ≺ List ◾ ⊀ List String`
- `(List ◾ → List Nat) ≺ (List Bool → List ◾)`
Note that `A ≺ B` implies `A ≃ B`
The subtype relation has better properties, but also has problems.
First, when converting to LCNF we would have to add more casts. Example:
the function takes a `List ◾`, but the value has type `◾`.
Moreover, recall that `(List Nat → List Nat) ⊀ (◾ → ◾)` forcing us
to add many casts operations when moving to the mono phase where
we erase type parameters.
Recall that type compatibility and subtype relationships do not help with memory layout.
We have that `(UInt32 × UInt32) ≺ (◾ × ◾) ≺ ◾` but elements of these types have
different runtime representation.
Thus, we have decided to abandon the type compatibility checks and cast operations
in LCNF. The only drawback is that we lose the capability of catching simple bugs
at compiler passes.
In the future, we can try to add a sanity check flag that instructs the compiler to use
the subtype relation in sanity checks and add the necessary casts.
-/
namespace Check
open InferType
/-
Type and structural properties checker for LCNF expressions.
-/
structure Context where
/-- Join points that are in scope. -/
jps : FVarIdSet := {}
/-- Variables and local functions in scope -/
vars : FVarIdSet := {}
structure State where
/-- All free variables found -/
all : FVarIdHashSet := {}
abbrev CheckM := ReaderT Context $ StateRefT State InferTypeM
def checkTypes : CheckM Bool := do
return (← getConfig).checkTypes
def checkFVar (fvarId : FVarId) : CheckM Unit :=
unless (← read).vars.contains fvarId do
throwError "invalid out of scope free variable {← getBinderName fvarId}"
/-- Return true `f` is a constructor and `i` is less than its number of parameters. -/
def isCtorParam (f : Expr) (i : Nat) : CoreM Bool := do
let .const declName _ := f | return false
let .ctorInfo info ← getConstInfo declName | return false
return i < info.numParams
def checkAppArgs (f : Expr) (args : Array Arg) : CheckM Unit := do
let mut fType ← inferType f
let mut j := 0
for i in [:args.size] do
let arg := args[i]!
if fType.isErased then
return ()
fType := fType.headBeta
let (d, b) ←
match fType with
| .forallE _ d b _ => pure (d, b)
| _ =>
fType := instantiateRevRangeArgs fType j i args |>.headBeta
match fType with
| .forallE _ d b _ => j := i; pure (d, b)
| _ => return ()
let expectedType := instantiateRevRangeArgs d j i args
if (← checkTypes) then
let argType ← arg.inferType
unless (← InferType.compatibleTypes argType expectedType) do
throwError "type mismatch at LCNF application{indentExpr (mkAppN f (args.map Arg.toExpr))}\nargument {arg.toExpr} has type{indentExpr argType}\nbut is expected to have type{indentExpr expectedType}"
unless (← pure (maybeTypeFormerType expectedType) <||> isErasedCompatible expectedType) do
match arg with
| .fvar fvarId => checkFVar fvarId
| .erased => pure ()
| .type _ =>
-- Constructor parameters that are not type formers are erased at phase .mono
unless (← getPhase) ≥ .mono && (← isCtorParam f i) do
throwError "invalid LCNF application{indentExpr (mkAppN f (args.map (·.toExpr)))}\nargument{indentExpr arg.toExpr}\nhas type{indentExpr expectedType}\nmust be a free variable"
fType := b
def checkLetValue (e : LetValue) : CheckM Unit := do
match e with
| .value .. | .erased => pure ()
| .const declName us args => checkAppArgs (mkConst declName us) args
| .fvar fvarId args => checkFVar fvarId; checkAppArgs (.fvar fvarId) args
| .proj _ _ fvarId => checkFVar fvarId
def checkJpInScope (jp : FVarId) : CheckM Unit := do
unless (← read).jps.contains jp do
/-
We cannot jump to join points defined out of the scope of a local function declaration.
For example, the following is an invalid LCNF.
```
jp_1 := fun x => ... -- Some join point
let f := fun y => -- Local function declaration.
...
jp_1 _x.n -- jump to a join point that is not in the scope of `f`.
```
-/
throwError "invalid jump to out of scope join point `{mkFVar jp}`"
def checkParam (param : Param) : CheckM Unit := do
unless param == (← getParam param.fvarId) do
throwError "LCNF parameter mismatch at `{param.binderName}`, does not value in local context"
def checkParams (params : Array Param) : CheckM Unit :=
params.forM checkParam
def checkLetDecl (letDecl : LetDecl) : CheckM Unit := do
checkLetValue letDecl.value
if (← checkTypes) then
let valueType ← letDecl.value.inferType
unless (← InferType.compatibleTypes letDecl.type valueType) do
throwError "type mismatch at `{letDecl.binderName}`, value has type{indentExpr valueType}\nbut is expected to have type{indentExpr letDecl.type}"
unless letDecl == (← getLetDecl letDecl.fvarId) do
throwError "LCNF let declaration mismatch at `{letDecl.binderName}`, does not match value in local context"
def addFVarId (fvarId : FVarId) : CheckM Unit := do
if (← get).all.contains fvarId then
throwError "invalid LCNF, free variables are not unique `{fvarId.name}`"
modify fun s => { s with all := s.all.insert fvarId }
@[inline] def withFVarId (fvarId : FVarId) (x : CheckM α) : CheckM α := do
addFVarId fvarId
withReader (fun ctx => { ctx with vars := ctx.vars.insert fvarId }) x
@[inline] def withJp (fvarId : FVarId) (x : CheckM α) : CheckM α := do
addFVarId fvarId
withReader (fun ctx => { ctx with jps := ctx.jps.insert fvarId }) x
@[inline] def withParams (params : Array Param) (x : CheckM α) : CheckM α := do
params.forM (addFVarId ·.fvarId)
withReader (fun ctx => { ctx with vars := params.foldl (init := ctx.vars) fun vars p => vars.insert p.fvarId })
x
mutual
set_option linter.all false
partial def checkFunDeclCore (declName : Name) (params : Array Param) (type : Expr) (value : Code) : CheckM Unit := do
checkParams params
withParams params do
discard <| check value
if (← checkTypes) then
let valueType ← mkForallParams params (← value.inferType)
unless (← InferType.compatibleTypes type valueType) do
throwError "type mismatch at `{declName}`, value has type{indentExpr valueType}\nbut is expected to have type{indentExpr type}"
partial def checkFunDecl (funDecl : FunDecl) : CheckM Unit := do
checkFunDeclCore funDecl.binderName funDecl.params funDecl.type funDecl.value
let decl ← getFunDecl funDecl.fvarId
unless decl.binderName == funDecl.binderName do
throwError "LCNF local function declaration mismatch at `{funDecl.binderName}`, binder name in local context `{decl.binderName}`"
unless decl.type == funDecl.type do
throwError "LCNF local function declaration mismatch at `{funDecl.binderName}`, type in local context{indentExpr decl.type}\nexpected{indentExpr funDecl.type}"
unless (← getFunDecl funDecl.fvarId) == funDecl do
throwError "LCNF local function declaration mismatch at `{funDecl.binderName}`, declaration in local context does match"
partial def checkCases (c : Cases) : CheckM Unit := do
let mut ctorNames : NameSet := {}
let mut hasDefault := false
checkFVar c.discr
for alt in c.alts do
match alt with
| .default k => hasDefault := true; check k
| .alt ctorName params k =>
checkParams params
if ctorNames.contains ctorName then
throwError "invalid LCNF `cases`, alternative `{ctorName}` occurs more than once"
ctorNames := ctorNames.insert ctorName
let .ctorInfo val ← getConstInfo ctorName | throwError "invalid LCNF `cases`, `{ctorName}` is not a constructor name"
unless val.induct == c.typeName do
throwError "invalid LCNF `cases`, `{ctorName}` is not a constructor of `{c.typeName}`"
unless params.size == val.numFields do
throwError "invalid LCNF `cases`, `{ctorName}` has # {val.numFields} fields, but alternative has # {params.size} alternatives"
withParams params do check k
partial def check (code : Code) : CheckM Unit := do
match code with
| .let decl k => checkLetDecl decl; withFVarId decl.fvarId do check k
| .fun decl k =>
-- Remark: local function declarations should not jump to out of scope join points
withReader (fun ctx => { ctx with jps := {} }) do checkFunDecl decl
withFVarId decl.fvarId do check k
| .jp decl k => checkFunDecl decl; withJp decl.fvarId do check k
| .cases c => checkCases c
| .jmp fvarId args =>
checkJpInScope fvarId
let decl ← getFunDecl fvarId
unless decl.getArity == args.size do
throwError "invalid LCNF `goto`, join point {decl.binderName} has #{decl.getArity} parameters, but #{args.size} were provided"
checkAppArgs (.fvar fvarId) args
| .return fvarId => checkFVar fvarId
| .unreach .. => pure ()
end
def run (x : CheckM α) : CompilerM α :=
x |>.run {} |>.run' {} |>.run {}
end Check
def Decl.check (decl : Decl) : CompilerM Unit := do
Check.run do Check.checkFunDeclCore decl.name decl.params decl.type decl.value
/--
Check whether every local declaration in the local context is used in one of given `decls`.
-/
partial def checkDeadLocalDecls (decls : Array Decl) : CompilerM Unit := do
let (_, s) := visitDecls decls |>.run {}
let usesFVar (binderName : Name) (fvarId : FVarId) :=
unless s.contains fvarId do
throwError "LCNF local context contains unused local variable declaration `{binderName}`"
let lctx := (← get).lctx
lctx.params.forM fun fvarId decl => usesFVar decl.binderName fvarId
lctx.letDecls.forM fun fvarId decl => usesFVar decl.binderName fvarId
lctx.funDecls.forM fun fvarId decl => usesFVar decl.binderName fvarId
where
visitFVar (fvarId : FVarId) : StateM FVarIdHashSet Unit :=
modify (·.insert fvarId)
visitParam (param : Param) : StateM FVarIdHashSet Unit := do
visitFVar param.fvarId
visitParams (params : Array Param) : StateM FVarIdHashSet Unit := do
params.forM visitParam
visitCode (code : Code) : StateM FVarIdHashSet Unit := do
match code with
| .jmp .. | .return .. | .unreach .. => return ()
| .let decl k => visitFVar decl.fvarId; visitCode k
| .fun decl k | .jp decl k =>
visitFVar decl.fvarId; visitParams decl.params; visitCode decl.value
visitCode k
| .cases c => c.alts.forM fun alt => do
match alt with
| .default k => visitCode k
| .alt _ ps k => visitParams ps; visitCode k
visitDecl (decl : Decl) : StateM FVarIdHashSet Unit := do
visitParams decl.params
visitCode decl.value
visitDecls (decls : Array Decl) : StateM FVarIdHashSet Unit :=
decls.forM visitDecl
end Lean.Compiler.LCNF
|
cd406de23ed1d69ee334225e0166388c796c96f0 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/init/pathover.hlean | 8a2e02b6e98accea796a5b83715506e771600991 | [
"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 | 18,523 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Basic theorems about pathovers
-/
prelude
import .path .equiv
open equiv is_equiv function
variables {A A' : Type} {B B' : A → Type} {B'' : A' → Type} {C : Π⦃a⦄, B a → Type}
{a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄} {p₁₃ : a = a₃}
{b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄}
{c : C b} {c₂ : C b₂}
namespace eq
inductive pathover.{l} (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} :=
idpatho : pathover B b (refl a) b
notation b ` =[`:50 p:0 `] `:0 b₂:50 := pathover _ b p b₂
definition idpo [reducible] [constructor] : b =[refl a] b :=
pathover.idpatho b
/- equivalences with equality using transport -/
definition pathover_of_tr_eq [unfold 5 8] (r : p ▸ b = b₂) : b =[p] b₂ :=
by cases p; cases r; constructor
definition pathover_of_eq_tr [unfold 5 8] (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ :=
by cases p; cases r; constructor
definition tr_eq_of_pathover [unfold 8] (r : b =[p] b₂) : p ▸ b = b₂ :=
by cases r; reflexivity
definition eq_tr_of_pathover [unfold 8] (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ :=
by cases r; reflexivity
definition pathover_equiv_tr_eq [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (p ▸ b = b₂) :=
begin
fapply equiv.MK,
{ exact tr_eq_of_pathover},
{ exact pathover_of_tr_eq},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_equiv_eq_tr [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) :=
begin
fapply equiv.MK,
{ exact eq_tr_of_pathover},
{ exact pathover_of_eq_tr},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_tr [unfold 5] (p : a = a₂) (b : B a) : b =[p] p ▸ b :=
by cases p; constructor
definition tr_pathover [unfold 5] (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b :=
by cases p; constructor
definition concato [unfold 12] (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ :=
by induction r₂; exact r
definition inverseo [unfold 8] (r : b =[p] b₂) : b₂ =[p⁻¹] b :=
by induction r; constructor
definition concato_eq [unfold 10] (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' :=
by induction q; exact r
definition eq_concato [unfold 9] (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ :=
by induction q; exact r
definition change_path [unfold 9] (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ :=
q ▸ r
-- infix ` ⬝ ` := concato
infix ` ⬝o `:72 := concato
infix ` ⬝op `:73 := concato_eq
infix ` ⬝po `:73 := eq_concato
-- postfix `⁻¹` := inverseo
postfix `⁻¹ᵒ`:(max+10) := inverseo
definition pathover_cancel_right (q : b =[p ⬝ p₂] b₃) (r : b₃ =[p₂⁻¹] b₂) : b =[p] b₂ :=
change_path !con_inv_cancel_right (q ⬝o r)
definition pathover_cancel_right' (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) (r : b₂ =[p₂] b₃) : b =[p₁₃] b₃ :=
change_path !inv_con_cancel_right (q ⬝o r)
definition pathover_cancel_left (q : b₂ =[p⁻¹] b) (r : b =[p ⬝ p₂] b₃) : b₂ =[p₂] b₃ :=
change_path !inv_con_cancel_left (q ⬝o r)
definition pathover_cancel_left' (q : b =[p] b₂) (r : b₂ =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ :=
change_path !con_inv_cancel_left (q ⬝o r)
/- Some of the theorems analogous to theorems for = in init.path -/
definition cono_idpo (r : b =[p] b₂) : r ⬝o idpo =[con_idp p] r :=
pathover.rec_on r idpo
definition idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p] r :=
pathover.rec_on r idpo
definition cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
r ⬝o (r₂ ⬝o r₃) =[!con.assoc'] (r ⬝o r₂) ⬝o r₃ :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
(r ⬝o r₂) ⬝o r₃ =[!con.assoc] r ⬝o (r₂ ⬝o r₃) :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[!con.right_inv] idpo :=
pathover.rec_on r idpo
definition cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[!con.left_inv] idpo :=
pathover.rec_on r idpo
definition eq_of_pathover {a' a₂' : A'} (q : a' =[p] a₂') : a' = a₂' :=
by cases q;reflexivity
definition pathover_of_eq [unfold 5 8] (p : a = a₂) {a' a₂' : A'} (q : a' = a₂') : a' =[p] a₂' :=
by cases p;cases q;constructor
definition pathover_constant [constructor] (p : a = a₂) (a' a₂' : A') : a' =[p] a₂' ≃ a' = a₂' :=
begin
fapply equiv.MK,
{ exact eq_of_pathover},
{ exact pathover_of_eq p},
{ intro r, cases p, cases r, reflexivity},
{ intro r, cases r, reflexivity},
end
definition pathover_of_eq_tr_constant_inv (p : a = a₂) (a' : A')
: pathover_of_eq p (tr_constant p a')⁻¹ = pathover_tr p a' :=
by cases p; constructor
definition eq_of_pathover_idp [unfold 6] {b' : B a} (q : b =[idpath a] b') : b = b' :=
tr_eq_of_pathover q
--should B be explicit in the next two definitions?
definition pathover_idp_of_eq [unfold 6] {b' : B a} (q : b = b') : b =[idpath a] b' :=
pathover_of_tr_eq q
definition pathover_idp [constructor] (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
equiv.MK eq_of_pathover_idp
(pathover_idp_of_eq)
(to_right_inv !pathover_equiv_tr_eq)
(to_left_inv !pathover_equiv_tr_eq)
definition eq_of_pathover_idp_pathover_of_eq {A X : Type} (x : X) {a a' : A} (p : a = a') :
eq_of_pathover_idp (pathover_of_eq (idpath x) p) = p :=
by induction p; reflexivity
-- definition pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
-- pathover_equiv_tr_eq idp b b'
-- definition eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' :=
-- to_fun !pathover_idp q
-- definition pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' :=
-- to_inv !pathover_idp q
definition idp_rec_on [recursor] [unfold 7] {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Type}
{b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r :=
have H2 : P (pathover_idp_of_eq (eq_of_pathover_idp r)), from
eq.rec_on (eq_of_pathover_idp r) H,
proof left_inv !pathover_idp r ▸ H2 qed
definition rec_on_right [recursor] {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type}
{b₂ : B a₂} (r : b =[p] b₂) (H : P !pathover_tr) : P r :=
by cases r; exact H
definition rec_on_left [recursor] {P : Π⦃b : B a⦄, b =[p] b₂ → Type}
{b : B a} (r : b =[p] b₂) (H : P !tr_pathover) : P r :=
by cases r; exact H
--pathover with fibration B' ∘ f
definition pathover_ap [unfold 10] (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : b =[ap f p] b₂ :=
by cases q; constructor
definition pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p] b₂ :=
by cases p; apply (idp_rec_on q); apply idpo
definition pathover_compose [constructor] (B' : A' → Type) (f : A → A') (p : a = a₂)
(b : B' (f a)) (b₂ : B' (f a₂)) : b =[p] b₂ ≃ b =[ap f p] b₂ :=
begin
fapply equiv.MK,
{ exact pathover_ap B' f},
{ exact pathover_of_pathover_ap B' f},
{ intro q, cases p, esimp, apply (idp_rec_on q), apply idp},
{ intro q, cases q, reflexivity},
end
definition pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ :=
pathover_cancel_right q !pathover_tr⁻¹ᵒ
definition pathover_tr_of_pathover (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) : b =[p₁₃] p₂ ▸ b₂ :=
pathover_cancel_right' q !pathover_tr
definition pathover_of_tr_pathover (q : p ▸ b =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ :=
pathover_cancel_left' !pathover_tr q
definition tr_pathover_of_pathover (q : b =[p ⬝ p₂] b₃) : p ▸ b =[p₂] b₃ :=
pathover_cancel_left !pathover_tr⁻¹ᵒ q
definition pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' :=
by cases q;apply pathover_tr
definition tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' :=
by cases q;apply tr_pathover
definition eq_of_parallel_po_right (q : b =[p] b₂) (q' : b =[p] b₂') : b₂ = b₂' :=
begin
apply @eq_of_pathover_idp A B, apply change_path (con.left_inv p),
exact q⁻¹ᵒ ⬝o q'
end
definition eq_of_parallel_po_left (q : b =[p] b₂) (q' : b' =[p] b₂) : b = b' :=
begin
apply @eq_of_pathover_idp A B, apply change_path (con.right_inv p),
exact q ⬝o q'⁻¹ᵒ
end
variable (C)
definition transporto (r : b =[p] b₂) (c : C b) : C b₂ :=
by induction r;exact c
infix ` ▸o `:75 := transporto _
definition fn_tro_eq_tro_fn {C' : Π ⦃a : A⦄, B a → Type} (q : b =[p] b₂)
(f : Π⦃a : A⦄ (b : B a), C b → C' b) (c : C b) : f b₂ (q ▸o c) = q ▸o (f b c) :=
by induction q; reflexivity
variable {C}
/- various variants of ap for pathovers -/
definition apd [unfold 6] (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ :=
by induction p; constructor
definition apo [unfold 12] {f : A → A'} (g : Πa, B a → B'' (f a)) (q : b =[p] b₂) :
g a b =[p] g a₂ b₂ :=
by induction q; constructor
definition apd011 [unfold 10] (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
: f a b = f a₂ b₂ :=
by cases Hb; reflexivity
definition apd0111 [unfold 13 14] (f : Πa b, C b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
(Hc : c =[apd011 C Ha Hb] c₂) : f a b c = f a₂ b₂ c₂ :=
by cases Hb; apply (idp_rec_on Hc); apply idp
definition apod11 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g)
{b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apd011 C p q] g b₂ :=
by cases r; apply (idp_rec_on q); constructor
definition apdo10 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g)
(b : B a) : f b =[apd011 C p !pathover_tr] g (p ▸ b) :=
by cases r; constructor
definition apo10 [unfold 9] {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g)
(b : B a) : f b =[p] g (p ▸ b) :=
by cases r; constructor
definition apo10_constant_right [unfold 9] {f : B a → A'} {g : B a₂ → A'} (r : f =[p] g)
(b : B a) : f b = g (p ▸ b) :=
by cases r; constructor
definition apo10_constant_left [unfold 9] {f : A' → B a} {g : A' → B a₂} (r : f =[p] g)
(a' : A') : f a' =[p] g a' :=
by cases r; constructor
definition apo11 {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g)
(q : b =[p] b₂) : f b =[p] g b₂ :=
by induction q; exact apo10 r b
definition apdo011 {A : Type} {B : A → Type} {C : Π⦃a⦄, B a → Type}
(f : Π⦃a⦄ (b : B a), C b) {a a' : A} (p : a = a') {b : B a} {b' : B a'} (q : b =[p] b')
: f b =[apd011 C p q] f b' :=
by cases q; constructor
definition apdo0111 {A : Type} {B : A → Type} {C C' : Π⦃a⦄, B a → Type}
(f : Π⦃a⦄ {b : B a}, C b → C' b) {a a' : A} (p : a = a') {b : B a} {b' : B a'} (q : b =[p] b')
{c : C b} {c' : C b'} (r : c =[apd011 C p q] c')
: f c =[apd011 C' p q] f c' :=
begin
induction q, esimp at r, induction r using idp_rec_on, constructor
end
definition apo11_constant_right [unfold 12] {f : B a → A'} {g : B a₂ → A'}
(q : f =[p] g) (r : b =[p] b₂) : f b = g b₂ :=
eq_of_pathover (apo11 q r)
/- properties about these "ap"s, transporto and pathover_ap -/
definition apd_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃)
: apd f (p ⬝ q) = apd f p ⬝o apd f q :=
by cases p; cases q; reflexivity
definition apd_inv (f : Πa, B a) (p : a = a₂) : apd f p⁻¹ = (apd f p)⁻¹ᵒ :=
by cases p; reflexivity
definition apd_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) :
apd f p = pathover_of_eq p (ap f p) :=
eq.rec_on p idp
definition apo_invo (f : Πa, B a → B' a) {Ha : a = a₂} (Hb : b =[Ha] b₂)
: (apo f Hb)⁻¹ᵒ = apo f Hb⁻¹ᵒ :=
by induction Hb; reflexivity
definition apd011_inv (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
: (apd011 f Ha Hb)⁻¹ = (apd011 f Ha⁻¹ Hb⁻¹ᵒ) :=
by induction Hb; reflexivity
definition cast_apd011 (q : b =[p] b₂) (c : C b) : cast (apd011 C p q) c = q ▸o c :=
by induction q; reflexivity
definition apd_compose1 (g : Πa, B a → B' a) (f : Πa, B a) (p : a = a₂)
: apd (g ∘' f) p = apo g (apd f p) :=
by induction p; reflexivity
definition apd_compose2 (g : Πa', B'' a') (f : A → A') (p : a = a₂)
: apd (λa, g (f a)) p = pathover_of_pathover_ap B'' f (apd g (ap f p)) :=
by induction p; reflexivity
definition apo_tro (C : Π⦃a⦄, B' a → Type) (f : Π⦃a⦄, B a → B' a) (q : b =[p] b₂)
(c : C (f b)) : apo f q ▸o c = q ▸o c :=
by induction q; reflexivity
definition pathover_ap_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A')
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b) : pathover_ap B' f q ▸o c = q ▸o c :=
by induction q; reflexivity
definition pathover_ap_invo_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A')
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b₂)
: (pathover_ap B' f q)⁻¹ᵒ ▸o c = q⁻¹ᵒ ▸o c :=
by induction q; reflexivity
definition pathover_tro (q : b =[p] b₂) (c : C b) : c =[apd011 C p q] q ▸o c :=
by induction q; constructor
definition pathover_ap_invo {B' : A' → Type} (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂)
: pathover_ap B' f q⁻¹ᵒ =[ap_inv f p] (pathover_ap B' f q)⁻¹ᵒ :=
by induction q; exact idpo
definition tro_invo_tro {A : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') (c : C b') :
q ▸o (q⁻¹ᵒ ▸o c) = c :=
by induction q; reflexivity
definition invo_tro_tro {A : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') (c : C b) :
q⁻¹ᵒ ▸o (q ▸o c) = c :=
by induction q; reflexivity
definition cono_tro {A : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a₁ a₂ a₃ : A} {p₁ : a₁ = a₂} {p₂ : a₂ = a₃} {b₁ : B a₁} {b₂ : B a₂} {b₃ : B a₃}
(q₁ : b₁ =[p₁] b₂) (q₂ : b₂ =[p₂] b₃) (c : C b₁) :
transporto C (q₁ ⬝o q₂) c = transporto C q₂ (transporto C q₁ c) :=
by induction q₂; reflexivity
definition is_equiv_transporto [constructor] {A : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : is_equiv (transporto C q) :=
begin
fapply adjointify,
{ exact transporto C q⁻¹ᵒ},
{ exact tro_invo_tro C q},
{ exact invo_tro_tro C q}
end
definition equiv_apd011 [constructor] {A : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : C b ≃ C b' :=
equiv.mk (transporto C q) !is_equiv_transporto
/- some cancellation laws for concato_eq an variants -/
definition cono.right_inv_eq (q : b = b') :
pathover_idp_of_eq q ⬝op q⁻¹ = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.right_inv_eq' (q : b = b') :
q ⬝po (pathover_idp_of_eq q⁻¹) = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.left_inv_eq (q : b = b') :
pathover_idp_of_eq q⁻¹ ⬝op q = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition cono.left_inv_eq' (q : b = b') :
q⁻¹ ⬝po pathover_idp_of_eq q = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition pathover_of_fn_pathover_fn (f : Π{a}, B a ≃ B' a) (r : f b =[p] f b₂) : b =[p] b₂ :=
(left_inv f b)⁻¹ ⬝po apo (λa, f⁻¹ᵉ) r ⬝op left_inv f b₂
/- a pathover in a pathover type where the only thing which varies is the path is the same as
an equality with a change_path -/
definition change_path_of_pathover (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂)
(q : r =[s] r') : change_path s r = r' :=
by induction s; eapply idp_rec_on q; reflexivity
definition pathover_of_change_path (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂)
(q : change_path s r = r') : r =[s] r' :=
by induction s; induction q; constructor
definition pathover_pathover_path [constructor] (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) :
(r =[s] r') ≃ change_path s r = r' :=
begin
fapply equiv.MK,
{ apply change_path_of_pathover},
{ apply pathover_of_change_path},
{ intro q, induction s, induction q, reflexivity},
{ intro q, induction s, eapply idp_rec_on q, reflexivity},
end
/- variants of inverse2 and concat2 -/
definition inverseo2 [unfold 10] {r r' : b =[p] b₂} (s : r = r') : r⁻¹ᵒ = r'⁻¹ᵒ :=
by induction s; reflexivity
definition concato2 [unfold 15 16] {r r' : b =[p] b₂} {r₂ r₂' : b₂ =[p₂] b₃}
(s : r = r') (s₂ : r₂ = r₂') : r ⬝o r₂ = r' ⬝o r₂' :=
by induction s; induction s₂; reflexivity
infixl ` ◾o `:75 := concato2
postfix [parsing_only] `⁻²ᵒ`:(max+10) := inverseo2 --this notation is abusive, should we use it?
-- find a better name for this
definition fn_tro_eq_tro_fn2 (q : b =[p] b₂)
{k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b))
(c : C b) :
m (q ▸o c) = (pathover_ap B k (apo l q)) ▸o (m c) :=
by induction q; reflexivity
definition apd0111_precompose (f : Π⦃a⦄ {b : B a}, C b → A')
{k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b))
{q : b =[p] b₂} (c : C b)
: apd0111 (λa b c, f (m c)) p q (pathover_tro q c) ⬝ ap (@f _ _) (fn_tro_eq_tro_fn2 q m c) =
apd0111 f (ap k p) (pathover_ap B k (apo l q)) (pathover_tro _ (m c)) :=
by induction q; reflexivity
end eq
|
b285a12e5441b75136c4b97572e52fdafa4fed8e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1657.lean | 51f008bcc1047ebc4b6ea63bddfda0d026152c5c | [
"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 | 744 | lean | abbrev natrec_inner {C} (n: Nat)
(z: Option C) (s: C -> Option C)
: Option C
:= match n with
| 0 => z
| n + 1 => (natrec_inner n z s).bind s
def natrec_int {C} (n: Option Nat) -- ERROR
(z: Option C) (s: C -> Option C)
: Option C
:= n.bind (λn => natrec_inner n z s)
@[inline_if_reduce]
def foo (xs : List Nat) :=
match xs with
| [] => 0
| _::xs => foo xs + 1
def error : Nat := -- ERROR
foo [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
set_option compiler.maxRecInlineIfReduce 32
def ok : Nat :=
foo [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
@[inline]
def foldr (f : Nat → β → β) (acc : β) : Nat → β
| 0 => acc
| n+1 => foldr f (f n acc) n
def toList (r : Nat) : List Nat :=
foldr (· :: ·) [] r
|
d8e0af4da0b88c6fe0fd890719dffdaa54f89ad2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/category/FinPartOrd.lean | 228a947fccd7a0fa3406186d96af44cb95560e91 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,842 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.Fintype
import order.category.PartOrd
/-!
# The category of finite partial orders
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This defines `FinPartOrd`, the category of finite partial orders.
Note: `FinPartOrd` is *not* a subcategory of `BddOrd` because finite orders are not necessarily
bounded.
## TODO
`FinPartOrd` is equivalent to a small category.
-/
universes u v
open category_theory
/-- The category of finite partial orders with monotone functions. -/
structure FinPartOrd :=
(to_PartOrd : PartOrd)
[is_fintype : fintype to_PartOrd]
namespace FinPartOrd
instance : has_coe_to_sort FinPartOrd Type* := ⟨λ X, X.to_PartOrd⟩
instance (X : FinPartOrd) : partial_order X := X.to_PartOrd.str
attribute [instance] FinPartOrd.is_fintype
@[simp] lemma coe_to_PartOrd (X : FinPartOrd) : ↥X.to_PartOrd = ↥X := rfl
/-- Construct a bundled `FinPartOrd` from `fintype` + `partial_order`. -/
def of (α : Type*) [partial_order α] [fintype α] : FinPartOrd := ⟨⟨α⟩⟩
@[simp] lemma coe_of (α : Type*) [partial_order α] [fintype α] : ↥(of α) = α := rfl
instance : inhabited FinPartOrd := ⟨of punit⟩
instance large_category : large_category FinPartOrd :=
induced_category.category FinPartOrd.to_PartOrd
instance concrete_category : concrete_category FinPartOrd :=
induced_category.concrete_category FinPartOrd.to_PartOrd
instance has_forget_to_PartOrd : has_forget₂ FinPartOrd PartOrd :=
induced_category.has_forget₂ FinPartOrd.to_PartOrd
instance has_forget_to_Fintype : has_forget₂ FinPartOrd Fintype :=
{ forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y, coe_fn } }
/-- Constructs an isomorphism of finite partial orders from an order isomorphism between them. -/
@[simps] def iso.mk {α β : FinPartOrd.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := e,
inv := e.symm,
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
/-- `order_dual` as a functor. -/
@[simps] def dual : FinPartOrd ⥤ FinPartOrd :=
{ obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual }
/-- The equivalence between `FinPartOrd` and itself induced by `order_dual` both ways. -/
@[simps functor inverse] def dual_equiv : FinPartOrd ≌ FinPartOrd :=
equivalence.mk dual dual
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
end FinPartOrd
lemma FinPartOrd_dual_comp_forget_to_PartOrd :
FinPartOrd.dual ⋙ forget₂ FinPartOrd PartOrd =
forget₂ FinPartOrd PartOrd ⋙ PartOrd.dual := rfl
|
172079b6ac4a3a044511236347b074a7e3537cf3 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/elab2.lean | b0b1e2be5f3e1d17a0184edbf582e2a66a3de992 | [
"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 | 1,027 | lean | variable C : forall (A B : Type) (H : A = B) (a : A), B
variable D : forall (A A' : Type) (B : A -> Type) (B' : A' -> Type) (H : (forall x : A, B x) = (forall x : A', B' x)), A = A'
variable R : forall (A A' : Type) (B : A -> Type) (B' : A' -> Type) (H : (forall x : A, B x) = (forall x : A', B' x)) (a : A),
(B a) = (B' (C A A' (D A A' B B' H) a))
theorem R2 (A A' B B' : Type) (H : (A -> B) = (A' -> B')) (a : A) : B = B' := R _ _ _ _ H a
print environment 1
theorem R3 : forall (A1 A2 B1 B2 : Type) (H : (A1 -> B1) = (A2 -> B2)) (a : A1), B1 = B2 :=
fun (A1 A2 B1 B2 : Type) (H : (A1 -> B1) = (A2 -> B2)) (a : A1),
R _ _ _ _ H a
theorem R4 : forall (A1 A2 B1 B2 : Type) (H : (A1 -> B1) = (A2 -> B2)) (a : A1), B1 = B2 :=
fun (A1 A2 B1 B2 : Type) (H : (A1 -> B1) = (A2 -> B2)) (a : _),
R _ _ _ _ H a
theorem R5 : forall (A1 A2 B1 B2 : Type) (H : (A1 -> B1) = (A2 -> B2)) (a : A1), B1 = B2 :=
fun (A1 A2 B1 B2 : Type) (H : _) (a : _),
R _ _ _ _ H a
print environment 1
|
d47d4dc9433288180880ae406325aa6efdca366d | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2021/logic/sheet2.lean | 18b7585b5cb1682bb65be10ec87e9c1027183ff2 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 1,357 | lean | /-
Copyright (c) 2021 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
/-!
# Logic in Lean, example sheet 2 : `true` and `false`
We learn about the `true` and `false` propositions.
## Tactics you will need
To solve the levels on this sheet you will need to know all previous
tactics, plus the following two new ones:
* `trivial`
* `exfalso`
### The `trivial` tactic
If your goal is `⊢ true` then `trivial,` will solve it.
### The `exfalso` tactic
The tactic `exfalso,` turns any goal `⊢ P` into `⊢ false`.
This is mathematically valid because `false` implies any goal.
-/
-- Throughout this sheet, `P`, `Q` and `R` will denote propositions.
variables (P Q R : Prop)
example : true :=
begin
sorry
end
example : true → true :=
begin
sorry
end
example : false → true :=
begin
sorry
end
example : false → false :=
begin
sorry
end
example : (true → false) → false :=
begin
sorry
end
example : false → P :=
begin
sorry
end
example : true → false → true → false → true → false :=
begin
sorry
end
example : P → ((P → false) → false) :=
begin
sorry
end
example : (P → false) → P → Q :=
begin
sorry
end
example : (true → false) → P :=
begin
sorry
end |
640a93dc5147055e78e7a917bfb7168e6bba1c98 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/set/intervals/unordered_interval.lean | 94be4bae717a4b1dde298f35a0a1cc3dd0cf975a | [
"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 | 9,993 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import order.bounds
import data.set.intervals.image_preimage
/-!
# Intervals without endpoints ordering
In any decidable linear order `α`, we define the set of elements lying between two elements `a` and
`b` as `Icc (min a b) (max a b)`.
`Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The
interval as defined in this file is always the set of things lying between `a` and `b`, regardless
of the relative order of `a` and `b`.
For real numbers, `Icc (min a b) (max a b)` is the same as `segment ℝ a b`.
## Notation
We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to
make the notation available.
-/
universe u
open_locale pointwise
namespace set
section linear_order
variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c x : α}
/-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/
def interval (a b : α) := Icc (min a b) (max a b)
localized "notation `[`a `, ` b `]` := set.interval a b" in interval
@[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b :=
by rw [interval, min_eq_left h, max_eq_right h]
@[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a :=
by { rw [interval, min_eq_right h, max_eq_left h] }
lemma interval_swap (a b : α) : [a, b] = [b, a] :=
by rw [interval, interval, min_comm, max_comm]
lemma interval_of_lt (h : a < b) : [a, b] = Icc a b :=
interval_of_le (le_of_lt h)
lemma interval_of_gt (h : b < a) : [a, b] = Icc b a :=
interval_of_ge (le_of_lt h)
lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a :=
interval_of_gt (lt_of_not_ge h)
lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b :=
interval_of_lt (lt_of_not_ge h)
@[simp] lemma interval_self : [a, a] = {a} :=
set.ext $ by simp [le_antisymm_iff, and_comm]
@[simp] lemma nonempty_interval : set.nonempty [a, b] :=
by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl }
@[simp] lemma left_mem_interval : a ∈ [a, b] :=
by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ }
@[simp] lemma right_mem_interval : b ∈ [a, b] :=
by { rw interval_swap, exact left_mem_interval }
lemma Icc_subset_interval : Icc a b ⊆ [a, b] :=
by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 }
lemma Icc_subset_interval' : Icc b a ⊆ [a, b] :=
by { rw interval_swap, apply Icc_subset_interval }
lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] :=
Icc_subset_interval ⟨ha, hb⟩
lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] :=
Icc_subset_interval' ⟨hb, ha⟩
lemma not_mem_interval_of_lt (ha : c < a) (hb : c < b) : c ∉ interval a b :=
not_mem_Icc_of_lt $ lt_min_iff.mpr ⟨ha, hb⟩
lemma not_mem_interval_of_gt (ha : a < c) (hb : b < c) : c ∉ interval a b :=
not_mem_Icc_of_gt $ max_lt_iff.mpr ⟨ha, hb⟩
lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] :=
Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2)
lemma interval_subset_Icc (ha : a₁ ∈ Icc a₂ b₂) (hb : b₁ ∈ Icc a₂ b₂) : [a₁, b₁] ⊆ Icc a₂ b₂ :=
Icc_subset_Icc (le_min ha.1 hb.1) (max_le ha.2 hb.2)
lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] :=
iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2)
lemma interval_subset_interval_iff_le :
[a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ :=
by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max }
lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] :=
interval_subset_interval h right_mem_interval
lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] :=
interval_subset_interval left_mem_interval h
/-- A sort of triangle inequality. -/
lemma interval_subset_interval_union_interval : [a, c] ⊆ [a, b] ∪ [b, c] :=
begin
rintro x hx,
obtain hac | hac := le_total a c,
{ rw interval_of_le hac at hx,
obtain hb | hb := le_total x b,
{ exact or.inl (mem_interval_of_le hx.1 hb) },
{ exact or.inr (mem_interval_of_le hb hx.2) } },
{ rw interval_of_ge hac at hx,
obtain hb | hb := le_total x b,
{ exact or.inr (mem_interval_of_ge hx.1 hb) },
{ exact or.inl (mem_interval_of_ge hb hx.2) } }
end
lemma bdd_below_bdd_above_iff_subset_interval (s : set α) :
bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] :=
begin
rw [bdd_below_bdd_above_iff_subset_Icc],
split,
{ rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ },
{ rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ }
end
/-- The open-closed interval with unordered bounds. -/
def interval_oc : α → α → set α := λ a b, Ioc (min a b) (max a b)
-- Below is a capital iota
localized "notation `Ι` := set.interval_oc" in interval
lemma interval_oc_of_le (h : a ≤ b) : Ι a b = Ioc a b :=
by simp [interval_oc, h]
lemma interval_oc_of_lt (h : b < a) : Ι a b = Ioc b a :=
by simp [interval_oc, le_of_lt h]
lemma interval_oc_eq_union : Ι a b = Ioc a b ∪ Ioc b a :=
by cases le_total a b; simp [interval_oc, *]
lemma forall_interval_oc_iff {P : α → Prop} :
(∀ x ∈ Ι a b, P x) ↔ (∀ x ∈ Ioc a b, P x) ∧ (∀ x ∈ Ioc b a, P x) :=
by simp only [interval_oc_eq_union, mem_union_eq, or_imp_distrib, forall_and_distrib]
lemma interval_oc_subset_interval_oc_of_interval_subset_interval {a b c d : α}
(h : [a, b] ⊆ [c, d]) : Ι a b ⊆ Ι c d :=
Ioc_subset_Ioc (interval_subset_interval_iff_le.1 h).1 (interval_subset_interval_iff_le.1 h).2
lemma interval_oc_swap (a b : α) : Ι a b = Ι b a :=
by simp only [interval_oc, min_comm a b, max_comm a b]
end linear_order
open_locale interval
section ordered_add_comm_group
variables {α : Type u} [linear_ordered_add_comm_group α] (a b c x y : α)
@[simp] lemma preimage_const_add_interval : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] :=
by simp only [interval, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right]
@[simp] lemma preimage_add_const_interval : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] :=
by simpa only [add_comm] using preimage_const_add_interval a b c
@[simp] lemma preimage_neg_interval : - [a, b] = [-a, -b] :=
by simp only [interval, preimage_neg_Icc, min_neg_neg, max_neg_neg]
@[simp] lemma preimage_sub_const_interval : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_const_sub_interval : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] :=
by { rw [interval, interval, preimage_const_sub_Icc],
simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], }
@[simp] lemma image_const_add_interval : (λ x, a + x) '' [b, c] = [a + b, a + c] :=
by simp [add_comm]
@[simp] lemma image_add_const_interval : (λ x, x + a) '' [b, c] = [b + a, c + a] :=
by simp
@[simp] lemma image_const_sub_interval : (λ x, a - x) '' [b, c] = [a - b, a - c] :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_sub_const_interval : (λ x, x - a) '' [b, c] = [b - a, c - a] :=
by simp [sub_eq_add_neg, add_comm]
lemma image_neg_interval : has_neg.neg '' [a, b] = [-a, -b] := by simp
variables {a b c x y}
/-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y`
is less than or equal to that of `a` and `b` -/
lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : |y - x| ≤ |b - a| :=
begin
rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs],
rw [interval_subset_interval_iff_le] at h,
exact sub_le_sub h.2 h.1,
end
/-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : |x - a| ≤ |b - a| :=
abs_sub_le_of_subinterval (interval_subset_interval_left h)
/-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : |b - x| ≤ |b - a| :=
abs_sub_le_of_subinterval (interval_subset_interval_right h)
end ordered_add_comm_group
section linear_ordered_field
variables {k : Type u} [linear_ordered_field k] {a : k}
@[simp] lemma preimage_mul_const_interval (ha : a ≠ 0) (b c : k) :
(λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] :=
(lt_or_gt_of_ne ha).elim
(λ ha, by simp [interval, ha, ha.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos])
(λ (ha : 0 < a), by simp [interval, ha, ha.le, min_div_div_right, max_div_div_right])
@[simp] lemma preimage_const_mul_interval (ha : a ≠ 0) (b c : k) :
(λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] :=
by simp only [← preimage_mul_const_interval ha, mul_comm]
@[simp] lemma preimage_div_const_interval (ha : a ≠ 0) (b c : k) :
(λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] :=
by simp only [div_eq_mul_inv, preimage_mul_const_interval (inv_ne_zero ha), inv_inv]
@[simp] lemma image_mul_const_interval (a b c : k) : (λ x, x * a) '' [b, c] = [b * a, c * a] :=
if ha : a = 0 then by simp [ha] else
calc (λ x, x * a) '' [b, c] = (λ x, x * a⁻¹) ⁻¹' [b, c] :
(units.mk0 a ha).mul_right.image_eq_preimage _
... = (λ x, x / a) ⁻¹' [b, c] : by simp only [div_eq_mul_inv]
... = [b * a, c * a] : preimage_div_const_interval ha _ _
@[simp] lemma image_const_mul_interval (a b c : k) : (λ x, a * x) '' [b, c] = [a * b, a * c] :=
by simpa only [mul_comm] using image_mul_const_interval a b c
@[simp] lemma image_div_const_interval (a b c : k) : (λ x, x / a) '' [b, c] = [b / a, c / a] :=
by simp only [div_eq_mul_inv, image_mul_const_interval]
end linear_ordered_field
end set
|
a045da9bfbc4c3d2a74bce256952fa621c77265e | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/analysis/mean_inequalities.lean | cc562ed90d2d034007abf1a3a5e56707a7e548cf | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 24,645 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Sébastien Gouëzel
-/
import analysis.convex.specific_functions
import analysis.special_functions.pow
import data.real.conjugate_exponents
import tactic.nth_rewrite
/-!
# Mean value inequalities
In this file we prove several inequalities, including AM-GM inequality, Young's inequality,
Hölder inequality, and Minkowski inequality.
## Main theorems
### AM-GM inequality:
The inequality says that the geometric mean of a tuple of non-negative numbers is less than or equal
to their arithmetic mean. We prove the weighted version of this inequality: if $w$ and $z$
are two non-negative vectors and $\sum_{i\in s} w_i=1$, then
$$
\prod_{i\in s} z_i^{w_i} ≤ \sum_{i\in s} w_iz_i.
$$
The classical version is a special case of this inequality for $w_i=\frac{1}{n}$.
We prove a few versions of this inequality. Each of the following lemmas comes in two versions:
a version for real-valued non-negative functions is in the `real` namespace, and a version for
`nnreal`-valued functions is in the `nnreal` namespace.
- `geom_mean_le_arith_mean_weighted` : weighted version for functions on `finset`s;
- `geom_mean_le_arith_mean2_weighted` : weighted version for two numbers;
- `geom_mean_le_arith_mean3_weighted` : weighted version for three numbers;
- `geom_mean_le_arith_mean4_weighted` : weighted version for four numbers.
### Generalized mean inequality
The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$
and $p ≤ q$ we have
$$
\sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}.
$$
Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide
different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents
(`fpow_arith_mean_le_arith_mean_fpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and
`arith_mean_le_rpow_mean`). In the first two cases we prove
$$
\left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n
$$
in order to avoid using real exponents. For real exponents we prove both this and standard versions.
### Young's inequality
Young's inequality says that for non-negative numbers `a`, `b`, `p`, `q` such that
$\frac{1}{p}+\frac{1}{q}=1$ we have
$$
ab ≤ \frac{a^p}{p} + \frac{b^q}{q}.
$$
This inequality is a special case of the AM-GM inequality. It can be used to prove Hölder's
inequality (see below) but we use a different proof.
### Hölder's inequality
The inequality says that for two conjugate exponents `p` and `q` (i.e., for two positive numbers
such that $\frac{1}{p}+\frac{1}{q}=1$) and any two non-negative vectors their inner product is
less than or equal to the product of the $L_p$ norm of the first vector and the $L_q$ norm of the
second vector:
$$
\sum_{i\in s} a_ib_i ≤ \sqrt[p]{\sum_{i\in s} a_i^p}\sqrt[q]{\sum_{i\in s} b_i^q}.
$$
We give versions of this result in `real`, `nnreal` and `ennreal`.
There are at least two short proofs of this inequality. In one proof we prenormalize both vectors,
then apply Young's inequality to each $a_ib_i$. We use a different proof deducing this inequality
from the generalized mean inequality for well-chosen vectors and weights.
### Minkowski's inequality
The inequality says that for `p ≥ 1` the function
$$
\|a\|_p=\sqrt[p]{\sum_{i\in s} a_i^p}
$$
satisfies the triangle inequality $\|a+b\|_p\le \|a\|_p+\|b\|_p$.
We give versions of this result in `real`, `nnreal` and `ennreal`.
We deduce this inequality from Hölder's inequality. Namely, Hölder inequality implies that $\|a\|_p$
is the maximum of the inner product $\sum_{i\in s}a_ib_i$ over `b` such that $\|b\|_q\le 1$. Now
Minkowski's inequality follows from the fact that the maximum value of the sum of two functions is
less than or equal to the sum of the maximum values of the summands.
## TODO
- each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them
is to define `strict_convex_on` functions.
- generalized mean inequality with any `p ≤ q`, including negative numbers;
- prove that the power mean tends to the geometric mean as the exponent tends to zero.
- prove integral versions of these inequalities.
-/
universes u v
open finset
open_locale classical nnreal big_operators
noncomputable theory
variables {ι : Type u} (s : finset ι)
namespace real
/-- AM-GM inequality: the geometric mean is less than or equal to the arithmetic mean, weighted version
for real-valued nonnegative functions. -/
theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) :
(∏ i in s, (z i) ^ (w i)) ≤ ∑ i in s, w i * z i :=
begin
-- If some number `z i` equals zero and has non-zero weight, then LHS is 0 and RHS is nonnegative.
by_cases A : ∃ i ∈ s, z i = 0 ∧ w i ≠ 0,
{ rcases A with ⟨i, his, hzi, hwi⟩,
rw [prod_eq_zero his],
{ exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) },
{ rw hzi, exact zero_rpow hwi } },
-- If all numbers `z i` with non-zero weight are positive, then we apply Jensen's inequality
-- for `exp` and numbers `log (z i)` with weights `w i`.
{ simp only [not_exists, not_and, ne.def, not_not] at A,
have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)),
simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this,
convert this using 1; [apply prod_congr rfl, apply sum_congr rfl]; intros i hi,
{ cases eq_or_lt_of_le (hz i hi) with hz hz,
{ simp [A i hi hz.symm] },
{ exact rpow_def_of_pos hz _ } },
{ cases eq_or_lt_of_le (hz i hi) with hz hz,
{ simp [A i hi hz.symm] },
{ rw [exp_log hz] } } }
end
theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) :
(∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) :=
(convex_on_pow n).map_sum_le hw hw' hz
theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : even n) :
(∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) :=
(convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial)
theorem fpow_arith_mean_le_arith_mean_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) :
(∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) :=
(convex_on_fpow m).map_sum_le hw hw' hz
theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) :
(∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) :=
(convex_on_rpow hp).map_sum_le hw hw' hz
theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) :
∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) :=
begin
have : 0 < p := lt_of_lt_of_le zero_lt_one hp,
rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one],
exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp,
all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg],
intros i hi,
apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] },
end
end real
namespace nnreal
/-- The geometric mean is less than or equal to the arithmetic mean, weighted version
for `nnreal`-valued functions. -/
theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) :
(∏ i in s, (z i) ^ (w i:ℝ)) ≤ ∑ i in s, w i * z i :=
by exact_mod_cast real.geom_mean_le_arith_mean_weighted _ _ _ (λ i _, (w i).coe_nonneg)
(by assumption_mod_cast) (λ i _, (z i).coe_nonneg)
/-- The geometric mean is less than or equal to the arithmetic mean, weighted version
for two `nnreal` numbers. -/
theorem geom_mean_le_arith_mean2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) :
w₁ + w₂ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ :=
by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero,
fin.cons_succ, fin.cons_zero, add_zero, mul_one]
using geom_mean_le_arith_mean_weighted (univ : finset (fin 2))
(fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim)
theorem geom_mean_le_arith_mean3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) :
w₁ + w₂ + w₃ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ :=
by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero,
fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc]
using geom_mean_le_arith_mean_weighted (univ : finset (fin 3))
(fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim)
(fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim)
theorem geom_mean_le_arith_mean4_weighted (w₁ w₂ w₃ w₄ p₁ p₂ p₃ p₄ : ℝ≥0) :
w₁ + w₂ + w₃ + w₄ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ)* p₄ ^ (w₄:ℝ) ≤
w₁ * p₁ + w₂ * p₂ + w₃ * p₃ + w₄ * p₄ :=
by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero,
fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc]
using geom_mean_le_arith_mean_weighted (univ : finset (fin 4))
(fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ $ fin.cons w₄ fin_zero_elim)
(fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ $ fin.cons p₄ fin_zero_elim)
/-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued
functions and natural exponent. -/
theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) :
(∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) :=
by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg)
(by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n
/-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued
functions and real exponents. -/
theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ}
(hp : 1 ≤ p) :
(∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) :=
by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg)
(by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp
/-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued
functions and real exponents. -/
theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ}
(hp : 1 ≤ p) :
∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) :=
by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg)
(by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp
end nnreal
namespace real
theorem geom_mean_le_arith_mean2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂)
(hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) :
p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ :=
nnreal.geom_mean_le_arith_mean2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $
nnreal.coe_eq.1 $ by assumption
theorem geom_mean_le_arith_mean3_weighted {w₁ w₂ w₃ p₁ p₂ p₃ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂)
(hw₃ : 0 ≤ w₃) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hp₃ : 0 ≤ p₃) (hw : w₁ + w₂ + w₃ = 1) :
p₁ ^ w₁ * p₂ ^ w₂ * p₃ ^ w₃ ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ :=
nnreal.geom_mean_le_arith_mean3_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨w₃, hw₃⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ ⟨p₃, hp₃⟩ $
nnreal.coe_eq.1 $ by assumption
theorem geom_mean_le_arith_mean4_weighted {w₁ w₂ w₃ w₄ p₁ p₂ p₃ p₄ : ℝ} (hw₁ : 0 ≤ w₁)
(hw₂ : 0 ≤ w₂) (hw₃ : 0 ≤ w₃) (hw₄ : 0 ≤ w₄) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hp₃ : 0 ≤ p₃)
(hp₄ : 0 ≤ p₄) (hw : w₁ + w₂ + w₃ + w₄ = 1) :
p₁ ^ w₁ * p₂ ^ w₂ * p₃ ^ w₃ * p₄ ^ w₄ ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ + w₄ * p₄ :=
nnreal.geom_mean_le_arith_mean4_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨w₃, hw₃⟩ ⟨w₄, hw₄⟩
⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ ⟨p₃, hp₃⟩ ⟨p₄, hp₄⟩ $ nnreal.coe_eq.1 $ by assumption
/-- Young's inequality, a version for nonnegative real numbers. -/
theorem young_inequality_of_nonneg {a b p q : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b)
(hpq : p.is_conjugate_exponent q) :
a * b ≤ a^p / p + b^q / q :=
by simpa [← rpow_mul, ha, hb, hpq.ne_zero, hpq.symm.ne_zero, div_eq_inv_mul]
using geom_mean_le_arith_mean2_weighted hpq.one_div_nonneg hpq.symm.one_div_nonneg
(rpow_nonneg_of_nonneg ha p) (rpow_nonneg_of_nonneg hb q) hpq.inv_add_inv_conj
/-- Young's inequality, a version for arbitrary real numbers. -/
theorem young_inequality (a b : ℝ) {p q : ℝ} (hpq : p.is_conjugate_exponent q) :
a * b ≤ (abs a)^p / p + (abs b)^q / q :=
calc a * b ≤ abs (a * b) : le_abs_self (a * b)
... = abs a * abs b : abs_mul a b
... ≤ (abs a)^p / p + (abs b)^q / q :
real.young_inequality_of_nonneg (abs_nonneg a) (abs_nonneg b) hpq
end real
namespace nnreal
/-- Young's inequality, `ℝ≥0` version. We use `{p q : ℝ≥0}` in order to avoid constructing
witnesses of `0 ≤ p` and `0 ≤ q` for the denominators. -/
theorem young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hpq : 1 / p + 1 / q = 1) :
a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q :=
real.young_inequality_of_nonneg a.coe_nonneg b.coe_nonneg ⟨hp, nnreal.coe_eq.2 hpq⟩
/-- Hölder inequality: the scalar product of two functions is bounded by the product of their
`L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets,
with `ℝ≥0`-valued functions. -/
theorem inner_le_Lp_mul_Lq (f g : ι → ℝ≥0) {p q : ℝ}
(hpq : p.is_conjugate_exponent q) :
∑ i in s, f i * g i ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) * (∑ i in s, (g i) ^ q) ^ (1 / q) :=
begin
-- Let `G=∥g∥_q` be the `L_q`-norm of `g`.
set G := (∑ i in s, (g i) ^ q) ^ (1 / q),
have hGq : G ^ q = ∑ i in s, (g i) ^ q,
{ rw [← rpow_mul, one_div_mul_cancel hpq.symm.ne_zero, rpow_one], },
-- First consider the trivial case `∥g∥_q=0`
by_cases hG : G = 0,
{ rw [hG, sum_eq_zero, mul_zero],
intros i hi,
simp only [rpow_eq_zero_iff, sum_eq_zero_iff] at hG,
simp [(hG.1 i hi).1] },
{ -- Move power from right to left
rw [← div_le_iff hG, sum_div],
-- Now the inequality follows from the weighted generalized mean inequality
-- with weights `w_i` and numbers `z_i` given by the following formulas.
set w : ι → ℝ≥0 := λ i, (g i) ^ q / G ^ q,
set z : ι → ℝ≥0 := λ i, f i * (G / g i) ^ (q / p),
-- Show that the sum of weights equals one
have A : ∑ i in s, w i = 1,
{ rw [← sum_div, hGq, div_self],
simpa [rpow_eq_zero_iff, hpq.symm.ne_zero] using hG },
-- LHS of the goal equals LHS of the weighted generalized mean inequality
calc (∑ i in s, f i * g i / G) = (∑ i in s, w i * z i) :
begin
refine sum_congr rfl (λ i hi, _),
have : q - q / p = 1, by field_simp [hpq.ne_zero, hpq.symm.mul_eq_add],
dsimp only [w, z],
rw [← div_rpow, mul_left_comm, mul_div_assoc, ← @inv_div _ _ _ G, inv_rpow,
← div_eq_mul_inv, ← rpow_sub']; simp [this]
end
-- Apply the generalized mean inequality
... ≤ (∑ i in s, w i * (z i) ^ p) ^ (1 / p) :
nnreal.arith_mean_le_rpow_mean s w z A (le_of_lt hpq.one_lt)
-- Simplify the right hand side. Terms with `g i ≠ 0` are equal to `(f i) ^ p`,
-- the others are zeros.
... ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) :
begin
refine rpow_le_rpow (sum_le_sum (λ i hi, _)) hpq.one_div_nonneg,
dsimp only [w, z],
rw [mul_rpow, mul_left_comm, ← rpow_mul _ _ p, div_mul_cancel _ hpq.ne_zero, div_rpow,
div_mul_div, mul_comm (G ^ q), mul_div_mul_right],
{ nth_rewrite 1 [← mul_one ((f i) ^ p)],
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (div_self_le _) },
{ simpa [hpq.symm.ne_zero] using hG }
end }
end
/-- The `L_p` seminorm of a vector `f` is the greatest value of the inner product
`∑ i in s, f i * g i` over functions `g` of `L_q` seminorm less than or equal to one. -/
theorem is_greatest_Lp (f : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) :
is_greatest ((λ g : ι → ℝ≥0, ∑ i in s, f i * g i) ''
{g | ∑ i in s, (g i)^q ≤ 1}) ((∑ i in s, (f i)^p) ^ (1 / p)) :=
begin
split,
{ use λ i, ((f i) ^ p / f i / (∑ i in s, (f i) ^ p) ^ (1 / q)),
by_cases hf : ∑ i in s, (f i)^p = 0,
{ simp [hf, hpq.ne_zero, hpq.symm.ne_zero] },
{ have A : p + q - q ≠ 0, by simp [hpq.ne_zero],
have B : ∀ y : ℝ≥0, y * y^p / y = y^p,
{ refine λ y, mul_div_cancel_left_of_imp (λ h, _),
simpa [h, hpq.ne_zero] },
simp only [set.mem_set_of_eq, div_rpow, ← sum_div, ← rpow_mul,
div_mul_cancel _ hpq.symm.ne_zero, rpow_one, div_le_iff hf, one_mul, hpq.mul_eq_add,
← rpow_sub' _ A, _root_.add_sub_cancel, le_refl, true_and, ← mul_div_assoc, B],
rw [div_eq_iff, ← rpow_add hf, hpq.inv_add_inv_conj, rpow_one],
simpa [hpq.symm.ne_zero] using hf } },
{ rintros _ ⟨g, hg, rfl⟩,
apply le_trans (inner_le_Lp_mul_Lq s f g hpq),
simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul (le_refl _)
(nnreal.rpow_le_one hg (le_of_lt hpq.symm.one_div_pos)) }
end
/-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal
to the sum of the `L_p`-seminorms of the summands. A version for `nnreal`-valued functions. -/
theorem Lp_add_le (f g : ι → ℝ≥0) {p : ℝ} (hp : 1 ≤ p) :
(∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤
(∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) :=
begin
-- The result is trivial when `p = 1`, so we can assume `1 < p`.
rcases eq_or_lt_of_le hp with rfl|hp, { simp [finset.sum_add_distrib] },
have hpq := real.is_conjugate_exponent_conjugate_exponent hp,
have := is_greatest_Lp s (f + g) hpq,
simp only [pi.add_apply, add_mul, sum_add_distrib] at this,
rcases this.1 with ⟨φ, hφ, H⟩,
rw ← H,
exact add_le_add ((is_greatest_Lp s f hpq).2 ⟨φ, hφ, rfl⟩)
((is_greatest_Lp s g hpq).2 ⟨φ, hφ, rfl⟩)
end
end nnreal
namespace real
variables (f g : ι → ℝ) {p q : ℝ}
/-- Hölder inequality: the scalar product of two functions is bounded by the product of their
`L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets,
with real-valued functions. -/
theorem inner_le_Lp_mul_Lq (hpq : is_conjugate_exponent p q) :
∑ i in s, f i * g i ≤ (∑ i in s, (abs $ f i)^p) ^ (1 / p) * (∑ i in s, (abs $ g i)^q) ^ (1 / q) :=
begin
have := nnreal.coe_le_coe.2 (nnreal.inner_le_Lp_mul_Lq s (λ i, ⟨_, abs_nonneg (f i)⟩)
(λ i, ⟨_, abs_nonneg (g i)⟩) hpq),
push_cast at this,
refine le_trans (sum_le_sum $ λ i hi, _) this,
simp only [← abs_mul, le_abs_self]
end
/-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal
to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued functions. -/
theorem Lp_add_le (hp : 1 ≤ p) :
(∑ i in s, (abs $ f i + g i) ^ p) ^ (1 / p) ≤
(∑ i in s, (abs $ f i) ^ p) ^ (1 / p) + (∑ i in s, (abs $ g i) ^ p) ^ (1 / p) :=
begin
have := nnreal.coe_le_coe.2 (nnreal.Lp_add_le s (λ i, ⟨_, abs_nonneg (f i)⟩)
(λ i, ⟨_, abs_nonneg (g i)⟩) hp),
push_cast at this,
refine le_trans (rpow_le_rpow _ (sum_le_sum $ λ i hi, _) _) this;
simp [sum_nonneg, rpow_nonneg_of_nonneg, abs_nonneg, le_trans zero_le_one hp, abs_add,
rpow_le_rpow]
end
variables {f g}
/-- Hölder inequality: the scalar product of two functions is bounded by the product of their
`L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets,
with real-valued nonnegative functions. -/
theorem inner_le_Lp_mul_Lq_of_nonneg (hpq : is_conjugate_exponent p q)
(hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) :
∑ i in s, f i * g i ≤ (∑ i in s, (f i)^p) ^ (1 / p) * (∑ i in s, (g i)^q) ^ (1 / q) :=
by convert inner_le_Lp_mul_Lq s f g hpq using 3; apply sum_congr rfl; intros i hi;
simp only [abs_of_nonneg, hf i hi, hg i hi]
/-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal
to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued nonnegative
functions. -/
theorem Lp_add_le_of_nonneg (hp : 1 ≤ p) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) :
(∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤
(∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) :=
by convert Lp_add_le s f g hp using 2 ; [skip, congr' 1, congr' 1];
apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi, add_nonneg]
end real
namespace ennreal
variables (f g : ι → ennreal) {p q : ℝ}
/-- Hölder inequality: the scalar product of two functions is bounded by the product of their
`L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets,
with `ennreal`-valued functions. -/
theorem inner_le_Lp_mul_Lq (hpq : p.is_conjugate_exponent q) :
(∑ i in s, f i * g i) ≤ (∑ i in s, (f i)^p) ^ (1/p) * (∑ i in s, (g i)^q) ^ (1/q) :=
begin
by_cases H : (∑ i in s, (f i)^p) ^ (1/p) = 0 ∨ (∑ i in s, (g i)^q) ^ (1/q) = 0,
{ replace H : (∀ i ∈ s, f i = 0) ∨ (∀ i ∈ s, g i = 0),
by simpa [ennreal.rpow_eq_zero_iff, hpq.pos, hpq.symm.pos, asymm hpq.pos, asymm hpq.symm.pos,
sum_eq_zero_iff_of_nonneg] using H,
have : ∀ i ∈ s, f i * g i = 0 := λ i hi, by cases H; simp [H i hi],
have : (∑ i in s, f i * g i) = (∑ i in s, 0) := sum_congr rfl this,
simp [this] },
push_neg at H,
by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^q) ^ (1/q) = ⊤,
{ cases H'; simp [H', -one_div, H] },
replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤),
by simpa [ennreal.rpow_eq_top_iff, asymm hpq.pos, asymm hpq.symm.pos, hpq.pos, hpq.symm.pos,
ennreal.sum_eq_top_iff, not_or_distrib] using H',
have := ennreal.coe_le_coe.2 (@nnreal.inner_le_Lp_mul_Lq _ s (λ i, ennreal.to_nnreal (f i))
(λ i, ennreal.to_nnreal (g i)) _ _ hpq),
simp [← ennreal.coe_rpow_of_nonneg, le_of_lt (hpq.pos), le_of_lt (hpq.one_div_pos),
le_of_lt (hpq.symm.pos), le_of_lt (hpq.symm.one_div_pos)] at this,
convert this using 1;
[skip, congr' 2];
[skip, skip, simp, skip, simp];
{ apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi, -with_zero.coe_mul,
with_top.coe_mul.symm] },
end
/-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal
to the sum of the `L_p`-seminorms of the summands. A version for `ennreal` valued nonnegative
functions. -/
theorem Lp_add_le (hp : 1 ≤ p) :
(∑ i in s, (f i + g i) ^ p)^(1/p) ≤ (∑ i in s, (f i)^p) ^ (1/p) + (∑ i in s, (g i)^p) ^ (1/p) :=
begin
by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^p) ^ (1/p) = ⊤,
{ cases H'; simp [H', -one_div] },
have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp,
replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤),
by simpa [ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff,
not_or_distrib] using H',
have := ennreal.coe_le_coe.2 (@nnreal.Lp_add_le _ s (λ i, ennreal.to_nnreal (f i))
(λ i, ennreal.to_nnreal (g i)) _ hp),
push_cast [← ennreal.coe_rpow_of_nonneg, le_of_lt (pos), le_of_lt (one_div_pos.2 pos)] at this,
convert this using 2;
[skip, congr' 1, congr' 1];
{ apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi] }
end
end ennreal
|
e470c053708cf6c68e449a3387b5e6527729428f | 392d28f7e76ae84b38b6424255b29b4a4af0d129 | /inClassNotes/higherOrderFunctions/composeTest.lean | 27c2274c14ab6b472a61443e2fe097ba968944ee | [] | no_license | dg-1225/complogic-s21 | dd7349fd5288ec6c7bad3b0fe27987cfe176dc67 | f46b0bce48bbefbfbcdbc3da904a85c5f643ef58 | refs/heads/master | 1,678,017,116,497 | 1,613,794,266,000 | 1,613,794,266,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,615 | lean | /-
Let's build up to notion of
higher-order functions.
-/
namespace hidden
-- Increment functions
def inc (n : nat) := n + 1
def sqr (n : nat) := n * n
def incThenSqr (n : nat) := sqr (inc n)
/-
36 <-- sqr <-- inc <-- 5
Think of data flowing right to left
through a composition of functions:
given n (on the right) first send it
through inc, then send that result
"to the left" through sqr.
-/
-/
def sqrThenInc (n : nat) := inc (sqr n)
/-
26 <-- inc <-- sqr <-- 5
-/
#eval incThenSqr 5
#eval sqrThenInc 5
/-
A diagram of the evaluation order
36 <-- (sqr <-- (inc <-- 5))
26 <-- (inc <-- (sqr <-- 5))
-/
/-
Regrouping parenthesis tells us that
sending the input through two functions
right to left is equivalent to running
it through a single function, one that
"combines" the effects of the two.
36 <-- (sqr <-- inc) <-- 5)
^^^^^^^^^^^^^
a function
26 <-- (inc <-- sqr) <-- 5)
^^^^^^^^^^^^^
a function
-/
/-
36 <-- (compose sqr inc) <-- 5)
26 <-- (compose inc sqr) <-- 5)
^^^^^^^^^^^^^^^^^
a function
-/
/-
36 <-- (compose sqr inc) <-- 5)
26 <-- (compose inc sqr) <-- 5)
^^^^^^^
higher-order function
-/
/-
Remember that a lambda term is
a literal value that represents
a function. What's special about
the form of data is that it can
be *applied* to an argument to
produce a result.
A higher-order function is just
a function that takes a lambda
term (aka "a function") as an
argument and/or returns one as
a result. In particular, we will
often want to define functions
that not only take "functions"
as arguments but that return
new functions as results, where
the new functions, *when applied*
use given functions to compute
results.
Such a higher-order function is a
machine that takes smaller data
consuming and producing machines
(functions) and combines them into
larger/new data consuming and
producing machines. Composition
of functions is a special case in
which a new function is returned
that, when applied to an argument,
applies each of the given functions
in turn.
-/
/-
36 <-- (sqr ∘ inc) <-- 5)
26 <-- (inc ∘ sqr) <-- 5)
-/
/-
Can we write a function that
takes two smaller functions,
f and g, and that returns a
function, (g ∘ f), that first
applies f to its argument and
then applies g to that result?
Let's try this for the special
case of two argument functions,
such as sqr and inc, each being
of type nat → nat.
-/
def compose_nat_nat (g f: ℕ → ℕ) :
(ℕ → ℕ) :=
_
-- let's test it out
#eval (compose_nat_nat sqr inc) 5
-- ^^^^^^^^^^^^^^^^^^^^^^^^^ function!
def sqrinc := compose_nat_nat sqr inc
#eval sqrinc 5
#eval (compose_nat_nat inc sqr) 5
def incsqr := compose_nat_nat inc sqr
#eval incsrq 5
/-
Suppose we want to compose functions
that have different types. The return
type of one has to match the argument
type of the next one in the pipeline.
Parametric polymorphism to the rescue.
-/
def compose_α_β_φ { α β φ : Type }
(g : β → φ) (f: α → β) : α → φ :=
_
#eval (compose_α_β_φ sqr string.length) "Hello!"
/-
The previous version works great as
long as the functions all takes values
of types, α, β, and φ, of type Type.
But in general, we'll want a function
that can operate on functions that
take arguments and that return results
in arbitrary type universes. So here,
then is the most general form of our
higher-order compose function.
-/
universes u₁ u₂ u₃ -- plural of universe
def compose
{α : Type u₁}
{β : Type u₂}
{φ : Type u₃}
(g : β → φ)
(f: α → β) :
α → φ :=
fun a, g (f a)
/-
Return a *function* that takes
one argument, a, and returns the
result of applying g to the result
of applying f to a.
-/
def incThenSqr' := compose sqr inc
def sqrThenInc' := compose inc sqr
def sqrlen := compose sqr string.length
#eval incThenSqr 5 -- expect 36
#eval incThenSqr 5 -- expect 26
#eval sqrlen "Hello!"
/-
Lean implements function composition
as function.comp, with ∘ as an infix
notation for this binary operation.
-/
#check function.comp
#check @function.comp
/-
function.comp :
Π {α : Sort u_1} {β : Sort u_2} {φ : Sort u_3},
(β → φ) → (α → β) → α → φ
-/
/-
Prop (Sort 0) -- logic
Type (Type 0) Sort 1 -- computation
Type 1 Sort 2
Type 2 Sort 3
etc
-/
universes u₁ u₂ u₃
-- introduce some local assumptions
variables (f : Sort u₁ → Sort u₂) (g : Sort u₂ → Sort u₃)
#check function.comp g f
#check g ∘ f
end hidden |
9865d6cd1f2ddfd303d39f9922a1798634d70e52 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/list/forall2.lean | 3c04c6b97d7989d07eff92886ba56399a4dd07f3 | [
"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,378 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import data.list.infix
/-!
# Double universal quantification on a list
This file provides an API for `list.forall₂` (definition in `data.list.defs`).
`forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element
of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied.
-/
open nat function
namespace list
variables {α β γ δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
open relator
mk_iff_of_inductive_prop list.forall₂ list.forall₂_iff
@[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} :
forall₂ R (a :: l₁) (b :: l₂) ↔ R a b ∧ forall₂ R l₁ l₂ :=
⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩
theorem forall₂.imp {R S : α → β → Prop}
(H : ∀ a b, R a b → S a b) {l₁ l₂}
(h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ :=
by induction h; constructor; solve_by_elim
lemma forall₂.mp {r q s : α → β → Prop} (h : ∀ a b, r a b → q a b → s a b) :
∀ {l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂
| [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a :: l₁) (b :: l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs)
lemma forall₂.flip : ∀ {a b}, forall₂ (flip r) b a → forall₂ r a b
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip
@[simp] lemma forall₂_same {r : α → α → Prop} : ∀ {l : list α}, forall₂ r l l ↔ ∀ x ∈ l, r x x
| [] := by simp
| (a :: l) := by simp [@forall₂_same l]
lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l :=
forall₂_same.2 $ λ a h, refl _
@[simp] lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) :=
begin
funext a b, apply propext,
split,
{ intro h, induction h, {refl}, simp only [*]; split; refl },
{ rintro rfl, exact forall₂_refl _ }
end
@[simp, priority 900] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
@[simp, priority 900] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
lemma forall₂_cons_left_iff {a l u} :
forall₂ r (a :: l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') :=
iff.intro
(λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_cons_right_iff {b l u} :
forall₂ r u (b :: l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') :=
iff.intro
(λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} :
∀ l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀ a∈l, p a) ∧ forall₂ r l u
| [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _),
imp_true_iff, true_and]
| (a :: l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons,
and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm]
@[simp] lemma forall₂_map_left_iff {f : γ → α} :
∀ {l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u
| [] _ := by simp only [map, forall₂_nil_left_iff]
| (a :: l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp] lemma forall₂_map_right_iff {f : γ → β} :
∀ {l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u
| _ [] := by simp only [map, forall₂_nil_right_iff]
| _ (b :: u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
lemma left_unique_forall₂' (hr : left_unique r) :
∀ {a b c}, forall₂ r a c → forall₂ r b c → a = b
| a₀ nil a₁ forall₂.nil forall₂.nil := rfl
| (a₀ :: l₀) (b :: l) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ left_unique_forall₂' h₀ h₁ ▸ rfl
lemma _root_.relator.left_unique.forall₂ (hr : left_unique r) : left_unique (forall₂ r) :=
@left_unique_forall₂' _ _ _ hr
lemma right_unique_forall₂' (hr : right_unique r) : ∀ {a b c}, forall₂ r a b → forall₂ r a c → b = c
| nil a₀ a₁ forall₂.nil forall₂.nil := rfl
| (b :: l) (a₀ :: l₀) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ right_unique_forall₂' h₀ h₁ ▸ rfl
lemma _root_.relator.right_unique.forall₂ (hr : right_unique r) : right_unique (forall₂ r) :=
@right_unique_forall₂' _ _ _ hr
lemma _root_.relator.bi_unique.forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) :=
⟨hr.left.forall₂, hr.right.forall₂⟩
theorem forall₂.length_eq {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂
| _ _ forall₂.nil := rfl
| _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂.length_eq h₂)
theorem forall₂.nth_le :
∀ {x : list α} {y : list β} (h : forall₂ r x y) ⦃i : ℕ⦄ (hx : i < x.length) (hy : i < y.length),
r (x.nth_le i hx) (y.nth_le i hy)
| (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) 0 hx hy := ha
| (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) (succ i) hx hy := hl.nth_le _ _
lemma forall₂_of_length_eq_of_nth_le : ∀ {x : list α} {y : list β},
x.length = y.length → (∀ i h₁ h₂, r (x.nth_le i h₁) (y.nth_le i h₂)) → forall₂ r x y
| [] [] hl h := forall₂.nil
| (a₁ :: l₁) (a₂ :: l₂) hl h := forall₂.cons
(h 0 (nat.zero_lt_succ _) (nat.zero_lt_succ _))
(forall₂_of_length_eq_of_nth_le (succ.inj hl) (
λ i h₁ h₂, h i.succ (succ_lt_succ h₁) (succ_lt_succ h₂)))
theorem forall₂_iff_nth_le {l₁ : list α} {l₂ : list β} :
forall₂ r l₁ l₂ ↔ l₁.length = l₂.length ∧ ∀ i h₁ h₂, r (l₁.nth_le i h₁) (l₂.nth_le i h₂) :=
⟨λ h, ⟨h.length_eq, h.nth_le⟩, and.rec forall₂_of_length_eq_of_nth_le⟩
theorem forall₂_zip {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁
| _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃
theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔
length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨λ h, ⟨h.length_eq, @forall₂_zip _ _ _ _ _ h⟩,
λ h, begin
cases h with h₁ h₂,
induction l₁ with a l₁ IH generalizing l₂,
{ cases length_eq_zero.1 h₁.symm, constructor },
{ cases l₂ with b l₂; injection h₁ with h₁,
exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) }
end⟩
theorem forall₂_take {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂)
| 0 _ _ _ := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂)
| 0 _ _ h := by simp only [drop, h]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ :=
have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)),
from forall₂_take (length l₁) h,
by rwa [take_left] at h'
theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ :=
have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)),
from forall₂_drop (length l₁) h,
by rwa [drop_left] at h'
lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈)
| a b h [] [] forall₂.nil := by simp only [not_mem_nil]
| a b h (a' :: as) (b' :: bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂)
lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map
| f g h [] [] forall₂.nil := forall₂.nil
| f g h (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂)
lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append
| [] [] h l₁ l₂ hl := hl
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl)
lemma rel_reverse : (forall₂ r ⇒ forall₂ r) reverse reverse
| [] [] forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := begin
simp only [reverse_cons],
exact rel_append (rel_reverse h₂) (forall₂.cons h₁ forall₂.nil)
end
@[simp]
lemma forall₂_reverse_iff {l₁ l₂} : forall₂ r (reverse l₁) (reverse l₂) ↔ forall₂ r l₁ l₂ :=
iff.intro
(λ h, by { rw [← reverse_reverse l₁, ← reverse_reverse l₂], exact rel_reverse h })
(λ h, rel_reverse h)
lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join
| [] [] forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂)
lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind :=
λ a b h₁ f g h₂, rel_join (rel_map @h₂ h₁)
lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs
lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs)
lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q]
(hpq : (r ⇒ (↔)) p q) :
(forall₂ r ⇒ forall₂ r) (filter p) (filter q)
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) :=
begin
by_cases p a,
{ have : q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂,
and_true], },
{ have : ¬ q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], },
end
lemma rel_filter_map : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map
| f g hfg _ _ forall₂.nil := forall₂.nil
| f g hfg (a :: as) (b :: bs) (forall₂.cons h₁ h₂) :=
by rw [filter_map_cons, filter_map_cons];
from match f a, g b, hfg h₁ with
| _, _, option.rel.none := rel_filter_map @hfg h₂
| _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂)
end
@[to_additive]
lemma rel_prod [monoid α] [monoid β]
(h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod :=
rel_foldl hf h
/-- Given a relation `r`, `sublist_forall₂ r l₁ l₂` indicates that there is a sublist of `l₂` such
that `forall₂ r l₁ l₂`. -/
inductive sublist_forall₂ (r : α → β → Prop) : list α → list β → Prop
| nil {l} : sublist_forall₂ [] l
| cons {a₁ a₂ l₁ l₂} : r a₁ a₂ → sublist_forall₂ l₁ l₂ →
sublist_forall₂ (a₁ :: l₁) (a₂ :: l₂)
| cons_right {a l₁ l₂} : sublist_forall₂ l₁ l₂ → sublist_forall₂ l₁ (a :: l₂)
lemma sublist_forall₂_iff {l₁ : list α} {l₂ : list β} :
sublist_forall₂ r l₁ l₂ ↔ ∃ l, forall₂ r l₁ l ∧ l <+ l₂ :=
begin
split; intro h,
{ induction h with _ a b l1 l2 rab rll ih b l1 l2 hl ih,
{ exact ⟨nil, forall₂.nil, nil_sublist _⟩ },
{ obtain ⟨l, hl1, hl2⟩ := ih,
refine ⟨b :: l, forall₂.cons rab hl1, hl2.cons_cons b⟩ },
{ obtain ⟨l, hl1, hl2⟩ := ih,
exact ⟨l, hl1, hl2.trans (sublist.cons _ _ _ (sublist.refl _))⟩ } },
{ obtain ⟨l, hl1, hl2⟩ := h,
revert l₁,
induction hl2 with _ _ _ _ ih _ _ _ _ ih; intros l₁ hl1,
{ rw [forall₂_nil_right_iff.1 hl1],
exact sublist_forall₂.nil },
{ exact sublist_forall₂.cons_right (ih hl1) },
{ cases hl1 with _ _ _ _ hr hl _,
exact sublist_forall₂.cons hr (ih hl) } }
end
variable {ra : α → α → Prop}
instance sublist_forall₂.is_refl [is_refl α ra] :
is_refl (list α) (sublist_forall₂ ra) :=
⟨λ l, sublist_forall₂_iff.2 ⟨l, forall₂_refl l, sublist.refl l⟩⟩
instance sublist_forall₂.is_trans [is_trans α ra] :
is_trans (list α) (sublist_forall₂ ra) :=
⟨λ a b c, begin
revert a b,
induction c with _ _ ih,
{ rintros _ _ h1 (_ | _ | _),
exact h1 },
{ rintros a b h1 h2,
cases h2 with _ _ _ _ _ hbc tbc _ _ y1 btc,
{ cases h1,
exact sublist_forall₂.nil },
{ cases h1 with _ _ _ _ _ hab tab _ _ _ atb,
{ exact sublist_forall₂.nil },
{ exact sublist_forall₂.cons (trans hab hbc) (ih _ _ tab tbc) },
{ exact sublist_forall₂.cons_right (ih _ _ atb tbc) } },
{ exact sublist_forall₂.cons_right (ih _ _ h1 btc), } }
end⟩
lemma sublist.sublist_forall₂ {l₁ l₂ : list α} (h : l₁ <+ l₂) (r : α → α → Prop) [is_refl α r] :
sublist_forall₂ r l₁ l₂ :=
sublist_forall₂_iff.2 ⟨l₁, forall₂_refl l₁, h⟩
lemma tail_sublist_forall₂_self [is_refl α ra] (l : list α) :
sublist_forall₂ ra l.tail l :=
l.tail_sublist.sublist_forall₂ ra
end list
|
34859986d3d514463b7ac5999719f31e8cdac437 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/996.hlean | 929b5f2b28a3ce0a5439312f76336314a6b00e7c | [
"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 | 266 | hlean | import types.pointed
open pointed
variable A : Type*
variable a : A
-- Type* is notation for the type of pointed types (types with a specified point in them)
definition ex (A : Type*) (v : Σ(x : A), x = x) : v = v :=
obtain (x : A) (p : _), from v,
rfl
print ex
|
3af0539fb305fa002f38dce4ec1442514728b64d | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/ofNatNormNum.lean | a8f726a3b821384eb41c645d17532da62ab18832 | [
"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 | 1,900 | lean | class OfNatSound (α : Type u) [Add α] [(n : Nat) → OfNat α n] : Prop where
ofNat_add (n m : Nat) : (OfNat.ofNat n : α) + OfNat.ofNat m = OfNat.ofNat (n+m)
export OfNatSound (ofNat_add)
theorem ex1 {α : Type u} [Add α] [(n : Nat) → OfNat α n] [OfNatSound α] : (10000000 : α) + 10000000 = 20000000 :=
ofNat_add ..
class Zero (α : Type u) where
zero : α
class One (α : Type u) where
one : α
instance [Zero α] : OfNat α (nat_lit 0) where
ofNat := Zero.zero
instance [One α] : OfNat α (nat_lit 1) where
ofNat := One.one
-- Some example structure
class S (α : Type u) extends Add α, Mul α, Zero α, One α where
add_assoc (a b c : α) : a + b + c = a + (b + c)
add_zero (a : α) : a + 0 = a
zero_add (a : α) : 0 + a = a
mul_zero (a : α) : a * 0 = 0
mul_one (a : α) : a * 1 = a
left_distrib (a b c : α) : a * (b + c) = a * b + a * c
-- Very simply default `ofNat` for `S`
protected def S.ofNat (α : Type u) [S α] : Nat → α
| 0 => 0
| n+1 => S.ofNat α n + 1
instance [S α] : OfNat α n where
ofNat := S.ofNat α n
instance [S α] : OfNatSound α where
ofNat_add n m := by
induction m with
| zero => simp [S.ofNat]; rw [Nat.add_zero]; erw [S.add_zero]; done
| succ m ih => simp [OfNat.ofNat, S.ofNat] at *; erw [← ih]; rw [S.add_assoc]
theorem S.ofNat_mul [S α] (n m : Nat) : (OfNat.ofNat n : α) * OfNat.ofNat m = OfNat.ofNat (n * m) := by
induction m with
| zero => rw [S.mul_zero, Nat.mul_zero]
| succ m ih =>
show OfNat.ofNat (α := α) n * OfNat.ofNat (m + 1) = OfNat.ofNat (n * m.succ)
rw [Nat.mul_succ, ← ofNat_add, ← ofNat_add, ← ih, left_distrib]
simp [OfNat.ofNat, S.ofNat]
erw [S.zero_add, S.mul_one]
theorem ex2 [S α] : (100000000000000000 : α) * 20000000000000000 = 2000000000000000000000000000000000 :=
S.ofNat_mul ..
#print ex2
|
47cc8d879fc7aa5b069d2b2f77d43afe5f878d12 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/number_theory/sum_two_squares.lean | 462ffe861141b0566687cd1fc873b319f283af59 | [
"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 | 824 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import number_theory.zsqrtd.gaussian_int
/-!
# Sums of two squares
Proof of Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum
of two squares
-/
open gaussian_int principal_ideal_ring
namespace nat
namespace prime
/-- **Fermat's theorem on the sum of two squares**. Every prime congruent to 1 mod 4 is the sum
of two squares. -/
lemma sq_add_sq (p : ℕ) [hp : _root_.fact p.prime] (hp1 : p % 4 = 1) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = p :=
begin
apply sq_add_sq_of_nat_prime_of_not_irreducible p,
rw [principal_ideal_ring.irreducible_iff_prime, prime_iff_mod_four_eq_three_of_nat_prime p, hp1],
norm_num
end
end prime
end nat
|
cde3cf9272e8af93b70a57c14dbcc4646fcabda0 | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/measure_theory/borel_space.lean | 44b625050b095deda77d4614fcdf2f0935b0233c | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,277 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import measure_theory.ae_measurable_sequence
import analysis.complex.basic
import analysis.normed_space.finite_dimension
import topology.G_delta
import measure_theory.arithmetic
import topology.semicontinuous
import topology.instances.ereal
/-!
# Borel (measurable) space
## Main definitions
* `borel α` : the least `σ`-algebra that contains all open sets;
* `class borel_space` : a space with `topological_space` and `measurable_space` structures
such that `‹measurable_space α› = borel α`;
* `class opens_measurable_space` : a space with `topological_space` and `measurable_space`
structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`.
* `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`;
* `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`.
## Main statements
* `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable;
* `continuous.measurable` : a continuous function is measurable;
* `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ`
is continuous, then `λ x, op (f x, g y)` is measurable;
* `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates,
and similarly for `dist` and `edist`;
* `ae_measurable.add` : similar dot notation for almost everywhere measurable functions;
* `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`.
-/
noncomputable theory
open classical set filter measure_theory
open_locale classical big_operators topological_space nnreal ennreal
universes u v w x y
variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α}
open measurable_space topological_space
/-- `measurable_space` structure generated by `topological_space`. -/
def borel (α : Type u) [topological_space α] : measurable_space α :=
generate_from {s : set α | is_open s}
lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] :
borel α = ⊤ :=
top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s)
lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] :
borel α = ⊤ :=
begin
refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _),
apply measurable_set.bUnion s.countable_encodable,
intros x hx,
apply measurable_set.of_compl,
apply generate_measurable.basic,
exact is_closed_singleton.is_open_compl
end
lemma borel_eq_generate_from_of_subbasis {s : set (set α)}
[t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) :
borel α = generate_from s :=
le_antisymm
(generate_from_le $ assume u (hu : t.is_open u),
begin
rw [hs] at hu,
induction hu,
case generate_open.basic : u hu
{ exact generate_measurable.basic u hu },
case generate_open.univ
{ exact @measurable_set.univ α (generate_from s) },
case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂
{ exact @measurable_set.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 @measurable_set.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 topological_space.is_topological_basis.borel_eq_generate_from [topological_space α]
[second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) :
borel α = generate_from s :=
borel_eq_generate_from_of_subbasis hs.eq_generate_from
lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) :=
λ s t hs ht hst, is_open.inter hs ht
lemma borel_eq_generate_from_is_closed [topological_space α] :
borel α = generate_from {s | is_closed s} :=
le_antisymm
(generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s})
(generate_measurable.basic _ $ is_closed_compl_iff.2 ht))
(generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α)
(generate_measurable.basic _ $ is_open_compl_iff.2 ht))
section order_topology
variable (α)
variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α]
lemma is_pi_system_Ioo_mem {α : Type*} [linear_order α] (s t : set α) :
is_pi_system {S | ∃ (l ∈ s) (u ∈ t), l < u ∧ Ioo l u = S} :=
begin
rintro _ _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩
⟨x, ⟨hlx₁ : l₁ < x, hxu₁ : x < u₁⟩, ⟨hlx₂ : l₂ < x, hxu₂ : x < u₂⟩⟩,
refine ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, _,
Ioo_inter_Ioo.symm⟩,
simp [hlx₂.trans hxu₁, hlx₁.trans hxu₂, *]
end
lemma is_pi_system_Ioo {α β : Type*} [linear_order β] (f : α → β) :
@is_pi_system β (⋃ l u (h : f l < f u), {Ioo (f l) (f u)}) :=
begin
convert is_pi_system_Ioo_mem (range f) (range f),
ext s,
simp [@eq_comm _ _ s]
end
lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) :=
begin
refine le_antisymm _ (generate_from_le _),
{ rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _),
letI : measurable_space α := measurable_space.generate_from (range Iio),
have H : ∀ a : α, measurable_set (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 measurable_set.Union,
exact λ _, (H _).compl } },
{ rw forall_range_iff,
intro a,
exact generate_measurable.basic _ is_open_Iio }
end
lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) :=
@borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _
end order_topology
lemma borel_comap {f : α → β} {t : topological_space β} :
@borel α (t.induced f) = (@borel β t).comap f :=
comap_generate_from.symm
lemma continuous.borel_measurable [topological_space α] [topological_space β]
{f : α → β} (hf : continuous f) :
@measurable α β (borel α) (borel β) f :=
measurable.of_le_map $ generate_from_le $
λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf)
/-- A space with `measurable_space` and `topological_space` structures such that
all open sets are measurable. -/
class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop :=
(borel_le : borel α ≤ h)
/-- A space with `measurable_space` and `topological_space` structures such that
the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/
class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop :=
(measurable_eq : ‹measurable_space α› = borel α)
/-- In a `borel_space` all open sets are measurable. -/
@[priority 100]
instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α]
[borel_space α] : opens_measurable_space α :=
⟨ge_of_eq $ borel_space.measurable_eq⟩
instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α]
[hα : borel_space α] (s : set α) :
borel_space s :=
⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩
instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α]
[h : opens_measurable_space α] (s : set α) :
opens_measurable_space s :=
⟨by { rw [borel_comap], exact comap_mono h.1 }⟩
section
variables [topological_space α] [measurable_space α] [opens_measurable_space α]
[topological_space β] [measurable_space β] [opens_measurable_space β]
[topological_space γ] [measurable_space γ] [borel_space γ]
[topological_space γ₂] [measurable_space γ₂] [borel_space γ₂]
[measurable_space δ]
lemma is_open.measurable_set (h : is_open s) : measurable_set s :=
opens_measurable_space.borel_le _ $ generate_measurable.basic _ h
@[measurability]
lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set
lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s :=
begin
rcases h with ⟨S, hSo, hSc, rfl⟩,
exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set)
end
lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) :
measurable_set {x | continuous_at f x} :=
(is_Gδ_set_of_continuous_at f).measurable_set
lemma is_closed.measurable_set (h : is_closed s) : measurable_set s :=
h.is_open_compl.measurable_set.of_compl
lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s :=
h.is_closed.measurable_set
@[measurability]
lemma measurable_set_closure : measurable_set (closure s) :=
is_closed_closure.measurable_set
lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) :
measurable f :=
by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf }
lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) :
measurable f :=
begin
apply measurable_of_is_open, intros s hs,
rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs
end
lemma measurable_of_is_closed' {f : δ → γ}
(hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f :=
begin
apply measurable_of_is_closed, intros s hs,
cases eq_empty_or_nonempty s with h1 h1, { simp [h1] },
by_cases h2 : s = univ, { simp [h2] },
exact hf s hs h1 h2
end
instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated :=
begin
rw [nhds, infi_subtype'],
refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _),
exact i.2.2.measurable_set.principal_is_measurably_generated
end
/-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for
each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`.
-/
lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s)
(a : α) :
(𝓝[s] a).is_measurably_generated :=
by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _
@[priority 100] -- see Note [lower instance priority]
instance opens_measurable_space.to_measurable_singleton_class [t1_space α] :
measurable_singleton_class α :=
⟨λ x, is_closed_singleton.measurable_set⟩
instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι]
[t' : Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)]
[∀ i, opens_measurable_space (π i)] :
opens_measurable_space (Π i, π i) :=
begin
constructor,
have : Pi.topological_space =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧
t = pi ↑i s},
{ rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] },
rw [borel_eq_generate_from_of_subbasis this],
apply generate_from_le,
rintros _ ⟨s, i, hi, rfl⟩,
refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _),
rw [eq_generate_from_countable_basis (π a)],
exact generate_open.basic _ (hi a ha)
end
instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] :
opens_measurable_space (α × β) :=
begin
constructor,
rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from],
apply generate_from_le,
rintros _ ⟨u, v, hu, hv, rfl⟩,
exact (is_open_of_mem_countable_basis hu).measurable_set.prod
(is_open_of_mem_countable_basis hv).measurable_set
end
variables {α' : Type*} [topological_space α'] [measurable_space α']
lemma meas_interior_of_null_bdry {μ : measure α'} {s : set α'}
(h_nullbdry : μ (frontier s) = 0) : μ (interior s) = μ s :=
meas_eq_meas_smaller_of_between_null_diff
interior_subset subset_closure h_nullbdry
lemma meas_closure_of_null_bdry {μ : measure α'} {s : set α'}
(h_nullbdry : μ (frontier s) = 0) : μ (closure s) = μ s :=
(meas_eq_meas_larger_of_between_null_diff
interior_subset subset_closure h_nullbdry).symm
section preorder
variables [preorder α] [order_closed_topology α] {a b : α}
@[simp, measurability]
lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set
@[simp, measurability]
lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set
@[simp, measurability]
lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set
instance nhds_within_Ici_is_measurably_generated :
(𝓝[Ici b] a).is_measurably_generated :=
measurable_set_Ici.nhds_within_is_measurably_generated _
instance nhds_within_Iic_is_measurably_generated :
(𝓝[Iic b] a).is_measurably_generated :=
measurable_set_Iic.nhds_within_is_measurably_generated _
instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated :=
@filter.infi_is_measurably_generated _ _ _ _ $
λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated
instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated :=
@filter.infi_is_measurably_generated _ _ _ _ $
λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated
end preorder
section partial_order
variables [partial_order α] [order_closed_topology α] [second_countable_topology α]
{a b : α}
@[measurability]
lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} :=
order_closed_topology.is_closed_le'.measurable_set
@[measurability]
lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable_set {a | f a ≤ g a} :=
hf.prod_mk hg measurable_set_le'
end partial_order
section linear_order
variables [linear_order α] [order_closed_topology α] {a b : α}
@[simp, measurability]
lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set
@[simp, measurability]
lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set
@[simp, measurability]
lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set
@[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) :=
measurable_set_Ioi.inter measurable_set_Iic
@[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) :=
measurable_set_Ici.inter measurable_set_Iio
instance nhds_within_Ioi_is_measurably_generated :
(𝓝[Ioi b] a).is_measurably_generated :=
measurable_set_Ioi.nhds_within_is_measurably_generated _
instance nhds_within_Iio_is_measurably_generated :
(𝓝[Iio b] a).is_measurably_generated :=
measurable_set_Iio.nhds_within_is_measurably_generated _
@[measurability]
lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} :=
(is_open_lt continuous_fst continuous_snd).measurable_set
@[measurability]
lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f)
(hg : measurable g) : measurable_set {a | f a < g a} :=
hf.prod_mk hg measurable_set_lt'
lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s :=
begin
let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y,
have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)),
have humeas : measurable_set u := huopen.measurable_set,
have hfinite : (s \ u).finite,
{ refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _),
by_contra h,
push_neg at h,
exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1,
mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) },
have : u ⊆ s :=
bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))),
rw ← union_diff_cancel this,
exact humeas.union hfinite.measurable_set
end
lemma is_preconnected.measurable_set
(h : is_preconnected s) : measurable_set s :=
h.ord_connected.measurable_set
end linear_order
section linear_order
variables [linear_order α] [order_closed_topology α]
@[measurability]
lemma measurable_set_interval {a b : α} : measurable_set (interval a b) :=
measurable_set_Icc
variables [second_countable_topology α]
@[measurability]
lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable (λ a, max (f a) (g a)) :=
hf.piecewise (measurable_set_le hg hf) hg
@[measurability]
lemma ae_measurable.max {f g : δ → α} {μ : measure δ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ :=
⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk,
eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩
@[measurability]
lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable (λ a, min (f a) (g a)) :=
hf.piecewise (measurable_set_le hf hg) hg
@[measurability]
lemma ae_measurable.min {f g : δ → α} {μ : measure δ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ :=
⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk,
eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩
end linear_order
/-- A continuous function from an `opens_measurable_space` to a `borel_space`
is measurable. -/
lemma continuous.measurable {f : α → γ} (hf : continuous f) :
measurable f :=
hf.borel_measurable.mono opens_measurable_space.borel_le
(le_of_eq $ borel_space.measurable_eq)
/-- A continuous function from an `opens_measurable_space` to a `borel_space`
is ae-measurable. -/
lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ :=
h.measurable.ae_measurable
lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) :
measurable f :=
hf.continuous.measurable
@[priority 100, to_additive]
instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] :
has_measurable_mul γ :=
{ measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable,
measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable }
@[priority 100]
instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] :
has_measurable_sub γ :=
{ measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable,
measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable }
@[priority 100, to_additive]
instance topological_group.has_measurable_inv [group γ] [topological_group γ] :
has_measurable_inv γ :=
⟨continuous_inv.measurable⟩
@[priority 100]
instance has_continuous_smul.has_measurable_smul {M α} [topological_space M]
[topological_space α] [measurable_space M] [measurable_space α]
[opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] :
has_measurable_smul M α :=
⟨λ c, (continuous_const.smul continuous_id).measurable,
λ y, (continuous_id.smul continuous_const).measurable⟩
section homeomorph
/-- A homeomorphism between two Borel spaces is a measurable equivalence.-/
def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ :=
{ measurable_to_fun := h.continuous_to_fun.measurable,
measurable_inv_fun := h.continuous_inv_fun.measurable,
.. h }
@[simp]
lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h :=
rfl
@[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) :
(h.to_measurable_equiv.symm : γ₂ → γ) = h.symm :=
rfl
@[measurability]
lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h :=
h.continuous.measurable
end homeomorph
lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α)
(hf : continuous_on f {a}ᶜ) :
measurable f :=
measurable_of_measurable_on_compl_singleton a
(continuous_on_iff_continuous_restrict.1 hf).measurable
lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β]
{f : δ → α} {g : δ → β} {c : α → β → γ}
(h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) :
measurable (λ a, c (f a) (g a)) :=
h.measurable.comp (hf.prod_mk hg)
lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β]
{f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ}
(h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ a, c (f a) (g a)) μ :=
h.measurable.comp_ae_measurable (hf.prod_mk hg)
@[priority 100]
instance has_continuous_inv'.has_measurable_inv [group_with_zero γ] [t1_space γ]
[has_continuous_inv' γ] :
has_measurable_inv γ :=
⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv'⟩
@[priority 100, to_additive]
instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ]
[has_continuous_mul γ] : has_measurable_mul₂ γ :=
⟨continuous_mul.measurable⟩
@[priority 100]
instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ]
[has_continuous_sub γ] : has_measurable_sub₂ γ :=
⟨continuous_sub.measurable⟩
@[priority 100]
instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M]
[second_countable_topology M] [measurable_space M] [opens_measurable_space M]
[topological_space α] [second_countable_topology α] [measurable_space α]
[borel_space α] [has_scalar M α] [has_continuous_smul M α] :
has_measurable_smul₂ M α :=
⟨continuous_smul.measurable⟩
end
section borel_space
variables [topological_space α] [measurable_space α] [borel_space α]
[topological_space β] [measurable_space β] [borel_space β]
[topological_space γ] [measurable_space γ] [borel_space γ]
[measurable_space δ]
lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, borel_space (π i)] :
measurable_space.pi ≤ borel (Π i, π i) :=
begin
have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) :=
funext (λ i, borel_space.measurable_eq),
rw [this],
exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable)
end
lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) :=
begin
rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq],
refine sup_le _ _,
{ exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable },
{ exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable }
end
instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι]
[t' : Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)]
[∀ i, borel_space (π i)] :
borel_space (Π i, π i) :=
⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩
instance prod.borel_space [second_countable_topology α] [second_countable_topology β] :
borel_space (α × β) :=
⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩
lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) :
measurable (function.inv_fun g) :=
begin
refine measurable_of_is_closed (λ s hs, _),
by_cases h : classical.choice n ∈ s,
{ rw preimage_inv_fun_of_mem hg.to_embedding.inj h,
exact (hg.closed_iff_image_closed.mp hs).measurable_set.union
hg.closed_range.measurable_set.compl },
{ rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h,
exact (hg.closed_iff_image_closed.mp hs).measurable_set }
end
lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) :
measurable (g ∘ f) ↔ measurable f :=
begin
refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩,
apply measurable_of_is_closed, intros s hs,
convert hf (hg.is_closed_map s hs).measurable_set,
rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj]
end
lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ}
(g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ :=
begin
by_cases h : nonempty β,
{ resetI,
refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩,
convert hg.measurable_inv_fun.comp_ae_measurable hf,
ext x,
exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm },
{ have H : ¬ nonempty δ, by { contrapose! h, exact nonempty.map f h },
simp [(measurable_of_not_nonempty H (g ∘ f)).ae_measurable,
(measurable_of_not_nonempty H f).ae_measurable] }
end
lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α}
{f : β → δ} (hg : closed_embedding g) :
ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) :=
begin
refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩,
by_cases hα : nonempty α,
swap, { simp [measure.eq_zero_of_not_nonempty hα μ] },
resetI,
refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩,
have : μ = measure.map (function.inv_fun g) (measure.map g μ),
by rw [measure.map_map hg.measurable_inv_fun hg.measurable,
(function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id],
rw this at h,
filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk,
ae_map_mem_range g hg.closed_range.measurable_set μ],
assume x hx₁ hx₂,
convert hx₁,
exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm,
end
section linear_order
variables [linear_order α] [order_topology α] [second_countable_topology α]
lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f :=
begin
convert measurable_generate_from _,
exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _),
rintro _ ⟨x, rfl⟩, exact hf x
end
lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ]
{f : δ → α} (hf : upper_semicontinuous f) : measurable f :=
measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set)
lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f :=
begin
convert measurable_generate_from _,
exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _),
rintro _ ⟨x, rfl⟩, exact hf x
end
lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ]
{f : δ → α} (hf : lower_semicontinuous f) : measurable f :=
measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set)
lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f :=
begin
apply measurable_of_Ioi,
simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff],
assumption
end
lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f :=
begin
apply measurable_of_Iio,
simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff],
assumption
end
lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg,
rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α],
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists],
exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set)
end
private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι)
{μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x),
let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some,
have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b),
{ intro b,
haveI hα : nonempty α := nonempty.map g ⟨b⟩,
simp only [ae_seq, g_seq],
split_ifs,
{ have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a},
{ ext x,
simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], },
rw h_set_eq,
exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, },
{ have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some},
{ ext1 x,
exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, },
rw h_singleton,
exact is_lub_singleton, }, },
refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩,
exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p)
(ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm,
end
lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure },
haveI : μ.ae.ne_bot := by simpa [ne_bot_iff],
by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, },
suffices : ∃ x, g =ᵐ[μ] λ y, g x,
by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, },
have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅,
{ intro x,
ext1 y,
rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false],
exact λ hi, hι (nonempty_of_exists hi), },
simp_rw h_empty at hg,
exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩,
end
lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg,
rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α],
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists],
exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set)
end
private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι)
{μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x),
let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some,
have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b),
{ intro b,
haveI hα : nonempty α := nonempty.map g ⟨b⟩,
simp only [ae_seq, g_seq],
split_ifs,
{ have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a},
{ ext x,
simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], },
rw h_set_eq,
exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, },
{ have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some},
{ ext1 x,
exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, },
rw h_singleton,
exact is_glb_singleton, }, },
refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩,
exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p)
(ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm,
end
lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure },
haveI : μ.ae.ne_bot := by simpa [ne_bot_iff],
by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, },
suffices : ∃ x, g =ᵐ[μ] λ y, g x,
by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, },
have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅,
{ intro x,
ext1 y,
rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false],
exact λ hi, hι (nonempty_of_exists hi), },
simp_rw h_empty at hg,
exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩,
end
lemma measurable_of_monotone [linear_order β] [order_closed_topology β] {f : β → α}
(hf : monotone f) : measurable f :=
suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x),
from measurable_of_Ioi (λ x, (h x).measurable_set),
λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1))
alias measurable_of_monotone ← monotone.measurable
lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β]
{μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α}
(hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f x ≤ f y) : ae_measurable f (μ.restrict s) :=
have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy,
ae_measurable_restrict_of_measurable_subtype hs this.measurable
lemma measurable_of_antimono [linear_order β] [order_closed_topology β] {f : β → α}
(hf : ∀ ⦃x y : β⦄, x ≤ y → f y ≤ f x) :
measurable f :=
@measurable_of_monotone (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf
lemma ae_measurable_restrict_of_antimono_on [linear_order β] [order_closed_topology β]
{μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α}
(hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f y ≤ f x) : ae_measurable f (μ.restrict s) :=
@ae_measurable_restrict_of_monotone_on (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf
end linear_order
@[measurability]
lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α]
(p : Prop) {f : δ → α} (hf : measurable f) :
measurable (λ b, ⨆ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact supr_pos h end)
(assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end)
@[measurability]
lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α]
(p : Prop) {f : δ → α} (hf : measurable f) :
measurable (λ b, ⨅ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact infi_pos h end )
(assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end)
section complete_linear_order
variables [complete_linear_order α] [order_topology α] [second_countable_topology α]
@[measurability]
lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨆ i, f i b) :=
measurable.is_lub hf $ λ b, is_lub_supr
@[measurability]
lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α}
(hf : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ b, ⨆ i, f i b) μ :=
ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr))
@[measurability]
lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨅ i, f i b) :=
measurable.is_glb hf $ λ b, is_glb_infi
@[measurability]
lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α}
(hf : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ b, ⨅ i, f i b) μ :=
ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi))
lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) :=
by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'],
exact measurable_supr (λ i, hf i) }
lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ :=
begin
haveI : encodable s := hs.to_encodable,
simp only [supr_subtype'],
exact ae_measurable_supr (λ i, hf i),
end
lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) :=
by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'],
exact measurable_infi (λ i, hf i) }
lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ :=
begin
haveI : encodable s := hs.to_encodable,
simp only [infi_subtype'],
exact ae_measurable_infi (λ i, hf i),
end
/-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`.
-/
lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i))
{p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable (λ x, liminf u (λ i, f i x)) :=
begin
simp_rw [hu.to_has_basis.liminf_eq_supr_infi],
refine measurable_bsupr _ hu.countable _,
exact λ i, measurable_binfi _ (hs i) hf
end
/-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`.
-/
lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i))
{p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable (λ x, limsup u (λ i, f i x)) :=
begin
simp_rw [hu.to_has_basis.limsup_eq_infi_supr],
refine measurable_binfi _ hu.countable _,
exact λ i, measurable_bsupr _ (hs i) hf
end
/-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter.
-/
@[measurability]
lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ x, liminf at_top (λ i, f i x)) :=
measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _)
/-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter.
-/
@[measurability]
lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ x, limsup at_top (λ i, f i x)) :=
measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _)
end complete_linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α]
lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable)
(hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) :
measurable (λ x, Sup ((λ i, f i x) '' s)) :=
begin
cases eq_empty_or_nonempty s with h2s h2s,
{ simp [h2s, measurable_const] },
{ apply measurable_of_Iic, intro y,
simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall],
exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) }
end
end conditionally_complete_linear_order
/-- Convert a `homeomorph` to a `measurable_equiv`. -/
def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β :=
{ to_equiv := h.to_equiv,
measurable_to_fun := h.continuous_to_fun.measurable,
measurable_inv_fun := h.continuous_inv_fun.measurable }
end borel_space
instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩
instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩
instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩
instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩
instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩
instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩
instance real.measurable_space : measurable_space ℝ := borel ℝ
instance real.borel_space : borel_space ℝ := ⟨rfl⟩
instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space
instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _
instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞
instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩
instance ereal.measurable_space : measurable_space ereal := borel ereal
instance ereal.borel_space : borel_space ereal := ⟨rfl⟩
instance complex.measurable_space : measurable_space ℂ := borel ℂ
instance complex.borel_space : borel_space ℂ := ⟨rfl⟩
section metric_space
variables [metric_space α] [measurable_space α] [opens_measurable_space α]
variables [measurable_space β] {x : α} {ε : ℝ}
open metric
@[measurability]
lemma measurable_set_ball : measurable_set (metric.ball x ε) :=
metric.is_open_ball.measurable_set
@[measurability]
lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) :=
metric.is_closed_ball.measurable_set
@[measurability]
lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) :=
(continuous_inf_dist_pt s).measurable
@[measurability]
lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_dist (f x) s) :=
measurable_inf_dist.comp hf
@[measurability]
lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) :=
(continuous_inf_nndist_pt s).measurable
@[measurability]
lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_nndist (f x) s) :=
measurable_inf_nndist.comp hf
variables [second_countable_topology α]
@[measurability]
lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) :=
continuous_dist.measurable
@[measurability]
lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, dist (f b) (g b)) :=
(@continuous_dist α _).measurable2 hf hg
@[measurability]
lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) :=
continuous_nndist.measurable
@[measurability]
lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, nndist (f b) (g b)) :=
(@continuous_nndist α _).measurable2 hf hg
end metric_space
section emetric_space
variables [emetric_space α] [measurable_space α] [opens_measurable_space α]
variables [measurable_space β] {x : α} {ε : ℝ≥0∞}
open emetric
@[measurability]
lemma measurable_set_eball : measurable_set (emetric.ball x ε) :=
emetric.is_open_ball.measurable_set
@[measurability]
lemma measurable_edist_right : measurable (edist x) :=
(continuous_const.edist continuous_id).measurable
@[measurability]
lemma measurable_edist_left : measurable (λ y, edist y x) :=
(continuous_id.edist continuous_const).measurable
@[measurability]
lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) :=
continuous_inf_edist.measurable
@[measurability]
lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_edist (f x) s) :=
measurable_inf_edist.comp hf
variables [second_countable_topology α]
@[measurability]
lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) :=
continuous_edist.measurable
@[measurability]
lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, edist (f b) (g b)) :=
(@continuous_edist α _).measurable2 hf hg
@[measurability]
lemma ae_measurable.edist {f g : β → α} {μ : measure β}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ :=
(@continuous_edist α _).ae_measurable2 hf hg
end emetric_space
namespace real
open measurable_space measure_theory
lemma borel_eq_generate_from_Ioo_rat :
borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_Ioo_rat.borel_eq_generate_from
lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) :=
by simpa [Union] using is_pi_system_Ioo (coe : ℚ → ℝ)
/-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals
with rational endpoints for a locally finite measure `μ` on `ℝ`. -/
def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [locally_finite_measure μ] :
μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) :=
{ set := λ n, Ioo (-(n + 1)) (n + 1),
set_mem := λ n,
begin
simp only [mem_Union, mem_singleton_iff],
refine ⟨-(n + 1), n + 1, _, by norm_cast⟩,
exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos
end,
finite := λ n,
calc μ (Ioo _ _) ≤ μ (Icc _ _) : μ.mono Ioo_subset_Icc_self
... < ∞ : is_compact_Icc.finite_measure,
spanning := Union_eq_univ_iff.2 $ λ x,
⟨nat_floor (abs x), neg_lt.1 ((neg_le_abs_self x).trans_lt (lt_nat_floor_add_one _)),
(le_abs_self x).trans_lt (lt_nat_floor_add_one _)⟩ }
lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [locally_finite_measure μ]
(h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν :=
(finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $
by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h }
lemma borel_eq_generate_from_Iio_rat :
borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) :=
begin
let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}),
apply le_antisymm _ (measurable_space.generate_from_le (λ t, _)),
{ rw borel_eq_generate_from_Ioo_rat,
refine generate_from_le (λ t, _),
simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩,
rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b),
{ have hg : ∀ q : ℚ, g.measurable_set' (Iio q) :=
λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }),
refine @measurable_set.inter _ g _ _ _ (hg _),
refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _),
exact @measurable_set.compl _ _ g (hg _) },
{ suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa,
refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩,
rcases exists_rat_btwn h with ⟨c, ac, cx⟩,
exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } },
{ simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio }
end
end real
variable [measurable_space α]
@[measurability]
lemma measurable_real_to_nnreal : measurable (real.to_nnreal) :=
nnreal.continuous_of_real.measurable
@[measurability]
lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.to_nnreal (f x)) :=
measurable_real_to_nnreal.comp hf
@[measurability]
lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, real.to_nnreal (f x)) μ :=
measurable_real_to_nnreal.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) :=
nnreal.continuous_coe.measurable
@[measurability]
lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) :
measurable (λ x, (f x : ℝ)) :=
measurable_coe_nnreal_real.comp hf
@[measurability]
lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ℝ)) μ :=
measurable_coe_nnreal_real.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) :=
ennreal.continuous_coe.measurable
@[measurability]
lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) :
measurable (λ x, (f x : ℝ≥0∞)) :=
ennreal.continuous_coe.measurable.comp hf
@[measurability]
lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ℝ≥0∞)) μ :=
ennreal.continuous_coe.measurable.comp_ae_measurable hf
@[measurability]
lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) :
measurable (λ x, ennreal.of_real (f x)) :=
ennreal.continuous_of_real.measurable.comp hf
/-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/
def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 :=
ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv
namespace ennreal
lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α}
(h : measurable (λ p : ℝ≥0, f p)) : measurable f :=
measurable_of_measurable_on_compl_singleton ∞
(measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h)
/-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/
def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit :=
{ measurable_to_fun := measurable_of_measurable_nnreal measurable_inl,
measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal
(@measurable_const ℝ≥0∞ unit _ _ ∞),
.. equiv.option_equiv_sum_punit ℝ≥0 }
open function (uncurry)
lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ]
{f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2)))
(H₂ : measurable (λ x, f (∞, x))) :
measurable f :=
let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β :=
(ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans
(measurable_equiv.sum_prod_distrib _ _ _) in
e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd)
lemma measurable_of_measurable_nnreal_nnreal [measurable_space β]
{f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2)))
(h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) :
measurable f :=
measurable_of_measurable_nnreal_prod
(measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃)
(measurable_of_measurable_nnreal h₂)
@[measurability]
lemma measurable_of_real : measurable ennreal.of_real :=
ennreal.continuous_of_real.measurable
@[measurability]
lemma measurable_to_real : measurable ennreal.to_real :=
ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real
@[measurability]
lemma measurable_to_nnreal : measurable ennreal.to_nnreal :=
ennreal.measurable_of_measurable_nnreal measurable_id
instance : has_measurable_mul₂ ℝ≥0∞ :=
begin
refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩,
{ simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] },
{ simp only [ennreal.top_mul, ennreal.coe_eq_zero],
exact measurable_const.piecewise (measurable_set_singleton _) measurable_const },
{ simp only [ennreal.mul_top, ennreal.coe_eq_zero],
exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }
end
instance : has_measurable_sub₂ ℝ≥0∞ :=
⟨by apply measurable_of_measurable_nnreal_nnreal;
simp [← ennreal.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩
instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩
end ennreal
@[measurability]
lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, (f x).to_nnreal) :=
ennreal.measurable_to_nnreal.comp hf
@[measurability]
lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x).to_nnreal) μ :=
ennreal.measurable_to_nnreal.comp_ae_measurable hf
lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} :
measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f :=
⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩
@[measurability]
lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, ennreal.to_real (f x)) :=
ennreal.measurable_to_real.comp hf
@[measurability]
lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, ennreal.to_real (f x)) μ :=
ennreal.measurable_to_real.comp_ae_measurable hf
/-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/
@[measurability]
lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) :
measurable (λ x, ∑' i, f i x) :=
by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr,
exact λ s, s.measurable_sum (λ i _, h i) }
@[measurability]
lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) :
measurable (λ x, ∑' i, f i x) :=
begin
simp_rw [nnreal.tsum_eq_to_nnreal_tsum],
exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal,
end
@[measurability]
lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α}
(h : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ x, ∑' i, f i x) μ :=
by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr,
exact λ s, finset.ae_measurable_sum s (λ i _, h i) }
@[measurability]
lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) :=
continuous_coe_real_ereal.measurable
@[measurability]
lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) :
measurable (λ x, (f x : ereal)) :=
measurable_coe_real_ereal.comp hf
@[measurability]
lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ereal)) μ :=
measurable_coe_real_ereal.comp_ae_measurable hf
/-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/
def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ :=
ereal.ne_bot_top_homeomorph_real.to_measurable_equiv
lemma ereal.measurable_of_measurable_real {f : ereal → α}
(h : measurable (λ p : ℝ, f p)) : measurable f :=
measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp)
(measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h)
@[measurability]
lemma measurable_ereal_to_real : measurable ereal.to_real :=
ereal.measurable_of_measurable_real (by simpa using measurable_id)
@[measurability]
lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) :
measurable (λ x, (f x).to_real) :=
measurable_ereal_to_real.comp hf
@[measurability]
lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x).to_real) μ :=
measurable_ereal_to_real.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) :=
continuous_coe_ennreal_ereal.measurable
@[measurability]
lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, (f x : ereal)) :=
measurable_coe_ennreal_ereal.comp hf
@[measurability]
lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ereal)) μ :=
measurable_coe_ennreal_ereal.comp_ae_measurable hf
section normed_group
variables [normed_group α] [opens_measurable_space α] [measurable_space β]
@[measurability]
lemma measurable_norm : measurable (norm : α → ℝ) :=
continuous_norm.measurable
@[measurability]
lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) :=
measurable_norm.comp hf
@[measurability]
lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, norm (f a)) μ :=
measurable_norm.comp_ae_measurable hf
@[measurability]
lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) :=
continuous_nnnorm.measurable
@[measurability]
lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) :=
measurable_nnnorm.comp hf
@[measurability]
lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, nnnorm (f a)) μ :=
measurable_nnnorm.comp_ae_measurable hf
@[measurability]
lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) :=
measurable_nnnorm.coe_nnreal_ennreal
@[measurability]
lemma measurable.ennnorm {f : β → α} (hf : measurable f) :
measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) :=
hf.nnnorm.coe_nnreal_ennreal
@[measurability]
lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ :=
measurable_ennnorm.comp_ae_measurable hf
end normed_group
section limits
variables [measurable_space β] [metric_space β] [borel_space β]
open metric
/-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable.
The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we
don't need that case yet. -/
lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι)
[ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop}
{s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g :=
begin
rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff],
have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) :=
λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq,
simp_rw [← this],
show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))),
exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs,
end
/-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/
lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0}
(hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g :=
measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _)
/-- A limit (over a general filter) of measurable functions valued in a metric space is measurable.
The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we
don't need that case yet. -/
lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β}
(u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop}
{s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable g :=
begin
apply measurable_of_is_closed', intros s h1s h2s h3s,
have : measurable (λ x, inf_nndist (g x) s),
{ refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap,
rw [tendsto_pi], rw [tendsto_pi] at lim, intro x,
exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) },
have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0},
{ ext x, simp [h1s, ← mem_iff_inf_dist_zero_of_closed h1s h2s, ← nnreal.coe_eq_zero] },
rw [h4s], exact this (measurable_set_singleton 0),
end
/-- A sequential limit of measurable functions valued in a metric space is measurable. -/
lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β}
(hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) :
measurable g :=
measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _)
lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β}
(hf : ∀ n, ae_measurable (f n) μ)
(h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) :
ae_measurable g μ :=
begin
let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)),
let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto,
let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some,
refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some)
(ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩,
refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _,
refine tendsto_pi.mpr (λ x, _),
simp_rw [ae_seq, ae_seq_lim],
split_ifs with hx,
{ simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx,
exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, },
{ exact tendsto_const_nhds, },
end
lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β}
(hf : ∀ n, measurable (f n))
(h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) :
measurable g :=
ae_measurable_iff_measurable.mp
(ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto)
lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β}
(hf : ∀ n, ae_measurable (f n) μ)
(h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) :
∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim),
∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) :=
begin
let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l),
have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x),
from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx,
have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0,
from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto,
let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some)
(λ h, (⟨f 0 x⟩ : nonempty β).some),
have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)),
{ intros x hx_conv,
simp only [f_lim, hx_conv, dif_pos],
exact (hp_mem x hx_conv).some_spec, },
have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)),
{ intros x,
simp only [f_lim, ae_seq],
split_ifs,
{ rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n),
exact (hp_mem x h).some_spec, },
{ exact tendsto_const_nhds, }, },
have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)),
{ refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _),
exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), },
have h_f_lim_meas : measurable f_lim,
from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)),
exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩,
end
end limits
namespace continuous_linear_map
variables {𝕜 : Type*} [normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E]
variables [opens_measurable_space E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F]
@[measurability]
protected lemma measurable (L : E →L[𝕜] F) : measurable L :=
L.continuous.measurable
lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) :
measurable (λ (a : α), L (φ a)) :=
L.measurable.comp φ_meas
end continuous_linear_map
namespace continuous_linear_map
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
instance : measurable_space (E →L[𝕜] F) := borel _
instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩
@[measurability]
lemma measurable_apply [measurable_space F] [borel_space F] (x : E) :
measurable (λ f : E →L[𝕜] F, f x) :=
(apply 𝕜 F x).continuous.measurable
@[measurability]
lemma measurable_apply' [measurable_space E] [opens_measurable_space E]
[measurable_space F] [borel_space F] :
measurable (λ (x : E) (f : E →L[𝕜] F), f x) :=
measurable_pi_lambda _ $ λ f, f.measurable
@[measurability]
lemma measurable_coe [measurable_space F] [borel_space F] :
measurable (λ (f : E →L[𝕜] F) (x : E), f x) :=
measurable_pi_lambda _ measurable_apply
end continuous_linear_map
section continuous_linear_map_nondiscrete_normed_field
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
@[measurability]
lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) :
measurable (λ a, φ a v) :=
(continuous_linear_map.apply 𝕜 E v).measurable.comp hφ
@[measurability]
lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α}
(hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ :=
(continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ
end continuous_linear_map_nondiscrete_normed_field
section normed_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜]
variables [borel_space 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E]
lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) :
measurable (λ x, f x • c) ↔ measurable f :=
measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc)
lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) :
ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ :=
ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc)
end normed_space
lemma is_compact.measure_lt_top_of_nhds_within [topological_space α]
{s : set α} {μ : measure α} (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) :
μ s < ∞ :=
is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht)
(λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ
lemma is_compact.measure_lt_top [topological_space α] {s : set α} {μ : measure α}
[locally_finite_measure μ] (h : is_compact s) :
μ s < ∞ :=
h.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _
|
0ab0178e5cfbc0a7e20267beb116876fcb2e09cd | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/analysis/filter.lean | edff2cd7db0d59c5787c471178e7a35d679a3e3f | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 12,580 | 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 order.filter.cofinite
/-!
# Computational realization of filters (experimental)
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides infrastructure to compute with filters.
## Main declarations
* `cfilter`: Realization of a filter base. Note that this is in the generality of filters on
lattices, while `filter` is filters of sets (so corresponding to `cfilter (set α) σ`).
* `filter.realizer`: Realization of a `filter`. `cfilter` that generates the given filter.
-/
open set filter
/-- A `cfilter α σ` is a realization of a filter (base) on `α`,
represented by a type `σ` together with operations for the top element and
the binary inf operation. -/
structure cfilter (α σ : Type*) [partial_order α] :=
(f : σ → α)
(pt : σ)
(inf : σ → σ → σ)
(inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a)
(inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b)
variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*}
instance [inhabited α] [semilattice_inf α] : inhabited (cfilter α α) :=
⟨{ f := id,
pt := default,
inf := (⊓),
inf_le_left := λ _ _, inf_le_left,
inf_le_right := λ _ _, inf_le_right }⟩
namespace cfilter
section
variables [partial_order α] (F : cfilter α σ)
instance : has_coe_to_fun (cfilter α σ) (λ _, σ → α) := ⟨cfilter.f⟩
@[simp] theorem coe_mk (f pt inf h₁ h₂ a) : (@cfilter.mk α σ _ f pt inf h₁ h₂) a = f a := rfl
/-- Map a cfilter to an equivalent representation type. -/
def of_equiv (E : σ ≃ τ) : cfilter α σ → cfilter α τ
| ⟨f, p, g, h₁, h₂⟩ :=
{ f := λ a, f (E.symm a),
pt := E p,
inf := λ a b, E (g (E.symm a) (E.symm b)),
inf_le_left := λ a b, by simpa using h₁ (E.symm a) (E.symm b),
inf_le_right := λ a b, by simpa using h₂ (E.symm a) (E.symm b) }
@[simp] theorem of_equiv_val (E : σ ≃ τ) (F : cfilter α σ) (a : τ) :
F.of_equiv E a = F (E.symm a) := by cases F; refl
end
/-- The filter represented by a `cfilter` is the collection of supersets of
elements of the filter base. -/
def to_filter (F : cfilter (set α) σ) : filter α :=
{ sets := {a | ∃ b, F b ⊆ a},
univ_sets := ⟨F.pt, subset_univ _⟩,
sets_of_superset := λ x y ⟨b, h⟩ s, ⟨b, subset.trans h s⟩,
inter_sets := λ x y ⟨a, h₁⟩ ⟨b, h₂⟩, ⟨F.inf a b,
subset_inter (subset.trans (F.inf_le_left _ _) h₁) (subset.trans (F.inf_le_right _ _) h₂)⟩ }
@[simp] theorem mem_to_filter_sets (F : cfilter (set α) σ) {a : set α} :
a ∈ F.to_filter ↔ ∃ b, F b ⊆ a := iff.rfl
end cfilter
/-- A realizer for filter `f` is a cfilter which generates `f`. -/
structure filter.realizer (f : filter α) :=
(σ : Type*)
(F : cfilter (set α) σ)
(eq : F.to_filter = f)
/-- A `cfilter` realizes the filter it generates. -/
protected def cfilter.to_realizer (F : cfilter (set α) σ) : F.to_filter.realizer := ⟨σ, F, rfl⟩
namespace filter.realizer
theorem mem_sets {f : filter α} (F : f.realizer) {a : set α} : a ∈ f ↔ ∃ b, F.F b ⊆ a :=
by cases F; subst f; simp
/-- Transfer a realizer along an equality of filter. This has better definitional equalities than
the `eq.rec` proof. -/
def of_eq {f g : filter α} (e : f = g) (F : f.realizer) : g.realizer :=
⟨F.σ, F.F, F.eq.trans e⟩
/-- A filter realizes itself. -/
def of_filter (f : filter α) : f.realizer := ⟨f.sets,
{ f := subtype.val,
pt := ⟨univ, univ_mem⟩,
inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, inter_mem h₁ h₂⟩,
inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_left x y,
inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_right x y },
filter_eq $ set.ext $ λ x, set_coe.exists.trans exists_mem_subset_iff⟩
/-- Transfer a filter realizer to another realizer on a different base type. -/
def of_equiv {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : f.realizer :=
⟨τ, F.F.of_equiv E, by refine eq.trans _ F.eq; exact filter_eq (set.ext $ λ x,
⟨λ ⟨s, h⟩, ⟨E.symm s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E t, by simp [h]⟩⟩)⟩
@[simp] theorem of_equiv_σ {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) :
(F.of_equiv E).σ = τ := rfl
@[simp] theorem of_equiv_F {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) (s : τ) :
(F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp
/-- `unit` is a realizer for the principal filter -/
protected def principal (s : set α) : (principal s).realizer := ⟨unit,
{ f := λ _, s,
pt := (),
inf := λ _ _, (),
inf_le_left := λ _ _, le_rfl,
inf_le_right := λ _ _, le_rfl },
filter_eq $ set.ext $ λ x,
⟨λ ⟨_, s⟩, s, λ h, ⟨(), h⟩⟩⟩
@[simp] theorem principal_σ (s : set α) : (realizer.principal s).σ = unit := rfl
@[simp] theorem principal_F (s : set α) (u : unit) : (realizer.principal s).F u = s := rfl
instance (s : set α) : inhabited (principal s).realizer := ⟨realizer.principal s⟩
/-- `unit` is a realizer for the top filter -/
protected def top : (⊤ : filter α).realizer :=
(realizer.principal _).of_eq principal_univ
@[simp] theorem top_σ : (@realizer.top α).σ = unit := rfl
@[simp] theorem top_F (u : unit) : (@realizer.top α).F u = univ := rfl
/-- `unit` is a realizer for the bottom filter -/
protected def bot : (⊥ : filter α).realizer :=
(realizer.principal _).of_eq principal_empty
@[simp] theorem bot_σ : (@realizer.bot α).σ = unit := rfl
@[simp] theorem bot_F (u : unit) : (@realizer.bot α).F u = ∅ := rfl
/-- Construct a realizer for `map m f` given a realizer for `f` -/
protected def map (m : α → β) {f : filter α} (F : f.realizer) : (map m f).realizer := ⟨F.σ,
{ f := λ s, image m (F.F s),
pt := F.F.pt,
inf := F.F.inf,
inf_le_left := λ a b, image_subset _ (F.F.inf_le_left _ _),
inf_le_right := λ a b, image_subset _ (F.F.inf_le_right _ _) },
filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; rw F.mem_sets; refl ⟩
@[simp] theorem map_σ (m : α → β) {f : filter α} (F : f.realizer) : (F.map m).σ = F.σ := rfl
@[simp] theorem map_F (m : α → β) {f : filter α} (F : f.realizer) (s) :
(F.map m).F s = image m (F.F s) := rfl
/-- Construct a realizer for `comap m f` given a realizer for `f` -/
protected def comap (m : α → β) {f : filter β} (F : f.realizer) : (comap m f).realizer := ⟨F.σ,
{ f := λ s, preimage m (F.F s),
pt := F.F.pt,
inf := F.F.inf,
inf_le_left := λ a b, preimage_mono (F.F.inf_le_left _ _),
inf_le_right := λ a b, preimage_mono (F.F.inf_le_right _ _) },
filter_eq $ set.ext $ λ x, by cases F; subst f; simp [cfilter.to_filter, mem_comap]; exact
⟨λ ⟨s, h⟩, ⟨_, ⟨s, subset.refl _⟩, h⟩,
λ ⟨y, ⟨s, h⟩, h₂⟩, ⟨s, subset.trans (preimage_mono h) h₂⟩⟩⟩
/-- Construct a realizer for the sup of two filters -/
protected def sup {f g : filter α} (F : f.realizer) (G : g.realizer) :
(f ⊔ g).realizer := ⟨F.σ × G.σ,
{ f := λ ⟨s, t⟩, F.F s ∪ G.F t,
pt := (F.F.pt, G.F.pt),
inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'),
inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _),
inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_right _ _)
(G.F.inf_le_right _ _) },
filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact
⟨λ ⟨s, t, h⟩, ⟨⟨s, subset.trans (subset_union_left _ _) h⟩,
⟨t, subset.trans (subset_union_right _ _) h⟩⟩,
λ ⟨⟨s, h₁⟩, ⟨t, h₂⟩⟩, ⟨s, t, union_subset h₁ h₂⟩⟩⟩
/-- Construct a realizer for the inf of two filters -/
protected def inf {f g : filter α} (F : f.realizer) (G : g.realizer) :
(f ⊓ g).realizer := ⟨F.σ × G.σ,
{ f := λ ⟨s, t⟩, F.F s ∩ G.F t,
pt := (F.F.pt, G.F.pt),
inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'),
inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _),
inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_right _ _)
(G.F.inf_le_right _ _) },
begin
ext x,
cases F; cases G; substs f g; simp [cfilter.to_filter],
split,
{ rintro ⟨s : F_σ, t : G_σ, h⟩,
apply mem_inf_of_inter _ _ h,
use s,
use t, },
{ rintros ⟨s, ⟨a, ha⟩, t, ⟨b, hb⟩, rfl⟩,
exact ⟨a, b, inter_subset_inter ha hb⟩ }
end⟩
/-- Construct a realizer for the cofinite filter -/
protected def cofinite [decidable_eq α] : (@cofinite α).realizer := ⟨finset α,
{ f := λ s, {a | a ∉ s},
pt := ∅,
inf := (∪),
inf_le_left := λ s t a, mt (finset.mem_union_left _),
inf_le_right := λ s t a, mt (finset.mem_union_right _) },
filter_eq $ set.ext $ λ x,
⟨λ ⟨s, h⟩, s.finite_to_set.subset (compl_subset_comm.1 h),
λ h, ⟨h.to_finset, by simp⟩⟩⟩
/-- Construct a realizer for filter bind -/
protected def bind {f : filter α} {m : α → filter β} (F : f.realizer) (G : ∀ i, (m i).realizer) :
(f.bind m).realizer :=
⟨Σ s : F.σ, Π i ∈ F.F s, (G i).σ,
{ f := λ ⟨s, f⟩, ⋃ i ∈ F.F s, (G i).F (f i H),
pt := ⟨F.F.pt, λ i H, (G i).F.pt⟩,
inf := λ ⟨a, f⟩ ⟨b, f'⟩, ⟨F.F.inf a b, λ i h,
(G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩,
inf_le_left := λ ⟨a, f⟩ ⟨b, f'⟩ x,
show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) →
x ∈ ⋃ i (H : i ∈ F.F a), ((G i).F) (f i H), by simp; exact
λ i h₁ h₂, ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩,
inf_le_right := λ ⟨a, f⟩ ⟨b, f'⟩ x,
show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) →
x ∈ ⋃ i (H : i ∈ F.F b), ((G i).F) (f' i H), by simp; exact
λ i h₁ h₂, ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ },
filter_eq $ set.ext $ λ x,
by cases F with _ F _; subst f; simp [cfilter.to_filter, mem_bind]; exact
⟨λ ⟨s, f, h⟩, ⟨F s, ⟨s, subset.refl _⟩, λ i H, (G i).mem_sets.2
⟨f i H, λ a h', h ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, h'⟩⟩⟩,
λ ⟨y, ⟨s, h⟩, f⟩,
let ⟨f', h'⟩ := classical.axiom_of_choice (λ i:F s, (G i).mem_sets.1 (f i (h i.2))) in
⟨s, λ i h, f' ⟨i, h⟩, λ a ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, m⟩, h' ⟨_, H⟩ m⟩⟩⟩
/-- Construct a realizer for indexed supremum -/
protected def Sup {f : α → filter β} (F : ∀ i, (f i).realizer) : (⨆ i, f i).realizer :=
let F' : (⨆ i, f i).realizer :=
((realizer.bind realizer.top F).of_eq $
filter_eq $ set.ext $ by simp [filter.bind, eq_univ_iff_forall, supr_sets_eq]) in
F'.of_equiv $ show (Σ u:unit, Π (i : α), true → (F i).σ) ≃ Π i, (F i).σ, from
⟨λ⟨_,f⟩ i, f i ⟨⟩, λ f, ⟨(), λ i _, f i⟩,
λ ⟨⟨⟩, f⟩, by dsimp; congr; simp, λ f, rfl⟩
/-- Construct a realizer for the product of filters -/
protected def prod {f g : filter α} (F : f.realizer) (G : g.realizer) : (f.prod g).realizer :=
(F.comap _).inf (G.comap _)
theorem le_iff {f g : filter α} (F : f.realizer) (G : g.realizer) :
f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b :=
⟨λ H t, F.mem_sets.1 (H (G.mem_sets.2 ⟨t, subset.refl _⟩)),
λ H x h, F.mem_sets.2 $
let ⟨s, h₁⟩ := G.mem_sets.1 h, ⟨t, h₂⟩ := H s in ⟨t, subset.trans h₂ h₁⟩⟩
theorem tendsto_iff (f : α → β) {l₁ : filter α} {l₂ : filter β} (L₁ : l₁.realizer)
(L₂ : l₂.realizer) :
tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b :=
(le_iff (L₁.map f) L₂).trans $ forall_congr $ λ b, exists_congr $ λ a, image_subset_iff
theorem ne_bot_iff {f : filter α} (F : f.realizer) :
f ≠ ⊥ ↔ ∀ a : F.σ, (F.F a).nonempty :=
begin
classical,
rw [not_iff_comm, ← le_bot_iff, F.le_iff realizer.bot, not_forall],
simp only [set.not_nonempty_iff_eq_empty],
exact ⟨λ ⟨x, e⟩ _, ⟨x, le_of_eq e⟩,
λ h, let ⟨x, h⟩ := h () in ⟨x, le_bot_iff.1 h⟩⟩
end
end filter.realizer
|
1345545bd8cd0cb8a727f7783ed4c7e0ba02f0e7 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/interactive/keywordCompletion.lean | 6ecd8449aaffc397b8a8fb3485bd38f45ed866a5 | [
"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 | 175 | lean | def regular := 0
macro "register_string " s:str : term => s
#check register_
--^ textDocument/completion
#check register_
--^ textDocument/completion
|
0818113784460c25125afb33ea636ee41ed72c7d | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/dual.lean | 5ec63c6bb7c54a7142f20d7ad6ad442e288626a4 | [
"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 | 26,741 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Fabian Glöckle
-/
import linear_algebra.finite_dimensional
import linear_algebra.projection
import linear_algebra.sesquilinear_form
import ring_theory.finiteness
import linear_algebra.free_module.finite.rank
/-!
# Dual vector spaces
The dual space of an R-module M is the R-module of linear maps `M → R`.
## Main definitions
* `dual R M` defines the dual space of M over R.
* Given a basis for an `R`-module `M`, `basis.to_dual` produces a map from `M` to `dual R M`.
* Given families of vectors `e` and `ε`, `dual_pair e ε` states that these families have the
characteristic properties of a basis and a dual.
* `dual_annihilator W` is the submodule of `dual R M` where every element annihilates `W`.
## Main results
* `to_dual_equiv` : the linear equivalence between the dual module and primal module,
given a finite basis.
* `dual_pair.basis` and `dual_pair.eq_dual`: if `e` and `ε` form a dual pair, `e` is a basis and
`ε` is its dual basis.
* `quot_equiv_annihilator`: the quotient by a subspace is isomorphic to its dual annihilator.
## Notation
We sometimes use `V'` as local notation for `dual K V`.
## TODO
Erdös-Kaplansky theorem about the dimension of a dual vector space in case of infinite dimension.
-/
noncomputable theory
namespace module
variables (R : Type*) (M : Type*)
variables [comm_semiring R] [add_comm_monoid M] [module R M]
/-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/
@[derive [add_comm_monoid, module R]] def dual := M →ₗ[R] R
instance {S : Type*} [comm_ring S] {N : Type*} [add_comm_group N] [module S N] :
add_comm_group (dual S N) := linear_map.add_comm_group
instance : add_monoid_hom_class (dual R M) M R :=
linear_map.add_monoid_hom_class
/-- The canonical pairing of a vector space and its algebraic dual. -/
def dual_pairing (R M) [comm_semiring R] [add_comm_monoid M] [module R M] :
module.dual R M →ₗ[R] M →ₗ[R] R := linear_map.id
@[simp] lemma dual_pairing_apply (v x) : dual_pairing R M v x = v x := rfl
namespace dual
instance : inhabited (dual R M) := linear_map.inhabited
instance : has_coe_to_fun (dual R M) (λ _, M → R) := ⟨linear_map.to_fun⟩
/-- Maps a module M to the dual of the dual of M. See `module.erange_coe` and
`module.eval_equiv`. -/
def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.flip linear_map.id
@[simp] lemma eval_apply (v : M) (a : dual R M) : eval R M v a = a v :=
begin
dunfold eval,
rw [linear_map.flip_apply, linear_map.id_apply]
end
variables {R M} {M' : Type*} [add_comm_monoid M'] [module R M']
/-- The transposition of linear maps, as a linear map from `M →ₗ[R] M'` to
`dual R M' →ₗ[R] dual R M`. -/
def transpose : (M →ₗ[R] M') →ₗ[R] (dual R M' →ₗ[R] dual R M) :=
(linear_map.llcomp R M M' R).flip
lemma transpose_apply (u : M →ₗ[R] M') (l : dual R M') : transpose u l = l.comp u := rfl
variables {M'' : Type*} [add_comm_monoid M''] [module R M'']
lemma transpose_comp (u : M' →ₗ[R] M'') (v : M →ₗ[R] M') :
transpose (u.comp v) = (transpose v).comp (transpose u) := rfl
end dual
end module
namespace basis
universes u v w
open module module.dual submodule linear_map cardinal function
open_locale big_operators
variables {R M K V ι : Type*}
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι]
variables (b : basis ι R M)
/-- The linear map from a vector space equipped with basis to its dual vector space,
taking basis elements to corresponding dual basis elements. -/
def to_dual : M →ₗ[R] module.dual R M :=
b.constr ℕ $ λ v, b.constr ℕ $ λ w, if w = v then (1 : R) else 0
lemma to_dual_apply (i j : ι) :
b.to_dual (b i) (b j) = if i = j then 1 else 0 :=
by { erw [constr_basis b, constr_basis b], ac_refl }
@[simp] lemma to_dual_total_left (f : ι →₀ R) (i : ι) :
b.to_dual (finsupp.total ι M R b f) (b i) = f i :=
begin
rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum, linear_map.sum_apply],
simp_rw [linear_map.map_smul, linear_map.smul_apply, to_dual_apply, smul_eq_mul,
mul_boole, finset.sum_ite_eq'],
split_ifs with h,
{ refl },
{ rw finsupp.not_mem_support_iff.mp h }
end
@[simp] lemma to_dual_total_right (f : ι →₀ R) (i : ι) :
b.to_dual (b i) (finsupp.total ι M R b f) = f i :=
begin
rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum],
simp_rw [linear_map.map_smul, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq],
split_ifs with h,
{ refl },
{ rw finsupp.not_mem_support_iff.mp h }
end
lemma to_dual_apply_left (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i :=
by rw [← b.to_dual_total_left, b.total_repr]
lemma to_dual_apply_right (i : ι) (m : M) : b.to_dual (b i) m = b.repr m i :=
by rw [← b.to_dual_total_right, b.total_repr]
lemma coe_to_dual_self (i : ι) : b.to_dual (b i) = b.coord i :=
by { ext, apply to_dual_apply_right }
/-- `h.to_dual_flip v` is the linear map sending `w` to `h.to_dual w v`. -/
def to_dual_flip (m : M) : (M →ₗ[R] R) := b.to_dual.flip m
lemma to_dual_flip_apply (m₁ m₂ : M) : b.to_dual_flip m₁ m₂ = b.to_dual m₂ m₁ := rfl
lemma to_dual_eq_repr (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i :=
b.to_dual_apply_left m i
lemma to_dual_eq_equiv_fun [fintype ι] (m : M) (i : ι) : b.to_dual m (b i) = b.equiv_fun m i :=
by rw [b.equiv_fun_apply, to_dual_eq_repr]
lemma to_dual_inj (m : M) (a : b.to_dual m = 0) : m = 0 :=
begin
rw [← mem_bot R, ← b.repr.ker, mem_ker, linear_equiv.coe_coe],
apply finsupp.ext,
intro b,
rw [← to_dual_eq_repr, a],
refl
end
theorem to_dual_ker : b.to_dual.ker = ⊥ :=
ker_eq_bot'.mpr b.to_dual_inj
theorem to_dual_range [fin : fintype ι] : b.to_dual.range = ⊤ :=
begin
rw eq_top_iff',
intro f,
rw linear_map.mem_range,
let lin_comb : ι →₀ R := finsupp.on_finset fin.elems (λ i, f.to_fun (b i)) _,
{ use finsupp.total ι M R b lin_comb,
apply b.ext,
{ intros i,
rw [b.to_dual_eq_repr _ i, repr_total b],
{ refl } } },
{ intros a _,
apply fin.complete }
end
end comm_semiring
section
variables [comm_semiring R] [add_comm_monoid M] [module R M] [fintype ι]
variables (b : basis ι R M)
@[simp] lemma sum_dual_apply_smul_coord (f : module.dual R M) : ∑ x, f (b x) • b.coord x = f :=
begin
ext m,
simp_rw [linear_map.sum_apply, linear_map.smul_apply, smul_eq_mul, mul_comm (f _), ←smul_eq_mul,
←f.map_smul, ←f.map_sum, basis.coord_apply, basis.sum_repr],
end
end
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι]
variables (b : basis ι R M)
/-- A vector space is linearly equivalent to its dual space. -/
@[simps]
def to_dual_equiv [fintype ι] : M ≃ₗ[R] (dual R M) :=
linear_equiv.of_bijective b.to_dual
(ker_eq_bot.mp b.to_dual_ker) (range_eq_top.mp b.to_dual_range)
/-- Maps a basis for `V` to a basis for the dual space. -/
def dual_basis [fintype ι] : basis ι R (dual R M) :=
b.map b.to_dual_equiv
-- We use `j = i` to match `basis.repr_self`
lemma dual_basis_apply_self [fintype ι] (i j : ι) :
b.dual_basis i (b j) = if j = i then 1 else 0 :=
by { convert b.to_dual_apply i j using 2, rw @eq_comm _ j i }
lemma total_dual_basis [fintype ι] (f : ι →₀ R) (i : ι) :
finsupp.total ι (dual R M) R b.dual_basis f (b i) = f i :=
begin
rw [finsupp.total_apply, finsupp.sum_fintype, linear_map.sum_apply],
{ simp_rw [linear_map.smul_apply, smul_eq_mul, dual_basis_apply_self, mul_boole,
finset.sum_ite_eq, if_pos (finset.mem_univ i)] },
{ intro, rw zero_smul },
end
lemma dual_basis_repr [fintype ι] (l : dual R M) (i : ι) :
b.dual_basis.repr l i = l (b i) :=
by rw [← total_dual_basis b, basis.total_repr b.dual_basis l]
lemma dual_basis_equiv_fun [fintype ι] (l : dual R M) (i : ι) :
b.dual_basis.equiv_fun l i = l (b i) :=
by rw [basis.equiv_fun_apply, dual_basis_repr]
lemma dual_basis_apply [fintype ι] (i : ι) (m : M) : b.dual_basis i m = b.repr m i :=
b.to_dual_apply_right i m
@[simp] lemma coe_dual_basis [fintype ι] :
⇑b.dual_basis = b.coord :=
by { ext i x, apply dual_basis_apply }
@[simp] lemma to_dual_to_dual [fintype ι] :
b.dual_basis.to_dual.comp b.to_dual = dual.eval R M :=
begin
refine b.ext (λ i, b.dual_basis.ext (λ j, _)),
rw [linear_map.comp_apply, to_dual_apply_left, coe_to_dual_self, ← coe_dual_basis,
dual.eval_apply, basis.repr_self, finsupp.single_apply, dual_basis_apply_self]
end
theorem eval_ker {ι : Type*} (b : basis ι R M) :
(dual.eval R M).ker = ⊥ :=
begin
rw ker_eq_bot',
intros m hm,
simp_rw [linear_map.ext_iff, dual.eval_apply, zero_apply] at hm,
exact (basis.forall_coord_eq_zero_iff _).mp (λ i, hm (b.coord i))
end
lemma eval_range {ι : Type*} [fintype ι] (b : basis ι R M) :
(eval R M).range = ⊤ :=
begin
classical,
rw [← b.to_dual_to_dual, range_comp, b.to_dual_range, map_top, to_dual_range _],
apply_instance
end
/-- A module with a basis is linearly equivalent to the dual of its dual space. -/
def eval_equiv {ι : Type*} [fintype ι] (b : basis ι R M) : M ≃ₗ[R] dual R (dual R M) :=
linear_equiv.of_bijective (eval R M)
(ker_eq_bot.mp b.eval_ker) (range_eq_top.mp b.eval_range)
@[simp] lemma eval_equiv_to_linear_map {ι : Type*} [fintype ι] (b : basis ι R M) :
(b.eval_equiv).to_linear_map = dual.eval R M := rfl
section
open_locale classical
variables [finite R M] [free R M] [nontrivial R]
instance dual_free : free R (dual R M) := free.of_basis (free.choose_basis R M).dual_basis
instance dual_finite : finite R (dual R M) := finite.of_basis (free.choose_basis R M).dual_basis
end
end comm_ring
/-- `simp` normal form version of `total_dual_basis` -/
@[simp] lemma total_coord [comm_ring R] [add_comm_group M] [module R M] [fintype ι]
(b : basis ι R M) (f : ι →₀ R) (i : ι) :
finsupp.total ι (dual R M) R b.coord f (b i) = f i :=
by { haveI := classical.dec_eq ι, rw [← coe_dual_basis, total_dual_basis] }
-- TODO(jmc): generalize to rings, once `module.rank` is generalized
theorem dual_dim_eq [field K] [add_comm_group V] [module K V] [fintype ι] (b : basis ι K V) :
cardinal.lift (module.rank K V) = module.rank K (dual K V) :=
begin
classical,
have := linear_equiv.lift_dim_eq b.to_dual_equiv,
simp only [cardinal.lift_umax] at this,
rw [this, ← cardinal.lift_umax],
apply cardinal.lift_id,
end
end basis
namespace module
variables {K V : Type*}
variables [field K] [add_comm_group V] [module K V]
open module module.dual submodule linear_map cardinal basis finite_dimensional
theorem eval_ker : (eval K V).ker = ⊥ :=
by { classical, exact (basis.of_vector_space K V).eval_ker }
-- TODO(jmc): generalize to rings, once `module.rank` is generalized
theorem dual_dim_eq [finite_dimensional K V] :
cardinal.lift (module.rank K V) = module.rank K (dual K V) :=
(basis.of_vector_space K V).dual_dim_eq
lemma erange_coe [finite_dimensional K V] : (eval K V).range = ⊤ :=
begin
letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance,
exact (basis.of_vector_space K V).eval_range
end
variables (K V)
/-- A vector space is linearly equivalent to the dual of its dual space. -/
def eval_equiv [finite_dimensional K V] : V ≃ₗ[K] dual K (dual K V) :=
linear_equiv.of_bijective (eval K V)
(ker_eq_bot.mp eval_ker) (range_eq_top.mp erange_coe)
variables {K V}
@[simp] lemma eval_equiv_to_linear_map [finite_dimensional K V] :
(eval_equiv K V).to_linear_map = dual.eval K V := rfl
end module
section dual_pair
open module
variables {R M ι : Type*}
variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι]
/-- `e` and `ε` have characteristic properties of a basis and its dual -/
@[nolint has_inhabited_instance]
structure dual_pair (e : ι → M) (ε : ι → (dual R M)) :=
(eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0)
(total : ∀ {m : M}, (∀ i, ε i m = 0) → m = 0)
[finite : ∀ m : M, fintype {i | ε i m ≠ 0}]
end dual_pair
namespace dual_pair
open module module.dual linear_map function
variables {R M ι : Type*}
variables [comm_ring R] [add_comm_group M] [module R M]
variables {e : ι → M} {ε : ι → dual R M}
/-- The coefficients of `v` on the basis `e` -/
def coeffs [decidable_eq ι] (h : dual_pair e ε) (m : M) : ι →₀ R :=
{ to_fun := λ i, ε i m,
support := by { haveI := h.finite m, exact {i : ι | ε i m ≠ 0}.to_finset },
mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } }
@[simp] lemma coeffs_apply [decidable_eq ι] (h : dual_pair e ε) (m : M) (i : ι) :
h.coeffs m i = ε i m := rfl
/-- linear combinations of elements of `e`.
This is a convenient abbreviation for `finsupp.total _ M R e l` -/
def lc {ι} (e : ι → M) (l : ι →₀ R) : M := l.sum (λ (i : ι) (a : R), a • (e i))
lemma lc_def (e : ι → M) (l : ι →₀ R) : lc e l = finsupp.total _ _ _ e l := rfl
variables [decidable_eq ι] (h : dual_pair e ε)
include h
lemma dual_lc (l : ι →₀ R) (i : ι) : ε i (dual_pair.lc e l) = l i :=
begin
erw linear_map.map_sum,
simp only [h.eval, map_smul, smul_eq_mul],
rw finset.sum_eq_single i,
{ simp },
{ intros q q_in q_ne,
simp [q_ne.symm] },
{ intro p_not_in,
simp [finsupp.not_mem_support_iff.1 p_not_in] },
end
@[simp]
lemma coeffs_lc (l : ι →₀ R) : h.coeffs (dual_pair.lc e l) = l :=
by { ext i, rw [h.coeffs_apply, h.dual_lc] }
/-- For any m : M n, \sum_{p ∈ Q n} (ε p m) • e p = m -/
@[simp]
lemma lc_coeffs (m : M) : dual_pair.lc e (h.coeffs m) = m :=
begin
refine eq_of_sub_eq_zero (h.total _),
intros i,
simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero]
end
/-- `(h : dual_pair e ε).basis` shows the family of vectors `e` forms a basis. -/
@[simps]
def basis : basis ι R M :=
basis.of_repr
{ to_fun := coeffs h,
inv_fun := lc e,
left_inv := lc_coeffs h,
right_inv := coeffs_lc h,
map_add' := λ v w, by { ext i, exact (ε i).map_add v w },
map_smul' := λ c v, by { ext i, exact (ε i).map_smul c v } }
@[simp] lemma coe_basis : ⇑h.basis = e :=
by { ext i, rw basis.apply_eq_iff, ext j,
rw [h.basis_repr_apply, coeffs_apply, h.eval, finsupp.single_apply],
convert if_congr eq_comm rfl rfl } -- `convert` to get rid of a `decidable_eq` mismatch
lemma mem_of_mem_span {H : set ι} {x : M} (hmem : x ∈ submodule.span R (e '' H)) :
∀ i : ι, ε i x ≠ 0 → i ∈ H :=
begin
intros i hi,
rcases (finsupp.mem_span_image_iff_total _).mp hmem with ⟨l, supp_l, rfl⟩,
apply not_imp_comm.mp ((finsupp.mem_supported' _ _).mp supp_l i),
rwa [← lc_def, h.dual_lc] at hi
end
lemma coe_dual_basis [fintype ι] : ⇑h.basis.dual_basis = ε :=
funext (λ i, h.basis.ext (λ j, by rw [h.basis.dual_basis_apply_self, h.coe_basis, h.eval,
if_congr eq_comm rfl rfl]))
end dual_pair
namespace submodule
universes u v w
variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M]
variable {W : submodule R M}
/-- The `dual_restrict` of a submodule `W` of `M` is the linear map from the
dual of `M` to the dual of `W` such that the domain of each linear map is
restricted to `W`. -/
def dual_restrict (W : submodule R M) :
module.dual R M →ₗ[R] module.dual R W :=
linear_map.dom_restrict' W
@[simp] lemma dual_restrict_apply
(W : submodule R M) (φ : module.dual R M) (x : W) :
W.dual_restrict φ x = φ (x : M) := rfl
/-- The `dual_annihilator` of a submodule `W` is the set of linear maps `φ` such
that `φ w = 0` for all `w ∈ W`. -/
def dual_annihilator {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M]
[module R M] (W : submodule R M) : submodule R $ module.dual R M :=
W.dual_restrict.ker
@[simp] lemma mem_dual_annihilator (φ : module.dual R M) :
φ ∈ W.dual_annihilator ↔ ∀ w ∈ W, φ w = 0 :=
begin
refine linear_map.mem_ker.trans _,
simp_rw [linear_map.ext_iff, dual_restrict_apply],
exact ⟨λ h w hw, h ⟨w, hw⟩, λ h w, h w.1 w.2⟩
end
lemma dual_restrict_ker_eq_dual_annihilator (W : submodule R M) :
W.dual_restrict.ker = W.dual_annihilator :=
rfl
lemma dual_annihilator_sup_eq_inf_dual_annihilator (U V : submodule R M) :
(U ⊔ V).dual_annihilator = U.dual_annihilator ⊓ V.dual_annihilator :=
begin
ext φ,
rw [mem_inf, mem_dual_annihilator, mem_dual_annihilator, mem_dual_annihilator],
split; intro h,
{ refine ⟨_, _⟩;
intros x hx,
exact h x (mem_sup.2 ⟨x, hx, 0, zero_mem _, add_zero _⟩),
exact h x (mem_sup.2 ⟨0, zero_mem _, x, hx, zero_add _⟩) },
{ simp_rw mem_sup,
rintro _ ⟨x, hx, y, hy, rfl⟩,
rw [linear_map.map_add, h.1 _ hx, h.2 _ hy, add_zero] }
end
/-- The pullback of a submodule in the dual space along the evaluation map. -/
def dual_annihilator_comap (Φ : submodule R (module.dual R M)) : submodule R M :=
Φ.dual_annihilator.comap (module.dual.eval R M)
lemma mem_dual_annihilator_comap_iff {Φ : submodule R (module.dual R M)} (x : M) :
x ∈ Φ.dual_annihilator_comap ↔ ∀ φ ∈ Φ, (φ x : R) = 0 :=
by simp_rw [dual_annihilator_comap, mem_comap, mem_dual_annihilator, module.dual.eval_apply]
end submodule
namespace subspace
open submodule linear_map
universes u v w
-- We work in vector spaces because `exists_is_compl` only hold for vector spaces
variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [module K V]
/-- Given a subspace `W` of `V` and an element of its dual `φ`, `dual_lift W φ` is
the natural extension of `φ` to an element of the dual of `V`.
That is, `dual_lift W φ` sends `w ∈ W` to `φ x` and `x` in the complement of `W` to `0`. -/
noncomputable def dual_lift (W : subspace K V) :
module.dual K W →ₗ[K] module.dual K V :=
let h := classical.indefinite_description _ W.exists_is_compl in
(linear_map.of_is_compl_prod h.2).comp (linear_map.inl _ _ _)
variable {W : subspace K V}
@[simp] lemma dual_lift_of_subtype {φ : module.dual K W} (w : W) :
W.dual_lift φ (w : V) = φ w :=
by { erw of_is_compl_left_apply _ w, refl }
lemma dual_lift_of_mem {φ : module.dual K W} {w : V} (hw : w ∈ W) :
W.dual_lift φ w = φ ⟨w, hw⟩ :=
dual_lift_of_subtype ⟨w, hw⟩
@[simp] lemma dual_restrict_comp_dual_lift (W : subspace K V) :
W.dual_restrict.comp W.dual_lift = 1 :=
by { ext φ x, simp }
lemma dual_restrict_left_inverse (W : subspace K V) :
function.left_inverse W.dual_restrict W.dual_lift :=
λ x, show W.dual_restrict.comp W.dual_lift x = x,
by { rw [dual_restrict_comp_dual_lift], refl }
lemma dual_lift_right_inverse (W : subspace K V) :
function.right_inverse W.dual_lift W.dual_restrict :=
W.dual_restrict_left_inverse
lemma dual_restrict_surjective :
function.surjective W.dual_restrict :=
W.dual_lift_right_inverse.surjective
lemma dual_lift_injective : function.injective W.dual_lift :=
W.dual_restrict_left_inverse.injective
/-- The quotient by the `dual_annihilator` of a subspace is isomorphic to the
dual of that subspace. -/
noncomputable def quot_annihilator_equiv (W : subspace K V) :
(module.dual K V ⧸ W.dual_annihilator) ≃ₗ[K] module.dual K W :=
(quot_equiv_of_eq _ _ W.dual_restrict_ker_eq_dual_annihilator).symm.trans $
W.dual_restrict.quot_ker_equiv_of_surjective dual_restrict_surjective
/-- The natural isomorphism forom the dual of a subspace `W` to `W.dual_lift.range`. -/
noncomputable def dual_equiv_dual (W : subspace K V) :
module.dual K W ≃ₗ[K] W.dual_lift.range :=
linear_equiv.of_injective _ dual_lift_injective
lemma dual_equiv_dual_def (W : subspace K V) :
W.dual_equiv_dual.to_linear_map = W.dual_lift.range_restrict := rfl
@[simp] lemma dual_equiv_dual_apply (φ : module.dual K W) :
W.dual_equiv_dual φ = ⟨W.dual_lift φ, mem_range.2 ⟨φ, rfl⟩⟩ := rfl
section
open_locale classical
open finite_dimensional
variables {V₁ : Type*} [add_comm_group V₁] [module K V₁]
instance [H : finite_dimensional K V] : finite_dimensional K (module.dual K V) :=
by apply_instance
variables [finite_dimensional K V] [finite_dimensional K V₁]
@[simp] lemma dual_finrank_eq :
finrank K (module.dual K V) = finrank K V :=
linear_equiv.finrank_eq (basis.of_vector_space K V).to_dual_equiv.symm
/-- The quotient by the dual is isomorphic to its dual annihilator. -/
noncomputable def quot_dual_equiv_annihilator (W : subspace K V) :
(module.dual K V ⧸ W.dual_lift.range) ≃ₗ[K] W.dual_annihilator :=
linear_equiv.quot_equiv_of_quot_equiv $
linear_equiv.trans W.quot_annihilator_equiv W.dual_equiv_dual
/-- The quotient by a subspace is isomorphic to its dual annihilator. -/
noncomputable def quot_equiv_annihilator (W : subspace K V) :
(V ⧸ W) ≃ₗ[K] W.dual_annihilator :=
begin
refine _ ≪≫ₗ W.quot_dual_equiv_annihilator,
refine linear_equiv.quot_equiv_of_equiv _ (basis.of_vector_space K V).to_dual_equiv,
exact (basis.of_vector_space K W).to_dual_equiv.trans W.dual_equiv_dual
end
open finite_dimensional
@[simp]
lemma finrank_dual_annihilator_comap_eq {Φ : subspace K (module.dual K V)} :
finrank K Φ.dual_annihilator_comap = finrank K Φ.dual_annihilator :=
begin
rw [submodule.dual_annihilator_comap, ← module.eval_equiv_to_linear_map],
exact linear_equiv.finrank_eq (linear_equiv.of_submodule' _ _),
end
lemma finrank_add_finrank_dual_annihilator_comap_eq
(W : subspace K (module.dual K V)) :
finrank K W + finrank K W.dual_annihilator_comap = finrank K V :=
begin
rw [finrank_dual_annihilator_comap_eq, W.quot_equiv_annihilator.finrank_eq.symm, add_comm,
submodule.finrank_quotient_add_finrank, subspace.dual_finrank_eq],
end
end
end subspace
variables {R : Type*} [comm_ring R] {M₁ : Type*} {M₂ : Type*}
variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂]
open module
/-- Given a linear map `f : M₁ →ₗ[R] M₂`, `f.dual_map` is the linear map between the dual of
`M₂` and `M₁` such that it maps the functional `φ` to `φ ∘ f`. -/
def linear_map.dual_map (f : M₁ →ₗ[R] M₂) : dual R M₂ →ₗ[R] dual R M₁ :=
linear_map.lcomp R R f
@[simp] lemma linear_map.dual_map_apply (f : M₁ →ₗ[R] M₂) (g : dual R M₂) (x : M₁) :
f.dual_map g x = g (f x) :=
linear_map.lcomp_apply f g x
@[simp] lemma linear_map.dual_map_id :
(linear_map.id : M₁ →ₗ[R] M₁).dual_map = linear_map.id :=
by { ext, refl }
lemma linear_map.dual_map_comp_dual_map {M₃ : Type*} [add_comm_group M₃] [module R M₃]
(f : M₁ →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) :
f.dual_map.comp g.dual_map = (g.comp f).dual_map :=
rfl
/-- The `linear_equiv` version of `linear_map.dual_map`. -/
def linear_equiv.dual_map (f : M₁ ≃ₗ[R] M₂) : dual R M₂ ≃ₗ[R] dual R M₁ :=
{ inv_fun := f.symm.to_linear_map.dual_map,
left_inv :=
begin
intro φ, ext x,
simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map,
linear_map.to_fun_eq_coe, linear_equiv.apply_symm_apply]
end,
right_inv :=
begin
intro φ, ext x,
simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map,
linear_map.to_fun_eq_coe, linear_equiv.symm_apply_apply]
end,
.. f.to_linear_map.dual_map }
@[simp] lemma linear_equiv.dual_map_apply (f : M₁ ≃ₗ[R] M₂) (g : dual R M₂) (x : M₁) :
f.dual_map g x = g (f x) :=
linear_map.lcomp_apply f g x
@[simp] lemma linear_equiv.dual_map_refl :
(linear_equiv.refl R M₁).dual_map = linear_equiv.refl R (dual R M₁) :=
by { ext, refl }
@[simp] lemma linear_equiv.dual_map_symm {f : M₁ ≃ₗ[R] M₂} :
(linear_equiv.dual_map f).symm = linear_equiv.dual_map f.symm := rfl
lemma linear_equiv.dual_map_trans {M₃ : Type*} [add_comm_group M₃] [module R M₃]
(f : M₁ ≃ₗ[R] M₂) (g : M₂ ≃ₗ[R] M₃) :
g.dual_map.trans f.dual_map = (f.trans g).dual_map :=
rfl
namespace linear_map
variable (f : M₁ →ₗ[R] M₂)
lemma ker_dual_map_eq_dual_annihilator_range :
f.dual_map.ker = f.range.dual_annihilator :=
begin
ext φ, split; intro hφ,
{ rw mem_ker at hφ,
rw submodule.mem_dual_annihilator,
rintro y ⟨x, rfl⟩,
rw [← dual_map_apply, hφ, zero_apply] },
{ ext x,
rw dual_map_apply,
rw submodule.mem_dual_annihilator at hφ,
exact hφ (f x) ⟨x, rfl⟩ }
end
lemma range_dual_map_le_dual_annihilator_ker :
f.dual_map.range ≤ f.ker.dual_annihilator :=
begin
rintro _ ⟨ψ, rfl⟩,
simp_rw [submodule.mem_dual_annihilator, mem_ker],
rintro x hx,
rw [dual_map_apply, hx, map_zero]
end
section finite_dimensional
variables {K : Type*} [field K] {V₁ : Type*} {V₂ : Type*}
variables [add_comm_group V₁] [module K V₁] [add_comm_group V₂] [module K V₂]
open finite_dimensional
variable [finite_dimensional K V₂]
@[simp] lemma finrank_range_dual_map_eq_finrank_range (f : V₁ →ₗ[K] V₂) :
finrank K f.dual_map.range = finrank K f.range :=
begin
have := submodule.finrank_quotient_add_finrank f.range,
rw [(subspace.quot_equiv_annihilator f.range).finrank_eq,
← ker_dual_map_eq_dual_annihilator_range] at this,
conv_rhs at this { rw ← subspace.dual_finrank_eq },
refine add_left_injective (finrank K f.dual_map.ker) _,
change _ + _ = _ + _,
rw [finrank_range_add_finrank_ker f.dual_map, add_comm, this],
end
lemma range_dual_map_eq_dual_annihilator_ker [finite_dimensional K V₁] (f : V₁ →ₗ[K] V₂) :
f.dual_map.range = f.ker.dual_annihilator :=
begin
refine eq_of_le_of_finrank_eq f.range_dual_map_le_dual_annihilator_ker _,
have := submodule.finrank_quotient_add_finrank f.ker,
rw (subspace.quot_equiv_annihilator f.ker).finrank_eq at this,
refine add_left_injective (finrank K f.ker) _,
simp_rw [this, finrank_range_dual_map_eq_finrank_range],
exact finrank_range_add_finrank_ker f,
end
end finite_dimensional
section field
variables {K V : Type*}
variables [field K] [add_comm_group V] [module K V]
lemma dual_pairing_nondegenerate : (dual_pairing K V).nondegenerate :=
begin
refine ⟨separating_left_iff_ker_eq_bot.mpr ker_id, _⟩,
intros x,
contrapose,
rintros hx : x ≠ 0,
rw [not_forall],
let f : V →ₗ[K] K := classical.some (linear_pmap.mk_span_singleton x 1 hx).to_fun.exists_extend,
use [f],
refine ne_zero_of_eq_one _,
have h : f.comp (K ∙ x).subtype = (linear_pmap.mk_span_singleton x 1 hx).to_fun :=
classical.some_spec (linear_pmap.mk_span_singleton x (1 : K) hx).to_fun.exists_extend,
exact (fun_like.congr_fun h _).trans (linear_pmap.mk_span_singleton_apply _ hx _),
end
end field
end linear_map
|
fb923e30cd31610eae9fb0fb36cddbbdd895936b | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world7/level10.lean | f89bf2d16fa65ab470f9c6b0065f9e414e629dda | [
"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 | 3,180 | lean | import game.world7.level9 -- hide
import tactic.tauto
local attribute [instance, priority 10] classical.prop_decidable -- we are mathematicians
/-
# Advanced proposition world.
## Level 10: the law of the excluded middle.
We proved earlier that `(P → Q) → (¬ Q → ¬ P)`. The converse,
that `(¬ Q → ¬ P) → (P → Q)` is certainly true, but trying to prove
it using what we've learnt so far is impossible (because it is not provable in
constructive logic). For example, after
```
intro h,
intro p,
repeat {rw not_iff_imp_false at h},
```
in the below, you are left with
```
P Q : Prop,
h : (Q → false) → P → false
p : P
⊢ Q
```
The tools you have are not sufficient to continue. But you can just
prove this, and any other basic lemmas of this form like `¬ ¬ P → P`,
using the `by_cases` tactic. Instead of starting with all the `intro`s,
try this instead:
`by_cases p : P; by_cases q : Q,`
**Note the semicolon**! It means "do the next tactic to all the goals, not just the top one".
After it, there are four goals, one for each of the four possibilities PQ=TT, TF, FT, FF.
You can see that `p` is a proof of `P` in some of the goals, and a proof of `¬ P` in others.
Similar comments apply to `q`.
`repeat {cc}` then finishes the job.
This approach assumed that `P ∨ ¬ P` was true; the `by_cases` tactic just does `cases` on
this result. This is called the law of the excluded middle, and it cannot be proved just
using tactics such as `intro` and `apply`.
-/
/- Lemma : no-side-bar
If $P$ and $Q$ are true/false statements, then
$$(\lnot Q\implies \lnot P)\implies(P\implies Q).$$
-/
lemma contrapositive2 (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) :=
begin
by_cases p : P; by_cases q : Q,
repeat {cc},
end
/-
OK that's enough logic -- now perhaps it's time to go on to Advanced Addition World!
Get to it via the main menu.
-/
/-
## Pro tip
In fact the tactic `tauto!` just kills this goal (and many other logic goals) immediately.
-/
/- Tactic : by_cases
## Summary
`by_cases h : P` does a cases split on whether `P` is true or false.
## Details
Some logic goals cannot be proved with `intro` and `apply` and `exact`.
The simplest example is the law of the excluded middle `¬ ¬ P → P`.
You can prove this using truth tables but not with `intro`, `apply` etc.
To do a truth table proof, the tactic `by_cases h : P` will turn a goal of
`⊢ ¬ ¬ P → P` into two goals
```
P : Prop,
h : P
⊢ ¬¬P → P
P : Prop,
h : ¬P
⊢ ¬¬P → P
```
Each of these can now be proved using `intro`, `apply`, `exact` and `exfalso`.
Remember though that in these simple logic cases, high-powered logic
tactics like `cc` and `tauto!` will just prove everything.
-/
/- Tactic : tauto
## Summary
The `tauto` tactic (and its variant `tauto!`) will close various logic
goals.
## Details
`tauto` is an all-purpose logic tactic which will try to solve goals using pure
logical reasoning -- for example it will close the following goal:
```
P Q : Prop,
hP : P,
hQ : Q
⊢ P ∧ Q
```
`tauto` is supposed to only use constructive logic, but its big brother `tauto!` uses classical logic
and hence closes more goals.
-/
|
34c7a55f08ebcdd5530d0a1935cbfed42c50f07e | 32317185abf7e7c963f4c67c190aec61af6b3628 | /library/data/nat/power.lean | 7b093734b8e9a751fe6cda654e28e513f09fceb2 | [
"Apache-2.0"
] | permissive | Andrew-Zipperer-unorganized/lean | 198a2317f21198cd8d26e7085e484b86277f17f7 | dcb35008e1474a0abebe632b1dced120e5f8c009 | refs/heads/master | 1,622,526,520,945 | 1,453,576,559,000 | 1,454,612,842,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,653 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
The power function on the natural numbers.
-/
import data.nat.basic data.nat.order data.nat.div data.nat.gcd algebra.ring_power
namespace nat
definition nat_has_pow_nat [instance] [reducible] [priority nat.prio] : has_pow_nat nat :=
has_pow_nat.mk has_pow_nat.pow_nat
theorem pow_le_pow_of_le {x y : ℕ} (i : ℕ) (H : x ≤ y) : x^i ≤ y^i :=
pow_le_pow_of_le i !zero_le H
theorem eq_zero_of_pow_eq_zero {a m : ℕ} (H : a^m = 0) : a = 0 :=
or.elim (eq_zero_or_pos m)
(suppose m = 0,
by rewrite [`m = 0` at H, pow_zero at H]; contradiction)
(suppose m > 0,
have h₁ : ∀ m, a^succ m = 0 → a = 0,
begin
intro m,
induction m with m ih,
{rewrite pow_one; intros; assumption},
rewrite pow_succ,
intro H,
cases eq_zero_or_eq_zero_of_mul_eq_zero H with h₃ h₄,
assumption,
exact ih h₄
end,
obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos `m > 0`,
show a = 0, by rewrite h₂ at H; apply h₁ m' H)
-- generalize to semirings?
theorem le_pow_self {x : ℕ} (H : x > 1) : ∀ i, i ≤ x^i
| 0 := !zero_le
| (succ j) := have x > 0, from lt.trans zero_lt_one H,
have h₁ : x^j ≥ 1, from succ_le_of_lt (pow_pos_of_pos _ this),
have x ≥ 2, from succ_le_of_lt H,
calc
succ j = j + 1 : rfl
... ≤ x^j + 1 : add_le_add_right (le_pow_self j)
... ≤ x^j + x^j : add_le_add_left h₁
... = x^j * (1 + 1) : by rewrite [left_distrib, *mul_one]
... = x^j * 2 : rfl
... ≤ x^j * x : mul_le_mul_left _ `x ≥ 2`
... = x^(succ j) : pow_succ'
-- TODO: eventually this will be subsumed under the algebraic theorems
theorem mul_self_eq_pow_2 (a : nat) : a * a = a ^ 2 :=
show a * a = a ^ (succ (succ zero)), from
by rewrite [*pow_succ, *pow_zero, mul_one]
theorem pow_cancel_left : ∀ {a b c : nat}, a > 1 → a ^ b = a ^ c → b = c
| a 0 0 h₁ h₂ := rfl
| a (succ b) 0 h₁ h₂ :=
assert a = 1, by rewrite [pow_succ at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right h₂),
assert (1:nat) < 1, by rewrite [this at h₁]; exact h₁,
absurd `1 <[nat] 1` !lt.irrefl
| a 0 (succ c) h₁ h₂ :=
assert a = 1, by rewrite [pow_succ at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right (eq.symm h₂)),
assert (1:nat) < 1, by rewrite [this at h₁]; exact h₁,
absurd `1 <[nat] 1` !lt.irrefl
| a (succ b) (succ c) h₁ h₂ :=
assert a ≠ 0, from assume aeq0, by rewrite [aeq0 at h₁]; exact (absurd h₁ dec_trivial),
assert a^b = a^c, by rewrite [*pow_succ at h₂]; exact (eq_of_mul_eq_mul_left (pos_of_ne_zero this) h₂),
by rewrite [pow_cancel_left h₁ this]
theorem pow_div_cancel : ∀ {a b : nat}, a ≠ 0 → (a ^ succ b) / a = a ^ b
| a 0 h := by rewrite [pow_succ, pow_zero, mul_one, nat.div_self (pos_of_ne_zero h)]
| a (succ b) h := by rewrite [pow_succ, nat.mul_div_cancel_left _ (pos_of_ne_zero h)]
lemma dvd_pow : ∀ (i : nat) {n : nat}, n > 0 → i ∣ i^n
| i 0 h := absurd h !lt.irrefl
| i (succ n) h := by rewrite [pow_succ']; apply dvd_mul_left
lemma dvd_pow_of_dvd_of_pos : ∀ {i j n : nat}, i ∣ j → n > 0 → i ∣ j^n
| i j 0 h₁ h₂ := absurd h₂ !lt.irrefl
| i j (succ n) h₁ h₂ := by rewrite [pow_succ']; apply dvd_mul_of_dvd_right h₁
lemma pow_mod_eq_zero (i : nat) {n : nat} (h : n > 0) : (i ^ n) % i = 0 :=
iff.mp !dvd_iff_mod_eq_zero (dvd_pow i h)
lemma pow_dvd_of_pow_succ_dvd {p i n : nat} : p^(succ i) ∣ n → p^i ∣ n :=
suppose p^(succ i) ∣ n,
assert p^i ∣ p^(succ i),
by rewrite [pow_succ']; apply nat.dvd_of_eq_mul; apply rfl,
dvd.trans `p^i ∣ p^(succ i)` `p^(succ i) ∣ n`
lemma dvd_of_pow_succ_dvd_mul_pow {p i n : nat} (Ppos : p > 0) :
p^(succ i) ∣ (n * p^i) → p ∣ n :=
by rewrite [pow_succ]; apply nat.dvd_of_mul_dvd_mul_right; apply pow_pos_of_pos _ Ppos
lemma coprime_pow_right {a b} : ∀ n, coprime b a → coprime b (a^n)
| 0 h := !comprime_one_right
| (succ n) h :=
begin
rewrite [pow_succ'],
apply coprime_mul_right,
exact coprime_pow_right n h,
exact h
end
lemma coprime_pow_left {a b} : ∀ n, coprime b a → coprime (b^n) a :=
take n, suppose coprime b a,
coprime_swap (coprime_pow_right n (coprime_swap this))
end nat
|
05ea52bdcf57e460f3db8a1cdba06a3edd36d323 | 4fa118f6209450d4e8d058790e2967337811b2b5 | /src/sheaves/presheaf_of_rings.lean | c630ebb6e5e0b9838ac0666a9ac9c90ca497a205 | [
"Apache-2.0"
] | permissive | leanprover-community/lean-perfectoid-spaces | 16ab697a220ed3669bf76311daa8c466382207f7 | 95a6520ce578b30a80b4c36e36ab2d559a842690 | refs/heads/master | 1,639,557,829,139 | 1,638,797,866,000 | 1,638,797,866,000 | 135,769,296 | 96 | 10 | Apache-2.0 | 1,638,797,866,000 | 1,527,892,754,000 | Lean | UTF-8 | Lean | false | false | 1,571 | lean | /-
Presheaf of rings.
https://stacks.math.columbia.edu/tag/006N
Author: Ramon Fernandez Mir
-/
import sheaves.presheaf
universes u v
-- Definition of a presheaf of rings.
structure presheaf_of_rings (α : Type u) [topological_space α]
extends presheaf α :=
(Fring : ∀ (U), comm_ring (F U))
(res_is_ring_hom : ∀ (U V) (HVU : V ⊆ U), is_ring_hom (res U V HVU))
instance {α : Type u} [topological_space α]
: has_coe (presheaf_of_rings α) (presheaf α)
:= ⟨λ F, F.to_presheaf⟩
attribute [instance] presheaf_of_rings.Fring
attribute [instance] presheaf_of_rings.res_is_ring_hom
instance presheaf_of_rings.comm_ring {α : Type u} [topological_space α]
(F : presheaf_of_rings α) (U : topological_space.opens α) : comm_ring (F U) :=
F.Fring U
namespace presheaf_of_rings
variables {α : Type u} {β : Type v} [topological_space α] [topological_space β]
-- Morphism of presheaf of rings.
structure morphism (F G : presheaf_of_rings α)
extends presheaf.morphism F.to_presheaf G.to_presheaf :=
(ring_homs : ∀ (U), is_ring_hom (map U))
local infix `⟶`:80 := morphism
def identity (F : presheaf_of_rings α) : F ⟶ F :=
{ ring_homs := λ U, is_ring_hom.id,
..presheaf.id F.to_presheaf }
-- Isomorphic presheaves of rings.
local infix `⊚`:80 := presheaf.comp
structure iso (F G : presheaf_of_rings α) :=
(mor : F ⟶ G)
(inv : G ⟶ F)
(mor_inv_id : mor.to_morphism ⊚ inv.to_morphism = presheaf.id F.to_presheaf)
(inv_mor_id : inv.to_morphism ⊚ mor.to_morphism = presheaf.id G.to_presheaf)
end presheaf_of_rings
|
132440213687c4c3e507e10e6e483364e9c32429 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/geometry/manifold/partition_of_unity.lean | 372b10dfa89b139dece7b352ac3741aae5d07684 | [
"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 | 18,968 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import geometry.manifold.algebra.structures
import geometry.manifold.bump_function
import topology.paracompact
import topology.partition_of_unity
import topology.shrinking_lemma
/-!
# Smooth partition of unity
In this file we define two structures, `smooth_bump_covering` and `smooth_partition_of_unity`. Both
structures describe coverings of a set by a locally finite family of supports of smooth functions
with some additional properties. The former structure is mostly useful as an intermediate step in
the construction of a smooth partition of unity but some proofs that traditionally deal with a
partition of unity can use a `smooth_bump_covering` as well.
Given a real manifold `M` and its subset `s`, a `smooth_bump_covering ι I M s` is a collection of
`smooth_bump_function`s `f i` indexed by `i : ι` such that
* the center of each `f i` belongs to `s`;
* the family of sets `support (f i)` is locally finite;
* for each `x ∈ s`, there exists `i : ι` such that `f i =ᶠ[𝓝 x] 1`.
In the same settings, a `smooth_partition_of_unity ι I M s` is a collection of smooth nonnegative
functions `f i : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯`, `i : ι`, such that
* the family of sets `support (f i)` is locally finite;
* for each `x ∈ s`, the sum `∑ᶠ i, f i x` equals one;
* for each `x`, the sum `∑ᶠ i, f i x` is less than or equal to one.
We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each
index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than
being subordinate to an open covering of `M`, because we make no assumption about the way `U x`
depends on `x`.
We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology,
for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s`
subordinate to `U`. Then we use this fact to prove a similar statement about smooth partitions of
unity.
## Implementation notes
## TODO
* Build a framework for to transfer local definitions to global using partition of unity and use it
to define, e.g., the integral of a differential form over a manifold.
## Tags
smooth bump function, partition of unity
-/
universes uι uE uH uM
open function filter finite_dimensional set
open_locale topological_space manifold classical filter big_operators
noncomputable theory
variables {ι : Type uι}
{E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{H : Type uH} [topological_space H] (I : model_with_corners ℝ E H)
{M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
/-!
### Covering by supports of smooth bump functions
In this section we define `smooth_bump_covering ι I M s` to be a collection of
`smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x
∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of
this type is useful to construct a smooth partition of unity and can be used instead of a partition
of unity in some proofs.
We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for
any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s`
subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any
compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/
variables (ι M)
/-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if
* `(f i).c ∈ s` for all `i`;
* the family `λ i, support (f i)` is locally finite;
* for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`;
in other words, `x` belongs to the interior of `{y | f i y = 1}`;
If `M` is a finite dimensional real manifold which is a sigma-compact Hausdorff topological space,
then for every covering `U : M → set M`, `∀ x, U x ∈ 𝓝 x`, there exists a `smooth_bump_covering`
subordinate to `U`, see `smooth_bump_covering.exists_is_subordinate`.
This covering can be used, e.g., to construct a partition of unity and to prove the weak
Whitney embedding theorem. -/
@[nolint has_inhabited_instance]
structure smooth_bump_covering (s : set M := univ) :=
(c : ι → M)
(to_fun : Π i, smooth_bump_function I (c i))
(c_mem' : ∀ i, c i ∈ s)
(locally_finite' : locally_finite (λ i, support (to_fun i)))
(eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1)
/-- We say that that a collection of functions form a smooth partition of unity on a set `s` if
* all functions are infinitely smooth and nonnegative;
* the family `λ i, support (f i)` is locally finite;
* for all `x ∈ s` the sum `∑ᶠ i, f i x` equals one;
* for all `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. -/
structure smooth_partition_of_unity (s : set M := univ) :=
(to_fun : ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯)
(locally_finite' : locally_finite (λ i, support (to_fun i)))
(nonneg' : ∀ i x, 0 ≤ to_fun i x)
(sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, to_fun i x = 1)
(sum_le_one' : ∀ x, ∑ᶠ i, to_fun i x ≤ 1)
variables {ι I M}
namespace smooth_partition_of_unity
variables {s : set M} (f : smooth_partition_of_unity ι I M s)
instance {s : set M} : has_coe_to_fun (smooth_partition_of_unity ι I M s)
(λ _, ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) :=
⟨smooth_partition_of_unity.to_fun⟩
protected lemma locally_finite : locally_finite (λ i, support (f i)) :=
f.locally_finite'
lemma nonneg (i : ι) (x : M) : 0 ≤ f i x := f.nonneg' i x
lemma sum_eq_one {x} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx
lemma sum_le_one (x : M) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x
/-- Reinterpret a smooth partition of unity as a continuous partition of unity. -/
def to_partition_of_unity : partition_of_unity ι M s :=
{ to_fun := λ i, f i, .. f }
lemma smooth_sum : smooth I 𝓘(ℝ) (λ x, ∑ᶠ i, f i x) :=
smooth_finsum (λ i, (f i).smooth) f.locally_finite
lemma le_one (i : ι) (x : M) : f i x ≤ 1 := f.to_partition_of_unity.le_one i x
lemma sum_nonneg (x : M) : 0 ≤ ∑ᶠ i, f i x := f.to_partition_of_unity.sum_nonneg x
/-- A smooth partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same
type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/
def is_subordinate (f : smooth_partition_of_unity ι I M s) (U : ι → set M) :=
∀ i, tsupport (f i) ⊆ U i
@[simp] lemma is_subordinate_to_partition_of_unity {f : smooth_partition_of_unity ι I M s}
{U : ι → set M} :
f.to_partition_of_unity.is_subordinate U ↔ f.is_subordinate U :=
iff.rfl
alias is_subordinate_to_partition_of_unity ↔
_ smooth_partition_of_unity.is_subordinate.to_partition_of_unity
end smooth_partition_of_unity
namespace bump_covering
-- Repeat variables to drop [finite_dimensional ℝ E] and [smooth_manifold_with_corners I M]
lemma smooth_to_partition_of_unity {E : Type uE} [normed_group E] [normed_space ℝ E]
{H : Type uH} [topological_space H] {I : model_with_corners ℝ E H}
{M : Type uM} [topological_space M] [charted_space H M] {s : set M}
(f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) :
smooth I 𝓘(ℝ) (f.to_partition_of_unity i) :=
(hf i).mul $ smooth_finprod_cond (λ j _, smooth_const.sub (hf j)) $
by { simp only [mul_support_one_sub], exact f.locally_finite }
variables {s : set M}
/-- A `bump_covering` such that all functions in this covering are smooth generates a smooth
partition of unity.
In our formalization, not every `f : bump_covering ι M s` with smooth functions `f i` is a
`smooth_bump_covering`; instead, a `smooth_bump_covering` is a covering by supports of
`smooth_bump_function`s. So, we define `bump_covering.to_smooth_partition_of_unity`, then reuse it
in `smooth_bump_covering.to_smooth_partition_of_unity`. -/
def to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) :
smooth_partition_of_unity ι I M s :=
{ to_fun := λ i, ⟨f.to_partition_of_unity i, f.smooth_to_partition_of_unity hf i⟩,
.. f.to_partition_of_unity }
@[simp] lemma to_smooth_partition_of_unity_to_partition_of_unity (f : bump_covering ι M s)
(hf : ∀ i, smooth I 𝓘(ℝ) (f i)) :
(f.to_smooth_partition_of_unity hf).to_partition_of_unity = f.to_partition_of_unity :=
rfl
@[simp] lemma coe_to_smooth_partition_of_unity (f : bump_covering ι M s)
(hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) :
⇑(f.to_smooth_partition_of_unity hf i) = f.to_partition_of_unity i :=
rfl
lemma is_subordinate.to_smooth_partition_of_unity {f : bump_covering ι M s}
{U : ι → set M} (h : f.is_subordinate U) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) :
(f.to_smooth_partition_of_unity hf).is_subordinate U :=
h.to_partition_of_unity
end bump_covering
namespace smooth_bump_covering
variables {s : set M} {U : M → set M} (fs : smooth_bump_covering ι I M s) {I}
instance : has_coe_to_fun (smooth_bump_covering ι I M s)
(λ x, Π (i : ι), smooth_bump_function I (x.c i)) :=
⟨to_fun⟩
@[simp] lemma coe_mk (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i))
(h₁ h₂ h₃) : ⇑(mk c to_fun h₁ h₂ h₃ : smooth_bump_covering ι I M s) = to_fun :=
rfl
/--
We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each
index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than
being subordinate to an open covering of `M`, because we make no assumption about the way `U x`
depends on `x`.
-/
def is_subordinate {s : set M} (f : smooth_bump_covering ι I M s) (U : M → set M) :=
∀ i, tsupport (f i) ⊆ U (f.c i)
lemma is_subordinate.support_subset {fs : smooth_bump_covering ι I M s} {U : M → set M}
(h : fs.is_subordinate U) (i : ι) :
support (fs i) ⊆ U (fs.c i) :=
subset.trans subset_closure (h i)
variable (I)
/-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space.
Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set
in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`.
Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/
lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s)
(hU : ∀ x ∈ s, U x ∈ 𝓝 x) :
∃ (ι : Type uM) (f : smooth_bump_covering ι I M s), f.is_subordinate U :=
begin
-- First we deduce some missing instances
haveI : locally_compact_space H := I.locally_compact,
haveI : locally_compact_space M := charted_space.locally_compact H,
haveI : normal_space M := normal_of_paracompact_t2,
-- Next we choose a covering by supports of smooth bump functions
have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx),
rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB
with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf,
/- Then we use the shrinking lemma to get a covering by smaller open -/
rcases exists_subset_Union_closed_subset hs (λ i, (f i).open_support)
(λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩,
choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i),
refine ⟨ι, ⟨c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩,
{ simpa only [smooth_bump_function.support_update_r] },
{ refine (mem_Union.1 $ hsV hx).imp (λ i hi, _),
exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt
((f i).support_subset_source $ hVf _ hi) (hr i hi).2 },
{ simpa only [coe_mk, smooth_bump_function.support_update_r, tsupport] using hfU i }
end
variables {I M}
protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite'
protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite :=
fs.locally_finite.point_finite x
lemma mem_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) :
x ∈ (chart_at H (fs.c i)).source :=
(fs i).support_subset_source $ by simp [h]
lemma mem_ext_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) :
x ∈ (ext_chart_at I (fs.c i)).source :=
by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h }
/-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/
def ind (x : M) (hx : x ∈ s) : ι := (fs.eventually_eq_one' x hx).some
lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 :=
(fs.eventually_eq_one' x hx).some_spec
lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 :=
(fs.eventually_eq_one x hx).eq_of_nhds
lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) :=
by simp [fs.apply_ind x hx]
lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) :
x ∈ (chart_at H (fs.c (fs.ind x hx))).source :=
fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx)
lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) :
x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source :=
fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx)
/-- The index type of a `smooth_bump_covering` of a compact manifold is finite. -/
protected def fintype [compact_space M] : fintype ι :=
fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support
variable [t2_space M]
/-- Reinterpret a `smooth_bump_covering` as a continuous `bump_covering`. Note that not every
`f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`. -/
def to_bump_covering : bump_covering ι M s :=
{ to_fun := λ i, ⟨fs i, (fs i).continuous⟩,
locally_finite' := fs.locally_finite,
nonneg' := λ i x, (fs i).nonneg,
le_one' := λ i x, (fs i).le_one,
eventually_eq_one' := fs.eventually_eq_one' }
@[simp] lemma is_subordinate_to_bump_covering {f : smooth_bump_covering ι I M s} {U : M → set M} :
f.to_bump_covering.is_subordinate (λ i, U (f.c i)) ↔ f.is_subordinate U :=
iff.rfl
alias is_subordinate_to_bump_covering ↔
_ smooth_bump_covering.is_subordinate.to_bump_covering
/-- Every `smooth_bump_covering` defines a smooth partition of unity. -/
def to_smooth_partition_of_unity : smooth_partition_of_unity ι I M s :=
fs.to_bump_covering.to_smooth_partition_of_unity (λ i, (fs i).smooth)
lemma to_smooth_partition_of_unity_apply (i : ι) (x : M) :
fs.to_smooth_partition_of_unity i x = fs i x * ∏ᶠ j (hj : well_ordering_rel j i), (1 - fs j x) :=
rfl
lemma to_smooth_partition_of_unity_eq_mul_prod (i : ι) (x : M) (t : finset ι)
(ht : ∀ j, well_ordering_rel j i → fs j x ≠ 0 → j ∈ t) :
fs.to_smooth_partition_of_unity i x =
fs i x * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j x) :=
fs.to_bump_covering.to_partition_of_unity_eq_mul_prod i x t ht
lemma exists_finset_to_smooth_partition_of_unity_eventually_eq (i : ι) (x : M) :
∃ t : finset ι, fs.to_smooth_partition_of_unity i =ᶠ[𝓝 x]
fs i * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j) :=
fs.to_bump_covering.exists_finset_to_partition_of_unity_eventually_eq i x
lemma to_smooth_partition_of_unity_zero_of_zero {i : ι} {x : M} (h : fs i x = 0) :
fs.to_smooth_partition_of_unity i x = 0 :=
fs.to_bump_covering.to_partition_of_unity_zero_of_zero h
lemma support_to_smooth_partition_of_unity_subset (i : ι) :
support (fs.to_smooth_partition_of_unity i) ⊆ support (fs i) :=
fs.to_bump_covering.support_to_partition_of_unity_subset i
lemma is_subordinate.to_smooth_partition_of_unity {f : smooth_bump_covering ι I M s} {U : M → set M}
(h : f.is_subordinate U) :
f.to_smooth_partition_of_unity.is_subordinate (λ i, U (f.c i)) :=
h.to_bump_covering.to_partition_of_unity
lemma sum_to_smooth_partition_of_unity_eq (x : M) :
∑ᶠ i, fs.to_smooth_partition_of_unity i x = 1 - ∏ᶠ i, (1 - fs i x) :=
fs.to_bump_covering.sum_to_partition_of_unity_eq x
end smooth_bump_covering
variable (I)
/-- Given two disjoint closed sets in a Hausdorff σ-compact finite dimensional manifold, there
exists an infinitely smooth function that is equal to `0` on one of them and is equal to one on the
other. -/
lemma exists_smooth_zero_one_of_closed [t2_space M] [sigma_compact_space M] {s t : set M}
(hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) :
∃ f : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 :=
begin
have : ∀ x ∈ t, sᶜ ∈ 𝓝 x, from λ x hx, hs.is_open_compl.mem_nhds (disjoint_right.1 hd hx),
rcases smooth_bump_covering.exists_is_subordinate I ht this with ⟨ι, f, hf⟩,
set g := f.to_smooth_partition_of_unity,
refine ⟨⟨_, g.smooth_sum⟩, λ x hx, _, λ x, g.sum_eq_one, λ x, ⟨g.sum_nonneg x, g.sum_le_one x⟩⟩,
suffices : ∀ i, g i x = 0,
by simp only [this, cont_mdiff_map.coe_fn_mk, finsum_zero, pi.zero_apply],
refine λ i, f.to_smooth_partition_of_unity_zero_of_zero _,
exact nmem_support.1 (subset_compl_comm.1 (hf.support_subset i) hx)
end
variable {I}
namespace smooth_partition_of_unity
/-- A `smooth_partition_of_unity` that consists of a single function, uniformly equal to one,
defined as an example for `inhabited` instance. -/
def single (i : ι) (s : set M) : smooth_partition_of_unity ι I M s :=
(bump_covering.single i s).to_smooth_partition_of_unity $ λ j,
begin
rcases eq_or_ne j i with rfl|h,
{ simp only [smooth_one, continuous_map.coe_one, bump_covering.coe_single, pi.single_eq_same] },
{ simp only [smooth_zero, bump_covering.coe_single, pi.single_eq_of_ne h,
continuous_map.coe_zero] }
end
instance [inhabited ι] (s : set M) : inhabited (smooth_partition_of_unity ι I M s) :=
⟨single default s⟩
variables [t2_space M] [sigma_compact_space M]
/-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set
`s`, then there exists a `bump_covering ι X s` that is subordinate to `U`. -/
lemma exists_is_subordinate {s : set M} (hs : is_closed s) (U : ι → set M) (ho : ∀ i, is_open (U i))
(hU : s ⊆ ⋃ i, U i) :
∃ f : smooth_partition_of_unity ι I M s, f.is_subordinate U :=
begin
haveI : locally_compact_space H := I.locally_compact,
haveI : locally_compact_space M := charted_space.locally_compact H,
haveI : normal_space M := normal_of_paracompact_t2,
rcases bump_covering.exists_is_subordinate_of_prop (smooth I 𝓘(ℝ)) _ hs U ho hU
with ⟨f, hf, hfU⟩,
{ exact ⟨f.to_smooth_partition_of_unity hf, hfU.to_smooth_partition_of_unity hf⟩ },
{ intros s t hs ht hd,
rcases exists_smooth_zero_one_of_closed I hs ht hd with ⟨f, hf⟩,
exact ⟨f, f.smooth, hf⟩ }
end
end smooth_partition_of_unity
|
e58a3c13c4e9d5ac94a14c2d425041f297b97d40 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/elements.lean | efab8ad52ccada3e57ca639466f7af2546f55dbd | [
"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 | 4,857 | 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.structured_arrow
import category_theory.groupoid
import category_theory.punit
/-!
# The category of elements
This file defines the category of elements, also known as (a special case of) the Grothendieck
construction.
Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`.
A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`.
## Implementation notes
This construction is equivalent to a special case of a comma construction, so this is mostly just a
more convenient API. We prove the equivalence in
`category_theory.category_of_elements.structured_arrow_equivalence`.
## References
* [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017]
* <https://en.wikipedia.org/wiki/Category_of_elements>
* <https://ncatlab.org/nlab/show/category+of+elements>
## Tags
category of elements, Grothendieck construction, comma category
-/
namespace category_theory
universes w v u
variables {C : Type u} [category.{v} C]
/--
The type of objects for the category of elements of a functor `F : C ⥤ Type`
is a pair `(X : C, x : F.obj X)`.
-/
@[nolint has_inhabited_instance]
def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c)
/-- The category structure on `F.elements`, for `F : C ⥤ Type`.
A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`.
-/
instance category_of_elements (F : C ⥤ Type w) : category.{v} F.elements :=
{ hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 },
id := λ p, ⟨𝟙 p.1, by obviously⟩,
comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ }
namespace category_of_elements
@[ext]
lemma ext (F : C ⥤ Type w) {x y : F.elements} (f g : x ⟶ y) (w : f.val = g.val) : f = g :=
subtype.ext_val w
@[simp] lemma comp_val {F : C ⥤ Type w} {p q r : F.elements} {f : p ⟶ q} {g : q ⟶ r} :
(f ≫ g).val = f.val ≫ g.val := rfl
@[simp] lemma id_val {F : C ⥤ Type w} {p : F.elements} : (𝟙 p : p ⟶ p).val = 𝟙 p.1 := rfl
end category_of_elements
noncomputable
instance groupoid_of_elements {G : Type u} [groupoid.{v} G] (F : G ⥤ Type w) :
groupoid F.elements :=
{ inv := λ p q f, ⟨inv f.val,
calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2
... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp
... = p.2 : by {rw ←functor.map_comp, simp}⟩, }
namespace category_of_elements
variable (F : C ⥤ Type w)
/-- The functor out of the category of elements which forgets the element. -/
@[simps]
def π : F.elements ⥤ C :=
{ obj := λ X, X.1,
map := λ X Y f, f.val }
/--
A natural transformation between functors induces a functor between the categories of elements.
-/
@[simps]
def map {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : F₁.elements ⥤ F₂.elements :=
{ obj := λ t, ⟨t.1, α.app t.1 t.2⟩,
map := λ t₁ t₂ k, ⟨k.1, by simpa [←k.2] using (functor_to_types.naturality _ _ α k.1 t₁.2).symm⟩ }
@[simp] lemma map_π {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl
/-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/
def to_structured_arrow : F.elements ⥤ structured_arrow punit F :=
{ obj := λ X, structured_arrow.mk (λ _, X.2),
map := λ X Y f, structured_arrow.hom_mk f.val (by tidy) }
@[simp] lemma to_structured_arrow_obj (X) :
(to_structured_arrow F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl
@[simp] lemma to_comma_map_right {X Y} (f : X ⟶ Y) :
((to_structured_arrow F).map f).right = f.val := rfl
/-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/
def from_structured_arrow : structured_arrow punit F ⥤ F.elements :=
{ obj := λ X, ⟨X.right, X.hom (punit.star)⟩,
map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ }
@[simp] lemma from_structured_arrow_obj (X) :
(from_structured_arrow F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl
@[simp] lemma from_structured_arrow_map {X Y} (f : X ⟶ Y) :
(from_structured_arrow F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl
/-- The equivalence between the category of elements `F.elements`
and the comma category `(*, F)`. -/
@[simps]
def structured_arrow_equivalence : F.elements ≌ structured_arrow punit F :=
equivalence.mk (to_structured_arrow F) (from_structured_arrow F)
(nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy))
(nat_iso.of_components
(λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } })
(by tidy))
end category_of_elements
end category_theory
|
cedeefd13e25742098c81c5bdc031177f6c44352 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/logic/axioms/funext.lean | 0e065341b1caea7a3286b0785aaa3e006bacf98a | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,151 | 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
-- logic.axioms.funext
-- ===================
import logic.cast algebra.function data.sigma
open function eq.ops
-- Function extensionality
axiom funext : ∀ {A : Type} {B : A → Type} {f g : Π a, B a} (H : ∀ a, f a = g a), f = g
namespace function
variables {A B C D: Type}
theorem compose.assoc (f : C → D) (g : B → C) (h : A → B) : (f ∘ g) ∘ h = f ∘ (g ∘ h) :=
funext (take x, rfl)
theorem compose.left_id (f : A → B) : id ∘ f = f :=
funext (take x, rfl)
theorem compose.right_id (f : A → B) : f ∘ id = f :=
funext (take x, rfl)
theorem compose_const_right (f : B → C) (b : B) : f ∘ (const A b) = const A (f b) :=
funext (take x, rfl)
theorem hfunext {A : Type} {B : A → Type} {B' : A → Type} {f : Π x, B x} {g : Π x, B' x}
(H : ∀ a, f a == g a) : f == g :=
let HH : B = B' := (funext (λ x, heq.type_eq (H x))) in
cast_to_heq (funext (λ a, heq.to_eq (heq.trans (cast_app HH f a) (H a))))
end function
|
835fac00b11c98bdc32fede076eaa011c2c52d26 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/category_theory/limits/shapes/equalizers.lean | 0c3f979cc3e7937da3cfbdf027441414d3a76348 | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 31,847 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.epi_mono
import category_theory.limits.limits
/-!
# Equalizers and coequalizers
This file defines (co)equalizers as special cases of (co)limits.
An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known
from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`.
A coequalizer is the dual concept.
## Main definitions
* `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams
* `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`.
* a `fork` is a cone over a parallel pair.
* there is really only one interesting morphism in a fork: the arrow from the vertex of the fork
to the domain of f and g. It is called `fork.ι`.
* an `equalizer` is now just a `limit (parallel_pair f g)`
Each of these has a dual.
## Main statements
* `equalizer.ι_mono` states that every equalizer map is a monomorphism
* `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer
of `f` and `f`.
## Implementation notes
As with the other special shapes in the limits library, all the definitions here are given as
`abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about
general limits can be used.
## References
* [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1]
-/
noncomputable theory
open category_theory
namespace category_theory.limits
local attribute [tidy] tactic.case_bash
universes v u u₂
/-- The type of objects for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v
| zero | one
open walking_parallel_pair
/-- The type family of morphisms for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq] inductive walking_parallel_pair_hom :
walking_parallel_pair → walking_parallel_pair → Type v
| left : walking_parallel_pair_hom zero one
| right : walking_parallel_pair_hom zero one
| id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X
/-- Satisfying the inhabited linter -/
instance : inhabited (walking_parallel_pair_hom zero one) :=
{ default := walking_parallel_pair_hom.left }
open walking_parallel_pair_hom
/-- Composition of morphisms in the indexing diagram for (co)equalizers. -/
def walking_parallel_pair_hom.comp :
Π (X Y Z : walking_parallel_pair)
(f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z),
walking_parallel_pair_hom X Z
| _ _ _ (id _) h := h
| _ _ _ left (id one) := left
| _ _ _ right (id one) := right
.
instance walking_parallel_pair_hom_category : small_category walking_parallel_pair :=
{ hom := walking_parallel_pair_hom,
id := walking_parallel_pair_hom.id,
comp := walking_parallel_pair_hom.comp }
@[simp]
lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) :
walking_parallel_pair_hom.id X = 𝟙 X :=
rfl
variables {C : Type u} [category.{v} C]
variables {X Y : C}
/-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with
common domain and codomain. -/
def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| one := Y
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, left := f
| _, _, right := g
end,
-- `tidy` can cope with this, but it's too slow:
map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }.
@[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl
@[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl
@[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl
@[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl
@[simp] lemma parallel_pair_functor_obj
{F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) :
(parallel_pair (F.map left) (F.map right)).obj j = F.obj j :=
begin
cases j; refl
end
/-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a
`parallel_pair` -/
@[simps {rhs_md := semireducible}]
def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) :
F ≅ parallel_pair (F.map left) (F.map right) :=
nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy
/-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/
abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g)
/-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/
abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g)
variables {f g : X ⟶ Y}
@[simp, reassoc] lemma fork.app_zero_left (s : fork f g) :
s.π.app zero ≫ f = s.π.app one :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma fork.app_zero_right (s : fork f g) :
s.π.app zero ≫ g = s.π.app one :=
by rw [←s.w right, parallel_pair_map_right]
@[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) :
f ≫ s.ι.app one = s.ι.app zero :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) :
g ≫ s.ι.app one = s.ι.app zero :=
by rw [←s.w right, parallel_pair_map_right]
/-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`.
-/
@[simps]
def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g :=
{ X := P,
π :=
{ app := λ X, begin cases X, exact ι, exact ι ≫ f, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
{ dsimp, simp, }, -- See note [dsimp, simp].
{ exact w },
{ dsimp, simp, },
end } }
/-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying
`f ≫ π = g ≫ π`. -/
@[simps]
def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g :=
{ X := P,
ι :=
{ app := λ X, begin cases X, exact f ≫ π, exact π, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
{ dsimp, simp, },
{ exact w.symm },
{ dsimp, simp, },
end } }
/-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X`
and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the
shorter name `fork.ι t`. -/
abbreviation fork.ι (t : fork f g) := t.π.app zero
/-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms
`t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is
interesting, and we give it the shorter name `cofork.π t`. -/
abbreviation cofork.π (t : cofork f g) := t.ι.app one
@[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
fork.ι (fork.of_ι ι w) = ι := rfl
@[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
cofork.π (cofork.of_π π w) = π := rfl
lemma fork.ι_eq_app_zero (t : fork f g) : fork.ι t = t.π.app zero := rfl
lemma cofork.π_eq_app_one (t : cofork f g) : cofork.π t = t.ι.app one := rfl
@[reassoc]
lemma fork.condition (t : fork f g) : fork.ι t ≫ f = fork.ι t ≫ g :=
by rw [t.app_zero_left, t.app_zero_right]
@[reassoc]
lemma cofork.condition (t : cofork f g) : f ≫ cofork.π t = g ≫ cofork.π t :=
by rw [t.left_app_one, t.right_app_one]
/-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the
first map -/
lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair),
k ≫ s.π.app j = l ≫ s.π.app j
| zero := h
| one := by rw [←fork.app_zero_left, reassoc_of h]
/-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for
the second map -/
lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair),
s.ι.app j ≫ k = s.ι.app j ≫ l
| zero := by simp only [←cofork.left_app_one, category.assoc, h]
| one := h
lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l :=
hs.hom_ext $ fork.equalizer_ext _ h
lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l :=
hs.hom_ext $ cofork.coequalizer_ext _ h
/-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying
`k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/
def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ s.X // l ≫ fork.ι s = k} :=
⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩
/-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying
`f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/
def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W)
(h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} :=
⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩
/-- This is a slightly more convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content -/
def fork.is_limit.mk (t : fork f g)
(lift : Π (s : fork f g), s.X ⟶ t.X)
(fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s)
(uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X)
(w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) :
is_limit t :=
{ lift := lift,
fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $
by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl,
uniq' := uniq }
/-- This is another convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content, and allows access to the
same `s` for all parts. -/
def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g)
(create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) :
is_limit t :=
fork.is_limit.mk t
(λ s, (create s).1)
(λ s, (create s).2.1)
(λ s m w, (create s).2.2 (w zero))
/-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It
only asks for a proof of facts that carry any mathematical content -/
def cofork.is_colimit.mk (t : cofork f g)
(desc : Π (s : cofork f g), t.X ⟶ s.X)
(fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s)
(uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X)
(w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) :
is_colimit t :=
{ desc := desc,
fac' := λ s j, walking_parallel_pair.cases_on j
(by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s),
uniq' := uniq }
/-- This is another convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content, and allows access to the
same `s` for all parts. -/
def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g)
(create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) :
is_colimit t :=
cofork.is_colimit.mk t
(λ s, (create s).1)
(λ s, (create s).2.1)
(λ s m w, (create s).2.2 (w one))
/-- This is a helper construction that can be useful when verifying that a category has all
equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`,
we get a cone on `F`.
If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`,
which you may find to be an easier way of achieving your goal. -/
def cone.of_fork
{F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } }
/-- This is a helper construction that can be useful when verifying that a category has all
coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`,
we get a cocone on `F`.
If you're thinking about using this, have a look at
`has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of
achieving your goal. -/
def cocone.of_cofork
{F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } }
@[simp] lemma cone.of_fork_π
{F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) (j) :
(cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cocone.of_cofork_ι
{F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) (j) :
(cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
/-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on
`F.map left` and `F.map right`. -/
def fork.of_cone
{F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) :=
{ X := t.X,
π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } }
/-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on
`F.map left` and `F.map right`. -/
def cofork.of_cocone
{F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) :=
{ X := t.X,
ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } }
@[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ C} (t : cone F) (j) :
(fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair ⥤ C} (t : cocone F) (j) :
(cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
/--
Helper function for constructing morphisms between equalizer forks.
-/
@[simps]
def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t :=
{ hom := k,
w' :=
begin
rintro ⟨_|_⟩,
{ exact w },
{ simpa using w =≫ f },
end }
/--
To construct an isomorphism between forks,
it suffices to give an isomorphism between the cone points
and check that it commutes with the `ι` morphisms.
-/
@[simps]
def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t :=
{ hom := fork.mk_hom i.hom w,
inv := fork.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) }
/--
Helper function for constructing morphisms between coequalizer coforks.
-/
@[simps]
def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t :=
{ hom := k,
w' :=
begin
rintro ⟨_|_⟩,
simpa using f ≫= w,
exact w,
end }
/--
To construct an isomorphism between coforks,
it suffices to give an isomorphism between the cocone points
and check that it commutes with the `π` morphisms.
-/
def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t :=
{ hom := cofork.mk_hom i.hom w,
inv := cofork.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) }
variables (f g)
section
/--
`has_equalizer f g` represents a particular choice of limiting cone
for the parallel pair of morphisms `f` and `g`.
-/
abbreviation has_equalizer := has_limit (parallel_pair f g)
variables [has_equalizer f g]
/-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by
saying `equalizer f g`. -/
abbreviation equalizer : C := limit (parallel_pair f g)
/-- If an equalizer of `f` and `g` exists, we can access the inclusion
`equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/
abbreviation equalizer.ι : equalizer f g ⟶ X :=
limit.π (parallel_pair f g) zero
/--
An equalizer cone for a parallel pair `f` and `g`.
-/
abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g)
@[simp] lemma equalizer.fork_ι :
(equalizer.fork f g).ι = equalizer.ι f g := rfl
@[simp] lemma equalizer.fork_π_app_zero :
(equalizer.fork f g).π.app zero = equalizer.ι f g := rfl
@[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g :=
fork.condition $ limit.cone $ parallel_pair f g
/-- The equalizer built from `equalizer.ι f g` is limiting. -/
def equalizer_is_equalizer : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) :=
is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy))
variables {f g}
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g`
via `equalizer.lift : W ⟶ equalizer f g`. -/
abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g :=
limit.lift (parallel_pair f g) (fork.of_ι k h)
@[simp, reassoc]
lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
equalizer.lift k h ≫ equalizer.ι f g = k :=
limit.lift_π _ _
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g`
satisfying `l ≫ equalizer.ι f g = k`. -/
def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} :=
⟨equalizer.lift k h, equalizer.lift_ι _ _⟩
/-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer
map. -/
@[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g}
(h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l :=
fork.is_limit.hom_ext (limit.is_limit _) h
/-- An equalizer morphism is a monomorphism -/
instance equalizer.ι_mono : mono (equalizer.ι f g) :=
{ right_cancellation := λ Z h k w, equalizer.hom_ext w }
end
section
variables {f g}
/-- The equalizer morphism in any limit cone is a monomorphism. -/
lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) :
mono (fork.ι c) :=
{ right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/
def id_fork (h : f = g) : fork f g :=
fork.of_ι (𝟙 X) $ h ▸ rfl
/-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/
def is_limit_id_fork (h : f = g) : is_limit (id_fork h) :=
fork.is_limit.mk _
(λ s, fork.ι s)
(λ s, category.comp_id _)
(λ s m h, by { convert h zero, exact (category.comp_id _).symm })
/-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)}
(h : is_limit c) : is_iso (c.π.app zero) :=
is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀
/-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) :=
is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _
/-- Every equalizer of `(f, f)` is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) :
is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq rfl h
/-- An equalizer that is an epimorphism is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)}
(h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h
end
instance has_equalizer_of_self : has_equalizer f f :=
has_limit.mk
{ cone := id_fork rfl,
is_limit := is_limit_id_fork rfl }
/-- The equalizer inclusion for `(f, f)` is an isomorphism. -/
instance equalizer.ι_of_self : is_iso (equalizer.ι f f) :=
equalizer.ι_of_eq rfl
/-- The equalizer of a morphism with itself is isomorphic to the source. -/
def equalizer.iso_source_of_self : equalizer f f ≅ X :=
as_iso (equalizer.ι f f)
@[simp] lemma equalizer.iso_source_of_self_hom :
(equalizer.iso_source_of_self f).hom = equalizer.ι f f :=
rfl
@[simp] lemma equalizer.iso_source_of_self_inv :
(equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) :=
rfl
section
/--
`has_coequalizer f g` represents a particular choice of colimiting cocone
for the parallel pair of morphisms `f` and `g`.
-/
abbreviation has_coequalizer := has_colimit (parallel_pair f g)
variables [has_coequalizer f g]
/-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by
saying `coequalizer f g`. -/
abbreviation coequalizer : C := colimit (parallel_pair f g)
/-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by
saying `coequalizer.π f g`. -/
abbreviation coequalizer.π : Y ⟶ coequalizer f g :=
colimit.ι (parallel_pair f g) one
/--
An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`.
-/
abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g)
@[simp] lemma coequalizer.cofork_π :
(coequalizer.cofork f g).π = coequalizer.π f g := rfl
@[simp] lemma coequalizer.cofork_ι_app_one :
(coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl
@[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g :=
cofork.condition $ colimit.cocone $ parallel_pair f g
/-- The cofork built from `coequalizer.π f g` is colimiting. -/
def coequalizer_is_coequalizer :
is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) :=
is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy))
variables {f g}
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f`
and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/
abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W :=
colimit.desc (parallel_pair f g) (cofork.of_π k h)
@[simp, reassoc]
lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
coequalizer.π f g ≫ coequalizer.desc k h = k :=
colimit.ι_desc _ _
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism
`l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/
def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
{l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} :=
⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩
/-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer
map -/
@[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W}
(h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l :=
cofork.is_colimit.hom_ext (colimit.is_colimit _) h
/-- A coequalizer morphism is an epimorphism -/
instance coequalizer.π_epi : epi (coequalizer.π f g) :=
{ left_cancellation := λ Z h k w, coequalizer.hom_ext w }
end
section
variables {f g}
/-- The coequalizer morphism in any colimit cocone is an epimorphism. -/
lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) :
epi (c.ι.app one) :=
{ left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/
def id_cofork (h : f = g) : cofork f g :=
cofork.of_π (𝟙 Y) $ h ▸ rfl
/-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/
def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) :=
cofork.is_colimit.mk _
(λ s, cofork.π s)
(λ s, category.id_comp _)
(λ s m h, by { convert h one, exact (category.id_comp _).symm })
/-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h
/-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) :
is_iso (coequalizer.π f g) :=
is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _
/-- Every coequalizer of `(f, f)` is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq rfl h
/-- A coequalizer that is a monomorphism is an isomorphism. -/
def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)}
(h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h
end
instance has_coequalizer_of_self : has_coequalizer f f :=
has_colimit.mk
{ cocone := id_cofork rfl,
is_colimit := is_colimit_id_cofork rfl }
/-- The coequalizer projection for `(f, f)` is an isomorphism. -/
instance coequalizer.π_of_self : is_iso (coequalizer.π f f) :=
coequalizer.π_of_eq rfl
/-- The coequalizer of a morphism with itself is isomorphic to the target. -/
def coequalizer.iso_target_of_self : coequalizer f f ≅ Y :=
(as_iso (coequalizer.π f f)).symm
@[simp] lemma coequalizer.iso_target_of_self_hom :
(coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) :=
rfl
@[simp] lemma coequalizer.iso_target_of_self_inv :
(coequalizer.iso_target_of_self f).inv = coequalizer.π f f :=
rfl
section comparison
variables {D : Type u₂} [category.{v} D] (G : C ⥤ D)
-- TODO: show this is an iso iff `G` preserves the equalizer of `f,g`.
/-- The comparison morphism for the equalizer of `f,g`. -/
def equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] :
G.obj (equalizer f g) ⟶ equalizer (G.map f) (G.map g) :=
equalizer.lift (G.map (equalizer.ι _ _)) (by simp only [←G.map_comp, equalizer.condition])
@[simp, reassoc]
lemma equalizer_comparison_comp_π [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] :
equalizer_comparison f g G ≫ equalizer.ι (G.map f) (G.map g) = G.map (equalizer.ι f g) :=
equalizer.lift_ι _ _
@[simp, reassoc]
lemma map_lift_equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)]
{Z : C} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) :
G.map (equalizer.lift h w) ≫ equalizer_comparison f g G =
equalizer.lift (G.map h) (by simp only [←G.map_comp, w]) :=
by { ext, simp [← G.map_comp] }
-- TODO: show this is an iso iff G preserves the coequalizer of `f,g`.
/-- The comparison morphism for the coequalizer of `f,g`. -/
def coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] :
coequalizer (G.map f) (G.map g) ⟶ G.obj (coequalizer f g) :=
coequalizer.desc (G.map (coequalizer.π _ _)) (by simp only [←G.map_comp, coequalizer.condition])
@[simp, reassoc]
lemma ι_comp_coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] :
coequalizer.π _ _ ≫ coequalizer_comparison f g G = G.map (coequalizer.π _ _) :=
coequalizer.π_desc _ _
@[simp, reassoc]
lemma coequalizer_comparison_map_desc [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)]
{Z : C} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) :
coequalizer_comparison f g G ≫ G.map (coequalizer.desc h w) =
coequalizer.desc (G.map h) (by simp only [←G.map_comp, w]) :=
by { ext, simp [← G.map_comp] }
end comparison
variables (C)
/-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/
abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C
/-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/
abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C
/-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/
lemma has_equalizers_of_has_limit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm }
/-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/
lemma has_coequalizers_of_has_colimit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C :=
{ has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) }
section
-- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
variables {C} [split_mono f]
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone.
-/
def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) :=
fork.of_ι f (by tidy)
@[simp] lemma cone_of_split_mono_π_app_zero : (cone_of_split_mono f).π.app zero = f := rfl
@[simp] lemma cone_of_split_mono_π_app_one : (cone_of_split_mono f).π.app one = f ≫ 𝟙 Y := rfl
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
-/
def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) :=
{ lift := λ s, s.π.app zero ≫ retraction f,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ rw [cone_of_split_mono_π_app_zero],
erw [category.assoc, ← s.π.naturality right, s.π.naturality left, category.comp_id], },
{ erw [cone_of_split_mono_π_app_one, category.comp_id, category.assoc,
← s.π.naturality right, category.id_comp], }
end,
uniq' := λ s m w, begin rw ←(w zero), simp, end, }
end
section
-- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
variables {C} [split_epi f]
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone.
-/
def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) :=
cofork.of_π f (by tidy)
@[simp] lemma cocone_of_split_epi_ι_app_one : (cocone_of_split_epi f).ι.app one = f := rfl
@[simp] lemma cocone_of_split_epi_ι_app_zero : (cocone_of_split_epi f).ι.app zero = 𝟙 X ≫ f := rfl
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
-/
def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) :=
{ desc := λ s, section_ f ≫ s.ι.app one,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ erw [cocone_of_split_epi_ι_app_zero, category.assoc, category.id_comp, ←category.assoc,
s.ι.naturality right, functor.const.obj_map, category.comp_id], },
{ erw [cocone_of_split_epi_ι_app_one, ←category.assoc, s.ι.naturality right,
←s.ι.naturality left, category.id_comp] }
end,
uniq' := λ s m w, begin rw ←(w one), simp, end, }
end
end category_theory.limits
|
ed4176d1316fea5572fcb50efae7b153b976a55d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1705.lean | 382afa39fbe5edc70e4316eab03252975a83057b | [
"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 | 406 | lean | def {u} stream (α : Type u) := nat → α
constant stream.cons {α} (a : α) (s : stream α) : stream α
notation (name := cons) h :: t := stream.cons h t
inductive T : Type
| mk : nat → T
notation `&-` := T.mk
example : T → T
| (&- x) := &- x --works
notation (name := head) `&-` := list.head
example : T → T
| (&- x) := &- x
def f {α} : list α → nat
| [] := 0
| (a::as) := f as + 1
|
031f8994b1ca7ffdc5794dc711dffd2e2fd9ea48 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/homology/functor.lean | 87f4bc213bacc480660898348190a6dbaf2fb1da | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,001 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.homology.homological_complex
/-!
# Complexes in functor categories
We can view a complex valued in a functor category `T ⥤ V` as
a functor from `T` to complexes valued in `V`.
## Future work
In fact this is an equivalence of categories.
-/
universes v u
open category_theory
open category_theory.limits
namespace homological_complex
variables {V : Type u} [category.{v} V] [has_zero_morphisms V]
variables {ι : Type*} {c : complex_shape ι}
/-- A complex of functors gives a functor to complexes. -/
@[simps obj map]
def as_functor {T : Type*} [category T]
(C : homological_complex (T ⥤ V) c) :
T ⥤ homological_complex V c :=
{ obj := λ t,
{ X := λ i, (C.X i).obj t,
d := λ i j, (C.d i j).app t,
d_comp_d' := λ i j k hij hjk, begin
have := C.d_comp_d i j k,
rw [nat_trans.ext_iff, function.funext_iff] at this,
exact this t
end,
shape' := λ i j h, begin
have := C.shape _ _ h,
rw [nat_trans.ext_iff, function.funext_iff] at this,
exact this t
end },
map := λ t₁ t₂ h,
{ f := λ i, (C.X i).map h,
comm' := λ i j hij, nat_trans.naturality _ _ },
map_id' := λ t, by { ext i, dsimp, rw (C.X i).map_id, },
map_comp' := λ t₁ t₂ t₃ h₁ h₂, by { ext i, dsimp, rw functor.map_comp, } }
/-- The functorial version of `homological_complex.as_functor`. -/
-- TODO in fact, this is an equivalence of categories.
@[simps]
def complex_of_functors_to_functor_to_complex {T : Type*} [category T] :
(homological_complex (T ⥤ V) c) ⥤ (T ⥤ homological_complex V c) :=
{ obj := λ C, C.as_functor,
map := λ C D f,
{ app := λ t,
{ f := λ i, (f.f i).app t,
comm' := λ i j w, nat_trans.congr_app (f.comm i j) t, },
naturality' := λ t t' g, by { ext i, exact (f.f i).naturality g, }, } }
end homological_complex
|
c96b41f424c6dd8bd41ad3e476c6882548c9541a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/witt_vector/is_poly.lean | d0dfef20a0fbd8ba4c712e4d09b25e01cd421ee8 | [
"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 | 23,368 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import algebra.ring.ulift
import ring_theory.witt_vector.basic
import data.mv_polynomial.funext
/-!
# The `is_poly` predicate
`witt_vector.is_poly` is a (type-valued) predicate on functions `f : Π R, 𝕎 R → 𝕎 R`.
It asserts that there is a family of polynomials `φ : ℕ → mv_polynomial ℕ ℤ`,
such that the `n`th coefficient of `f x` is equal to `φ n` evaluated on the coefficients of `x`.
Many operations on Witt vectors satisfy this predicate (or an analogue for higher arity functions).
We say that such a function `f` is a *polynomial function*.
The power of satisfying this predicate comes from `is_poly.ext`.
It shows that if `φ` and `ψ` witness that `f` and `g` are polynomial functions,
then `f = g` not merely when `φ = ψ`, but in fact it suffices to prove
```
∀ n, bind₁ φ (witt_polynomial p _ n) = bind₁ ψ (witt_polynomial p _ n)
```
(in other words, when evaluating the Witt polynomials on `φ` and `ψ`, we get the same values)
which will then imply `φ = ψ` and hence `f = g`.
Even though this sufficient condition looks somewhat intimidating,
it is rather pleasant to check in practice;
more so than direct checking of `φ = ψ`.
In practice, we apply this technique to show that the composition of `witt_vector.frobenius`
and `witt_vector.verschiebung` is equal to multiplication by `p`.
## Main declarations
* `witt_vector.is_poly`, `witt_vector.is_poly₂`:
two predicates that assert that a unary/binary function on Witt vectors
is polynomial in the coefficients of the input values.
* `witt_vector.is_poly.ext`, `witt_vector.is_poly₂.ext`:
two polynomial functions are equal if their families of polynomials are equal
after evaluating the Witt polynomials on them.
* `witt_vector.is_poly.comp` (+ many variants) show that unary/binary compositions
of polynomial functions are polynomial.
* `witt_vector.id_is_poly`, `witt_vector.neg_is_poly`,
`witt_vector.add_is_poly₂`, `witt_vector.mul_is_poly₂`:
several well-known operations are polynomial functions
(for Verschiebung, Frobenius, and multiplication by `p`, see their respective files).
## On higher arity analogues
Ideally, there should be a predicate `is_polyₙ` for functions of higher arity,
together with `is_polyₙ.comp` that shows how such functions compose.
Since mathlib does not have a library on composition of higher arity functions,
we have only implemented the unary and binary variants so far.
Nullary functions (a.k.a. constants) are treated
as constant functions and fall under the unary case.
## Tactics
There are important metaprograms defined in this file:
the tactics `ghost_simp` and `ghost_calc` and the attributes `@[is_poly]` and `@[ghost_simps]`.
These are used in combination to discharge proofs of identities between polynomial functions.
Any atomic proof of `is_poly` or `is_poly₂` (i.e. not taking additional `is_poly` arguments)
should be tagged as `@[is_poly]`.
Any lemma doing "ring equation rewriting" with polynomial functions should be tagged
`@[ghost_simps]`, e.g.
```lean
@[ghost_simps]
lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) :
bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1))
```
Proofs of identities between polynomial functions will often follow the pattern
```lean
begin
ghost_calc _,
<minor preprocessing>,
ghost_simp
end
```
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
/-
### Simplification tactics
`ghost_simp` is used later in the development for certain simplifications.
We define it here so it is a shared import.
-/
mk_simp_attribute ghost_simps
"Simplification rules for ghost equations"
namespace tactic
namespace interactive
setup_tactic_parser
/-- A macro for a common simplification when rewriting with ghost component equations. -/
meta def ghost_simp (lems : parse simp_arg_list) : tactic unit :=
do tactic.try tactic.intro1,
simp none none tt
(lems ++ [simp_arg_type.symm_expr ``(sub_eq_add_neg)])
[`ghost_simps] (loc.ns [none])
/--
`ghost_calc` is a tactic for proving identities between polynomial functions.
Typically, when faced with a goal like
```lean
∀ (x y : 𝕎 R), verschiebung (x * frobenius y) = verschiebung x * y
```
you can
1. call `ghost_calc`
2. do a small amount of manual work -- maybe nothing, maybe `rintro`, etc
3. call `ghost_simp`
and this will close the goal.
`ghost_calc` cannot detect whether you are dealing with unary or binary polynomial functions.
You must give it arguments to determine this.
If you are proving a universally quantified goal like the above,
call `ghost_calc _ _`.
If the variables are introduced already, call `ghost_calc x y`.
In the unary case, use `ghost_calc _` or `ghost_calc x`.
`ghost_calc` is a light wrapper around type class inference.
All it does is apply the appropriate extensionality lemma and try to infer the resulting goals.
This is subtle and Lean's elaborator doesn't like it because of the HO unification involved,
so it is easier (and prettier) to put it in a tactic script.
-/
meta def ghost_calc (ids' : parse ident_*) : tactic unit :=
do ids ← ids'.mmap $ λ n, get_local n <|> tactic.intro n,
`(@eq (witt_vector _ %%R) _ _) ← target,
match ids with
| [x] := refine ```(is_poly.ext _ _ _ _ %%x)
| [x, y] := refine ```(is_poly₂.ext _ _ _ _ %%x %%y)
| _ := fail "ghost_calc takes one or two arguments"
end,
nm ← match R with
| expr.local_const _ nm _ _ := return nm
| _ := get_unused_name `R
end,
iterate_exactly 2 apply_instance,
unfreezingI (tactic.clear' tt [R]),
introsI $ [nm, nm<.>"_inst"] ++ ids',
skip
end interactive
end tactic
namespace witt_vector
universe u
variables {p : ℕ} {R S : Type u} {σ idx : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S]
local notation `𝕎` := witt_vector p -- type as `\bbW`
open mv_polynomial
open function (uncurry)
include hp
variables (p)
noncomputable theory
/-!
### The `is_poly` predicate
-/
lemma poly_eq_of_witt_polynomial_bind_eq' (f g : ℕ → mv_polynomial (idx × ℕ) ℤ)
(h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) :
f = g :=
begin
ext1 n,
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
rw ← function.funext_iff at h,
replace h := congr_arg
(λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam)
(X_in_terms_of_W p ℚ n)) h,
simpa only [function.comp, map_bind₁, map_witt_polynomial,
← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h
end
lemma poly_eq_of_witt_polynomial_bind_eq (f g : ℕ → mv_polynomial ℕ ℤ)
(h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) :
f = g :=
begin
ext1 n,
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
rw ← function.funext_iff at h,
replace h := congr_arg
(λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam)
(X_in_terms_of_W p ℚ n)) h,
simpa only [function.comp, map_bind₁, map_witt_polynomial,
← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h
end
omit hp
-- Ideally, we would generalise this to n-ary functions
-- But we don't have a good theory of n-ary compositions in mathlib
/--
A function `f : Π R, 𝕎 R → 𝕎 R` that maps Witt vectors to Witt vectors over arbitrary base rings
is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th
coefficient of `f x` is given by evaluating `φₙ` at the coefficients of `x`.
See also `witt_vector.is_poly₂` for the binary variant.
The `ghost_calc` tactic treats `is_poly` as a type class,
and the `@[is_poly]` attribute derives certain specialized composition instances
for declarations of type `is_poly f`.
For the most part, users are not expected to treat `is_poly` as a class.
-/
class is_poly (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R) : Prop :=
mk' :: (poly : ∃ φ : ℕ → mv_polynomial ℕ ℤ, ∀ ⦃R⦄ [comm_ring R] (x : 𝕎 R),
by exactI (f x).coeff = λ n, aeval x.coeff (φ n))
/-- The identity function on Witt vectors is a polynomial function. -/
instance id_is_poly : is_poly p (λ _ _, id) :=
⟨⟨X, by { introsI, simp only [aeval_X, id] }⟩⟩
instance id_is_poly_i' : is_poly p (λ _ _ a, a) :=
witt_vector.id_is_poly _
namespace is_poly
instance : inhabited (is_poly p (λ _ _, id)) :=
⟨witt_vector.id_is_poly p⟩
variables {p}
include hp
lemma ext {f g} (hf : is_poly p f) (hg : is_poly p g)
(h : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R) (n : ℕ),
by exactI ghost_component n (f x) = ghost_component n (g x)) :
∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R), by exactI f x = g x :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
intros,
ext n,
rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq p φ ψ],
intro k,
apply mv_polynomial.funext,
intro x,
simp only [hom_bind₁],
specialize h (ulift ℤ) (mk p $ λ i, ⟨x i⟩) k,
simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h,
apply (ulift.ring_equiv.symm : ℤ ≃+* _).injective,
simp only [←ring_equiv.coe_to_ring_hom, map_eval₂_hom],
convert h using 1,
all_goals
{ funext i,
simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext1,
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
simp only [coeff_mk], refl }
end
omit hp
/-- The composition of polynomial functions is polynomial. -/
lemma comp {g f} (hg : is_poly p g) (hf : is_poly p f) :
is_poly p (λ R _Rcr, @g R _Rcr ∘ @f R _Rcr) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
use (λ n, bind₁ φ (ψ n)),
intros,
simp only [aeval_bind₁, function.comp, hg, hf]
end
end is_poly
/--
A binary function `f : Π R, 𝕎 R → 𝕎 R → 𝕎 R` on Witt vectors
is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th
coefficient of `f x y` is given by evaluating `φₙ` at the coefficients of `x` and `y`.
See also `witt_vector.is_poly` for the unary variant.
The `ghost_calc` tactic treats `is_poly₂` as a type class,
and the `@[is_poly]` attribute derives certain specialized composition instances
for declarations of type `is_poly₂ f`.
For the most part, users are not expected to treat `is_poly₂` as a class.
-/
class is_poly₂ (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R → 𝕎 R) : Prop :=
mk' :: (poly : ∃ φ : ℕ → mv_polynomial (fin 2 × ℕ) ℤ, ∀ ⦃R⦄ [comm_ring R] (x y : 𝕎 R),
by exactI (f x y).coeff = λ n, peval (φ n) ![x.coeff, y.coeff])
variable {p}
/-- The composition of polynomial functions is polynomial. -/
lemma is_poly₂.comp {h f g} (hh : is_poly₂ p h) (hf : is_poly p f) (hg : is_poly p g) :
is_poly₂ p (λ R _Rcr x y, by exactI h (f x) (g y)) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg,
obtain ⟨χ, hh⟩ := hh },
refine ⟨⟨(λ n, bind₁ (uncurry $
![λ k, rename (prod.mk (0 : fin 2)) (φ k),
λ k, rename (prod.mk (1 : fin 2)) (ψ k)]) (χ n)), _⟩⟩,
intros,
funext n,
simp only [peval, aeval_bind₁, function.comp, hh, hf, hg, uncurry],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, n⟩,
fin_cases i;
simp only [aeval_eq_eval₂_hom, eval₂_hom_rename, function.comp, matrix.cons_val_zero,
matrix.head_cons, matrix.cons_val_one],
end
/-- The composition of a polynomial function with a binary polynomial function is polynomial. -/
lemma is_poly.comp₂ {g f} (hg : is_poly p g) (hf : is_poly₂ p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g (f x y)) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
use (λ n, bind₁ φ (ψ n)),
intros,
simp only [peval, aeval_bind₁, function.comp, hg, hf]
end
/-- The diagonal `λ x, f x x` of a polynomial function `f` is polynomial. -/
lemma is_poly₂.diag {f} (hf : is_poly₂ p f) :
is_poly p (λ R _Rcr x, by exactI f x x) :=
begin
unfreezingI {obtain ⟨φ, hf⟩ := hf},
refine ⟨⟨λ n, bind₁ (uncurry ![X, X]) (φ n), _⟩⟩,
intros, funext n,
simp only [hf, peval, uncurry, aeval_bind₁],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, k⟩, fin_cases i;
simp only [matrix.head_cons, aeval_X, matrix.cons_val_zero, matrix.cons_val_one],
end
open tactic
namespace tactic
/-!
### The `@[is_poly]` attribute
This attribute is used to derive specialized composition instances
for `is_poly` and `is_poly₂` declarations.
-/
/--
If `n` is the name of a lemma with opened type `∀ vars, is_poly p _`,
`mk_poly_comp_lemmas n vars p` adds composition instances to the environment
`n.comp_i` and `n.comp₂_i`.
-/
meta def mk_poly_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit :=
do c ← mk_const n,
let appd := vars.foldl expr.app c,
tgt_bod ← to_expr ``(λ f [hf : is_poly %%p f], is_poly.comp %%appd hf) >>=
replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod,
let nm := n <.> "comp_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm,
tgt_bod ← to_expr ``(λ f [hf : is_poly₂ %%p f], is_poly.comp₂ %%appd hf) >>=
replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod,
let nm := n <.> "comp₂_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm
/--
If `n` is the name of a lemma with opened type `∀ vars, is_poly₂ p _`,
`mk_poly₂_comp_lemmas n vars p` adds composition instances to the environment
`n.comp₂_i` and `n.comp_diag`.
-/
meta def mk_poly₂_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit :=
do c ← mk_const n,
let appd := vars.foldl expr.app c,
tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g],
is_poly₂.comp %%appd hf hg) >>= replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify,
let nm := n <.> "comp₂_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm,
tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g],
(is_poly₂.comp %%appd hf hg).diag) >>= replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify,
let nm := n <.> "comp_diag",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm
/--
The `after_set` function for `@[is_poly]`. Calls `mk_poly(₂)_comp_lemmas`.
-/
meta def mk_comp_lemmas (n : name) : tactic unit :=
do d ← get_decl n,
(vars, tp) ← open_pis d.type,
match tp with
| `(is_poly %%p _) := mk_poly_comp_lemmas n vars p
| `(is_poly₂ %%p _) := mk_poly₂_comp_lemmas n vars p
| _ := fail "@[is_poly] should only be applied to terms of type `is_poly _ _` or `is_poly₂ _ _`"
end
/--
`@[is_poly]` is applied to lemmas of the form `is_poly f φ` or `is_poly₂ f φ`.
These lemmas should *not* be tagged as instances, and only atomic `is_poly` defs should be tagged:
composition lemmas should not. Roughly speaking, lemmas that take `is_poly` proofs as arguments
should not be tagged.
Type class inference struggles with function composition, and the higher order unification problems
involved in inferring `is_poly` proofs are complex. The standard style writing these proofs by hand
doesn't work very well. Instead, we construct the type class hierarchy "under the hood", with
limited forms of composition.
Applying `@[is_poly]` to a lemma creates a number of instances. Roughly, if the tagged lemma is a
proof of `is_poly f φ`, the instances added have the form
```lean
∀ g ψ, [is_poly g ψ] → is_poly (f ∘ g) _
```
Since `f` is fixed in this instance, it restricts the HO unification needed when the instance is
applied. Composition lemmas relating `is_poly` with `is_poly₂` are also added.
`id_is_poly` is an atomic instance.
The user-written lemmas are not instances. Users should be able to assemble `is_poly` proofs by hand
"as normal" if the tactic fails.
-/
@[user_attribute] meta def is_poly_attr : user_attribute :=
{ name := `is_poly,
descr := "Lemmas with this attribute describe the polynomial structure of functions",
after_set := some $ λ n _ _, mk_comp_lemmas n }
end tactic
include hp
/-!
### `is_poly` instances
These are not declared as instances at the top level,
but the `@[is_poly]` attribute adds instances based on each one.
Users are expected to use the non-instance versions manually.
-/
/-- The additive negation is a polynomial function on Witt vectors. -/
@[is_poly]
lemma neg_is_poly : is_poly p (λ R _, by exactI @has_neg.neg (𝕎 R) _) :=
⟨⟨λ n, rename prod.snd (witt_neg p n),
begin
introsI, funext n,
rw [neg_coeff, aeval_eq_eval₂_hom, eval₂_hom_rename],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, k⟩, fin_cases i, refl,
end⟩⟩
section zero_one
/- To avoid a theory of 0-ary functions (a.k.a. constants)
we model them as constant unary functions. -/
/-- The function that is constantly zero on Witt vectors is a polynomial function. -/
instance zero_is_poly : is_poly p (λ _ _ _, by exactI 0) :=
⟨⟨0, by { introsI, funext n, simp only [pi.zero_apply, alg_hom.map_zero, zero_coeff] }⟩⟩
@[simp] lemma bind₁_zero_witt_polynomial (n : ℕ) :
bind₁ (0 : ℕ → mv_polynomial ℕ R) (witt_polynomial p R n) = 0 :=
by rw [← aeval_eq_bind₁, aeval_zero, constant_coeff_witt_polynomial, ring_hom.map_zero]
omit hp
/-- The coefficients of `1 : 𝕎 R` as polynomials. -/
def one_poly (n : ℕ) : mv_polynomial ℕ ℤ := if n = 0 then 1 else 0
include hp
@[simp] lemma bind₁_one_poly_witt_polynomial (n : ℕ) :
bind₁ one_poly (witt_polynomial p ℤ n) = 1 :=
begin
rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum, finset.sum_eq_single 0],
{ simp only [one_poly, one_pow, one_mul, alg_hom.map_pow, C_1, pow_zero, bind₁_X_right,
if_true, eq_self_iff_true], },
{ intros i hi hi0,
simp only [one_poly, if_neg hi0, zero_pow (pow_pos hp.1.pos _), mul_zero,
alg_hom.map_pow, bind₁_X_right, alg_hom.map_mul], },
{ rw finset.mem_range, dec_trivial }
end
/-- The function that is constantly one on Witt vectors is a polynomial function. -/
instance one_is_poly : is_poly p (λ _ _ _, by exactI 1) :=
⟨⟨one_poly,
begin
introsI, funext n, cases n,
{ simp only [one_poly, if_true, eq_self_iff_true, one_coeff_zero, alg_hom.map_one], },
{ simp only [one_poly, nat.succ_pos', one_coeff_eq_of_pos,
if_neg n.succ_ne_zero, alg_hom.map_zero] }
end⟩⟩
end zero_one
omit hp
/-- Addition of Witt vectors is a polynomial function. -/
@[is_poly] lemma add_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (+)) :=
⟨⟨witt_add p, by { introsI, dunfold witt_vector.has_add, simp [eval] }⟩⟩
/-- Multiplication of Witt vectors is a polynomial function. -/
@[is_poly] lemma mul_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (*)) :=
⟨⟨witt_mul p, by { introsI, dunfold witt_vector.has_mul, simp [eval] }⟩⟩
include hp
-- unfortunately this is not universe polymorphic, merely because `f` isn't
lemma is_poly.map {f} (hf : is_poly p f) (g : R →+* S) (x : 𝕎 R) :
map g (f x) = f (map g x) :=
begin
-- this could be turned into a tactic “macro” (taking `hf` as parameter)
-- so that applications do not have to worry about the universe issue
-- see `is_poly₂.map` for a slightly more general proof strategy
unfreezingI {obtain ⟨φ, hf⟩ := hf},
ext n,
simp only [map_coeff, hf, map_aeval],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
simp only [map_coeff]
end
namespace is_poly₂
omit hp
instance [fact p.prime] : inhabited (is_poly₂ p _) := ⟨add_is_poly₂⟩
variables {p}
/-- The composition of a binary polynomial function
with a unary polynomial function in the first argument is polynomial. -/
lemma comp_left {g f} (hg : is_poly₂ p g) (hf : is_poly p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g (f x) y) :=
hg.comp hf (witt_vector.id_is_poly _)
/-- The composition of a binary polynomial function
with a unary polynomial function in the second argument is polynomial. -/
lemma comp_right {g f} (hg : is_poly₂ p g) (hf : is_poly p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g x (f y)) :=
hg.comp (witt_vector.id_is_poly p) hf
include hp
lemma ext {f g} (hf : is_poly₂ p f) (hg : is_poly₂ p g)
(h : ∀ (R : Type u) [_Rcr : comm_ring R] (x y : 𝕎 R) (n : ℕ),
by exactI ghost_component n (f x y) = ghost_component n (g x y)) :
∀ (R) [_Rcr : comm_ring R] (x y : 𝕎 R), by exactI f x y = g x y :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
intros,
ext n,
rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq' p φ ψ],
clear x y,
intro k,
apply mv_polynomial.funext,
intro x,
simp only [hom_bind₁],
specialize h (ulift ℤ) (mk p $ λ i, ⟨x (0, i)⟩) (mk p $ λ i, ⟨x (1, i)⟩) k,
simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h,
apply (ulift.ring_equiv.symm : ℤ ≃+* _).injective,
simp only [←ring_equiv.coe_to_ring_hom, map_eval₂_hom],
convert h using 1,
all_goals
{ funext i,
simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext1,
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext ⟨b, _⟩,
fin_cases b; simp only [coeff_mk, uncurry]; refl }
end
-- unfortunately this is not universe polymorphic, merely because `f` isn't
lemma map {f} (hf : is_poly₂ p f) (g : R →+* S) (x y : 𝕎 R) :
map g (f x y) = f (map g x) (map g y) :=
begin
-- this could be turned into a tactic “macro” (taking `hf` as parameter)
-- so that applications do not have to worry about the universe issue
unfreezingI {obtain ⟨φ, hf⟩ := hf},
ext n,
simp only [map_coeff, hf, map_aeval, peval, uncurry],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
try { ext ⟨i, k⟩, fin_cases i },
all_goals
{ simp only [map_coeff, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one] },
end
end is_poly₂
attribute [ghost_simps]
alg_hom.map_zero alg_hom.map_one alg_hom.map_add alg_hom.map_mul
alg_hom.map_sub alg_hom.map_neg alg_hom.id_apply map_nat_cast
ring_hom.map_zero ring_hom.map_one ring_hom.map_mul ring_hom.map_add
ring_hom.map_sub ring_hom.map_neg ring_hom.id_apply
mul_add add_mul add_zero zero_add mul_one one_mul mul_zero zero_mul
nat.succ_ne_zero add_tsub_cancel_right nat.succ_eq_add_one
if_true eq_self_iff_true if_false forall_true_iff forall_2_true_iff forall_3_true_iff
end witt_vector
|
62a7894c1197cc465f3244fdec34a1c1e2116636 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/char_zero.lean | 8990dd50178730bb01dae1f15420af23bc6c1b4b | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 4,828 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.nat.cast_field
import data.fintype.basic
/-!
# Characteristic zero (additional theorems)
A ring `R` is called of characteristic zero if every natural number `n` is non-zero when considered
as an element of `R`. Since this definition doesn't mention the multiplicative structure of `R`
except for the existence of `1` in this file characteristic zero is defined for additive monoids
with `1`.
## Main statements
* Characteristic zero implies that the additive monoid is infinite.
-/
namespace nat
variables {R : Type*} [add_monoid_with_one R] [char_zero R]
/-- `nat.cast` as an embedding into monoids of characteristic `0`. -/
@[simps]
def cast_embedding : ℕ ↪ R := ⟨coe, cast_injective⟩
@[simp] lemma cast_pow_eq_one {R : Type*} [semiring R] [char_zero R] (q : ℕ) (n : ℕ) (hn : n ≠ 0) :
(q : R) ^ n = 1 ↔ q = 1 :=
by { rw [←cast_pow, cast_eq_one], exact pow_eq_one_iff hn }
@[simp, norm_cast]
theorem cast_div_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ}
(n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n :=
begin
rcases eq_or_ne n 0 with rfl | hn,
{ simp },
{ exact cast_div n_dvd (cast_ne_zero.2 hn), },
end
end nat
section
variables (M : Type*) [add_monoid_with_one M] [char_zero M]
@[priority 100] -- see Note [lower instance priority]
instance char_zero.infinite : infinite M :=
infinite.of_injective coe nat.cast_injective
variable {M}
@[field_simps] lemma two_ne_zero' : (2:M) ≠ 0 :=
have ((2:ℕ):M) ≠ 0, from nat.cast_ne_zero.2 dec_trivial,
by rwa [nat.cast_two] at this
end
section
variables {R : Type*} [non_assoc_semiring R] [no_zero_divisors R] [char_zero R]
@[simp]
lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 :=
by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or]
@[simp]
lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero
@[simp]
lemma zero_eq_bit0 {a : R} : 0 = bit0 a ↔ a = 0 :=
by { rw [eq_comm], exact bit0_eq_zero }
end
section
variables {R : Type*} [non_assoc_ring R] [no_zero_divisors R] [char_zero R]
lemma neg_eq_self_iff {a : R} : -a = a ↔ a = 0 :=
neg_eq_iff_add_eq_zero.trans add_self_eq_zero
lemma eq_neg_self_iff {a : R} : a = -a ↔ a = 0 :=
eq_neg_iff_add_eq_zero.trans add_self_eq_zero
lemma nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b :=
begin
rw [←sub_eq_zero, ←mul_sub, mul_eq_zero, sub_eq_zero] at h,
exact_mod_cast h,
end
lemma nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b :=
by simpa [w] using nat_mul_inj h
lemma bit0_injective : function.injective (bit0 : R → R) :=
λ a b h, begin
dsimp [bit0] at h,
simp only [(two_mul a).symm, (two_mul b).symm] at h,
refine nat_mul_inj' _ two_ne_zero,
exact_mod_cast h,
end
lemma bit1_injective : function.injective (bit1 : R → R) :=
λ a b h, begin
simp only [bit1, add_left_inj] at h,
exact bit0_injective h,
end
@[simp] lemma bit0_eq_bit0 {a b : R} : bit0 a = bit0 b ↔ a = b :=
bit0_injective.eq_iff
@[simp] lemma bit1_eq_bit1 {a b : R} : bit1 a = bit1 b ↔ a = b :=
bit1_injective.eq_iff
@[simp]
lemma bit1_eq_one {a : R} : bit1 a = 1 ↔ a = 0 :=
by rw [show (1 : R) = bit1 0, by simp, bit1_eq_bit1]
@[simp]
lemma one_eq_bit1 {a : R} : 1 = bit1 a ↔ a = 0 :=
by { rw [eq_comm], exact bit1_eq_one }
end
section
variables {R : Type*} [division_ring R] [char_zero R]
@[simp] lemma half_add_self (a : R) : (a + a) / 2 = a :=
by rw [← mul_two, mul_div_cancel a two_ne_zero']
@[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a :=
by rw [← add_div, half_add_self]
lemma sub_half (a : R) : a - a / 2 = a / 2 :=
by rw [sub_eq_iff_eq_add, add_halves']
lemma half_sub (a : R) : a / 2 - a = - (a / 2) :=
by rw [← neg_sub, sub_half]
end
namespace with_top
instance {R : Type*} [add_monoid_with_one R] [char_zero R] : char_zero (with_top R) :=
{ cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h }
end with_top
section ring_hom
variables {R S : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
lemma ring_hom.char_zero (ϕ : R →+* S) [hS : char_zero S] : char_zero R :=
⟨λ a b h, char_zero.cast_injective (by rw [←map_nat_cast ϕ, ←map_nat_cast ϕ, h])⟩
lemma ring_hom.char_zero_iff {ϕ : R →+* S} (hϕ : function.injective ϕ) :
char_zero R ↔ char_zero S :=
⟨λ hR, ⟨by introsI a b h; rwa [← @nat.cast_inj R, ← hϕ.eq_iff, map_nat_cast ϕ, map_nat_cast ϕ]⟩,
λ hS, by exactI ϕ.char_zero⟩
lemma ring_hom.injective_nat (f : ℕ →+* R) [char_zero R] :
function.injective f :=
subsingleton.elim (nat.cast_ring_hom _) f ▸ nat.cast_injective
end ring_hom
|
8bdd8b21021cd676fe1e16db00e172315338520b | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /12_Axioms.org.4.lean | 46ed3c56264431f5a05fdf0276ed22bad541cf80 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 356 | lean | import standard
import logic
open eq.ops
namespace hide
-- BEGIN
definition set (X : Type) := X → Prop
namespace set
variable {X : Type}
definition mem [reducible] (x : X) (a : set X) := a x
notation e ∈ a := mem e a
theorem setext {a b : set X} (H : ∀ x, x ∈ a ↔ x ∈ b) : a = b :=
funext (take x, propext (H x))
end set
-- END
end hide
|
a177daaecc6884973d5fedb8bcebfd58d5a1c58c | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/dsimplify1.lean | 754cfac5a4565157d465386da4a6e5db6946a96b | [
"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 | 663 | lean | open tactic
example (f : nat → nat → nat) (p : nat → Prop) (a b : nat) : f ((a + 1, b).1) b = f (a+1) (a, b).2 :=
by do
t ← target,
new_t ← dsimplify (λ e, failed) (λ e, do new_e ← whnf e, return (new_e, tt)) t,
expected ← to_expr ```(f (nat.succ a) b = f (nat.succ a) b),
guard (new_t = expected),
reflexivity
example (f : nat → nat → nat) (p : nat → Prop) (a b : nat) : f ((a + 1, b).1) b = f (a+1) (a, b).2 :=
by do
t ← target,
new_t ← dsimplify (λ e, failed) (λ e, do new_e ← whnf_no_delta e, return (new_e, tt)) t,
expected ← to_expr ```(f (a + 1) b = f (a + 1) b),
guard (new_t = expected),
reflexivity
|
b8c6060228c2eca76b50c01697ef7765a03bdc5a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/print_ax2.lean | efdcf5db5ea12ea7ddb2d5dbd28e377b1c463326 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 26 | lean | open subtype print axioms
|
176e91bd1b198743d06c9680b6283d4caf61d3f0 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/list/indexes.lean | 03cffea6b52a67bcc46c53975ee3874730e7e8f9 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 5,468 | lean | import data.list.basic
import data.list.defs
import logic.basic
universes u v
open function
namespace list
variables {α : Type u} {β : Type v}
section foldr_with_index
/-- Specification of `foldr_with_index_aux`. -/
def foldr_with_index_aux_spec (f : ℕ → α → β → β) (start : ℕ) (b : β)
(as : list α) : β :=
foldr (uncurry f) b $ enum_from start as
theorem foldr_with_index_aux_spec_cons (f : ℕ → α → β → β) (start b a as) :
foldr_with_index_aux_spec f start b (a :: as) =
f start a (foldr_with_index_aux_spec f (start + 1) b as) :=
rfl
theorem foldr_with_index_aux_eq_foldr_with_index_aux_spec (f : ℕ → α → β → β)
(start b as) :
foldr_with_index_aux f start b as = foldr_with_index_aux_spec f start b as :=
begin
induction as generalizing start,
{ refl },
{ simp only [foldr_with_index_aux, foldr_with_index_aux_spec_cons, *] }
end
theorem foldr_with_index_eq_foldr_enum (f : ℕ → α → β → β) (b : β) (as : list α) :
foldr_with_index f b as = foldr (uncurry f) b (enum as) :=
by simp only
[foldr_with_index, foldr_with_index_aux_spec,
foldr_with_index_aux_eq_foldr_with_index_aux_spec, enum]
end foldr_with_index
theorem indexes_values_eq_filter_enum (p : α → Prop) [decidable_pred p]
(as : list α) :
indexes_values p as = filter (p ∘ prod.snd) (enum as) :=
by simp [indexes_values, foldr_with_index_eq_foldr_enum, uncurry, filter_eq_foldr]
theorem find_indexes_eq_map_indexes_values (p : α → Prop) [decidable_pred p]
(as : list α) :
find_indexes p as = map prod.fst (indexes_values p as) :=
by simp only
[indexes_values_eq_filter_enum, map_filter_eq_foldr, find_indexes,
foldr_with_index_eq_foldr_enum, uncurry]
section foldl_with_index
/-- Specification of `foldl_with_index_aux`. -/
def foldl_with_index_aux_spec (f : ℕ → α → β → α) (start : ℕ) (a : α)
(bs : list β) : α :=
foldl (λ a (p : ℕ × β), f p.fst a p.snd) a $ enum_from start bs
theorem foldl_with_index_aux_spec_cons (f : ℕ → α → β → α) (start a b bs) :
foldl_with_index_aux_spec f start a (b :: bs) =
foldl_with_index_aux_spec f (start + 1) (f start a b) bs :=
rfl
theorem foldl_with_index_aux_eq_foldl_with_index_aux_spec (f : ℕ → α → β → α)
(start a bs) :
foldl_with_index_aux f start a bs = foldl_with_index_aux_spec f start a bs :=
begin
induction bs generalizing start a,
{ refl },
{ simp [foldl_with_index_aux, foldl_with_index_aux_spec_cons, *] }
end
theorem foldl_with_index_eq_foldl_enum (f : ℕ → α → β → α) (a : α) (bs : list β) :
foldl_with_index f a bs =
foldl (λ a (p : ℕ × β), f p.fst a p.snd) a (enum bs) :=
by simp only
[foldl_with_index, foldl_with_index_aux_spec,
foldl_with_index_aux_eq_foldl_with_index_aux_spec, enum]
end foldl_with_index
section mfold_with_index
variables {m : Type u → Type v} [monad m]
theorem mfoldr_with_index_eq_mfoldr_enum {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) :
mfoldr_with_index f b as = mfoldr (uncurry f) b (enum as) :=
by simp only
[mfoldr_with_index, mfoldr_eq_foldr, foldr_with_index_eq_foldr_enum, uncurry]
theorem mfoldl_with_index_eq_mfoldl_enum [is_lawful_monad m] {α β}
(f : ℕ → β → α → m β) (b : β) (as : list α) :
mfoldl_with_index f b as =
mfoldl (λ b (p : ℕ × α), f p.fst b p.snd) b (enum as) :=
by rw [mfoldl_with_index, mfoldl_eq_foldl, foldl_with_index_eq_foldl_enum]
end mfold_with_index
section mmap_with_index
variables {m : Type u → Type v} [applicative m]
/-- Specification of `mmap_with_index_aux`. -/
def mmap_with_index_aux_spec {α β} (f : ℕ → α → m β) (start : ℕ) (as : list α) :
m (list β) :=
list.traverse (uncurry f) $ enum_from start as
-- Note: `traverse` the class method would require a less universe-polymorphic
-- `m : Type u → Type u`.
theorem mmap_with_index_aux_spec_cons {α β} (f : ℕ → α → m β) (start : ℕ)
(a : α) (as : list α) :
mmap_with_index_aux_spec f start (a :: as) =
list.cons <$> f start a <*> mmap_with_index_aux_spec f (start + 1) as :=
rfl
theorem mmap_with_index_aux_eq_mmap_with_index_aux_spec {α β} (f : ℕ → α → m β)
(start : ℕ) (as : list α) :
mmap_with_index_aux f start as = mmap_with_index_aux_spec f start as :=
begin
induction as generalizing start,
{ refl },
{ simp [mmap_with_index_aux, mmap_with_index_aux_spec_cons, *] }
end
theorem mmap_with_index_eq_mmap_enum {α β} (f : ℕ → α → m β) (as : list α) :
mmap_with_index f as = list.traverse (uncurry f) (enum as) :=
by simp only
[mmap_with_index, mmap_with_index_aux_spec,
mmap_with_index_aux_eq_mmap_with_index_aux_spec, enum ]
end mmap_with_index
section mmap_with_index'
variables {m : Type u → Type v} [applicative m] [is_lawful_applicative m]
theorem mmap_with_index'_aux_eq_mmap_with_index_aux {α} (f : ℕ → α → m punit)
(start : ℕ) (as : list α) :
mmap_with_index'_aux f start as =
mmap_with_index_aux f start as *> pure punit.star :=
by induction as generalizing start;
simp [mmap_with_index'_aux, mmap_with_index_aux, *, seq_right_eq, const, -comp_const]
with functor_norm
theorem mmap_with_index'_eq_mmap_with_index {α} (f : ℕ → α → m punit) (as : list α) :
mmap_with_index' f as = mmap_with_index f as *> pure punit.star :=
by apply mmap_with_index'_aux_eq_mmap_with_index_aux
end mmap_with_index'
end list
|
87770a805175e6f59238786be473903e9985ea8d | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /test/main/program.lean | 9944581aa5c947efd2b9d38be1a9ac363434a10a | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,607 | lean | import Papyrus
open Papyrus
--------------------------------------------------------------------------------
-- # Helpers
--------------------------------------------------------------------------------
def testOutDir : System.FilePath := "tmp"
def assertBEq [Repr α] [BEq α] (expected actual : α) : IO PUnit := do
unless expected == actual do
throw <| IO.userError s!"expected '{repr expected}', got '{repr actual}'"
def compileAndRunModule (mod : ModuleRef) (fname : String) : IO IO.Process.Output := do
IO.FS.createDirAll testOutDir
let file := testOutDir / fname
let bcFile := file.withExtension "bc" |>.toString
let asmFile := file.withExtension "s" |>.toString
let exeFile := file.withExtension System.FilePath.exeExtension |>.toString
-- Output Bitcode
mod.writeBitcodeToFile bcFile
-- Compile and Run It
let llc ← IO.Process.spawn {
cmd := "llc"
args := #["-o", asmFile, bcFile]
env := #[("LD_PRELOAD","")]
}
let exitCode ← llc.wait
unless exitCode == 0 do
throw <| IO.userError s!"llc exited with error code {exitCode}"
let cc ← IO.Process.spawn {
cmd := "cc"
args := #["-no-pie", "-o", exeFile, asmFile]
}
let exitCode ← cc.wait
unless exitCode == 0 do
throw <| IO.userError s!"cc exited with error code {exitCode}"
IO.Process.output {cmd := exeFile}
--------------------------------------------------------------------------------
-- # Exiting Program
--------------------------------------------------------------------------------
def testSimpleExitingProgram : LlvmM PUnit := do
-- Construct Module
let exitCode := 101
let mod ← ModuleRef.new "exit"
let intTypeRef ← IntegerTypeRef.get 32
let fnTy ← FunctionTypeRef.get intTypeRef #[]
let fn ← FunctionRef.create fnTy "main"
let bb ← BasicBlockRef.create
let const ← intTypeRef.getConstantInt exitCode
let inst ← ReturnInstRef.create const
bb.appendInstruction inst
fn.appendBasicBlock bb
mod.appendFunction fn
-- Verify It
discard mod.verify
-- Run It
let ee ← ExecutionEngineRef.createForModule mod
let ret ← ee.runFunction fn #[]
let exitCode ← ret.toInt
unless exitCode == 101 do
throw <| IO.userError s!"JIT returned exit code {exitCode}"
-- Output It
let out ← compileAndRunModule mod "exit"
unless out.exitCode == 101 do
throw <| IO.userError s!"program exited with code {out.exitCode}"
--------------------------------------------------------------------------------
-- # Hello World Program
--------------------------------------------------------------------------------
def testHelloWorldProgram : LlvmM PUnit := do
-- Construct Module
let mod ← ModuleRef.new "hello"
-- Initialize Hello String Constant
let hello := "Hello World!"
let helloGbl ← GlobalVariableRef.ofString hello
let intTypeRef ← IntegerTypeRef.get 32
let z ← intTypeRef.getConstantNat 0
let helloPtr ← ConstantExprRef.getGetElementPtr helloGbl #[z, z] true
mod.appendGlobalVariable helloGbl
-- Declare `printf` function
let stringTypeRef ← PointerTypeRef.get (← IntegerTypeRef.get 8)
let printfFnTy ← FunctionTypeRef.get intTypeRef #[stringTypeRef] true
let printf ← FunctionRef.create printfFnTy "printf"
mod.appendFunction printf
-- Add Main Function
let mainFnTy ← FunctionTypeRef.get intTypeRef #[]
let main ← FunctionRef.create mainFnTy "main"
mod.appendFunction main
let bb ← BasicBlockRef.create
main.appendBasicBlock bb
let call ← printf.createCall #[helloPtr]
bb.appendInstruction call
let ret ← ReturnInstRef.createUInt32 0
bb.appendInstruction ret
-- Verify, Compile, and Run Module
discard mod.verify
let out ← compileAndRunModule mod "hello"
unless out.exitCode == 0 do
throw <| IO.userError s!"program exited with code {out.exitCode}"
assertBEq hello out.stdout
--------------------------------------------------------------------------------
-- # Runner
--------------------------------------------------------------------------------
def main : IO PUnit := do
if (← initNativeTarget) then
throw <| IO.userError "failed to initialize native target"
if (← initNativeAsmPrinter) then
throw <| IO.userError "failed to initialize native asm printer"
LlvmM.run do
IO.println "Testing exiting program ... "
testSimpleExitingProgram
IO.println "Testing hello world program ... "
testHelloWorldProgram
|
8146d2e29bd45b35425abe36b2ada87ba75244a9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/apply.lean | 38af4fca320ba434982dc32a7d9eb6dcedfaf940 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 7,909 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.core
/-!
This file provides an alternative implementation for `apply` to fix the so-called "apply bug".
The issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition.
For instance, consider the following proof:
```
example {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z :=
begin
apply le_trans,
end
```
Because `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative
definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise,
a different strategy is deployed
-/
namespace tactic
/-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy
`new_g` to rearrange the dependent goals to either drop them, push them to the end of the list
or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/
def reorder_goals {α} (gs : list (bool × α)) : new_goals → list α
| new_goals.non_dep_first :=
let ⟨dep,non_dep⟩ := gs.partition (coe ∘ prod.fst) in
non_dep.map prod.snd ++ dep.map prod.snd
| new_goals.non_dep_only := (gs.filter (coe ∘ bnot ∘ prod.fst)).map prod.snd
| new_goals.all := gs.map prod.snd
private meta def has_opt_auto_param_inst_for_apply (ms : list (name × expr)) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m.2,
b ← is_class type,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b)
ff
private meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg)
(ms : list (name × expr)) : tactic unit :=
mwhen (has_opt_auto_param_inst_for_apply ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
try apply_instance >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
private meta def retry_apply_aux :
Π (e : expr) (cfg : apply_cfg), list (bool × name × expr) → tactic (list (name × expr))
| e cfg gs :=
focus1 (do {
tgt : expr ← target, t ← infer_type e,
unify t tgt,
exact e,
gs' ← get_goals,
let r := reorder_goals gs.reverse cfg.new_goals,
set_goals (gs' ++ r.map prod.snd),
return r }) <|>
do (expr.pi n bi d b) ← infer_type e >>= whnf | apply_core e cfg,
v ← mk_meta_var d,
let b := b.has_var,
e ← head_beta $ e v,
retry_apply_aux e cfg ((b, n, v) :: gs)
private meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name × expr)) :=
apply_core e cfg <|> retry_apply_aux e cfg []
/-- `apply'` mimics the behavior of `apply_core`. When
`apply_core` fails, it is retried by providing the term with meta
variables as additional arguments. The meta variables can then
become new goals depending on the `cfg.new_goals` policy.
`apply'` also finds instances and applies opt_params and auto_params. -/
meta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
do r ← retry_apply e cfg,
try_apply_opt_auto_param_instance_for_apply cfg r,
return r
/-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/
meta def fapply' (e : expr) : tactic (list (name × expr)) :=
apply' e {new_goals := new_goals.all}
/-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/
meta def eapply' (e : expr) : tactic (list (name × expr)) :=
apply' e {new_goals := new_goals.non_dep_only}
/-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'`
to make one proof step. -/
private meta def relation_tactic (md : transparency) (op_for : environment → name → option name)
(tac_name : string) : tactic unit :=
do tgt ← target >>= instantiate_mvars,
env ← get_env,
let r := expr.get_app_fn tgt,
match op_for env (expr.const_name r) with
| (some refl) := do r ← mk_const refl,
retry_apply r {md := md, new_goals := new_goals.non_dep_only },
return ()
| none := fail $ tac_name ++
" tactic failed, target is not a relation application with the expected property."
end
/-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/
meta def reflexivity' (md := semireducible) : tactic unit :=
relation_tactic md environment.refl_for "reflexivity"
/-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/
meta def symmetry' (md := semireducible) : tactic unit :=
relation_tactic md environment.symm_for "symmetry"
/-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/
meta def transitivity' (md := semireducible) : tactic unit :=
relation_tactic md environment.trans_for "transitivity"
namespace interactive
setup_tactic_parser
/--
Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion
of the type of term.
It differs from `apply` in that it does not unfold definition in order to find out what the
assumptions of the provided term is. It is especially useful when defining relations on function
spaces (e.g. `≤`) so that rules like transitivity on `le : (α → β) → (α → β) → (α → β)` will be
considered to have three parameters and two assumptions (i.e. `f g h : α → β`, `H₀ : f ≤ g`,
`H₁ : g ≤ h`) instead of three parameters, two assumptions and then one more parameter
(i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`, `x : α`). Whereas `apply` would expect the goal
`f x ≤ h x`, `apply'` will work with the goal `f ≤ h`.
-/
meta def apply' (q : parse texpr) : tactic unit :=
concat_tags (do h ← i_to_expr_for_apply q, tactic.apply' h)
/--
Similar to the `apply'` tactic, but does not reorder goals.
-/
meta def fapply' (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.fapply')
/--
Similar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not
been fixed by type inference or type class resolution.
-/
meta def eapply' (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.eapply')
/--
Similar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object.
-/
meta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e cfg)
/--
Similar to the `apply'` tactic, but uses matching instead of unification.
`mapply' t` is equivalent to `apply_with' t {unify := ff}`
-/
meta def mapply' (q : parse texpr) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e {unify := ff})
/--
Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`.
-/
meta def reflexivity' : tactic unit :=
tactic.reflexivity'
/--
Shorter name for the tactic `reflexivity'`.
-/
meta def refl' : tactic unit :=
tactic.reflexivity'
/--
`symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry
to assumption `h`
-/
meta def symmetry' : parse location → tactic unit
| l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry'
| (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry'
/--
Similar to `transitivity` with the difference that `apply'` is used instead of `apply`.
-/
meta def transitivity' (q : parse texpr?) : tactic unit :=
tactic.transitivity' >> match q with
| none := skip
| some q :=
do (r, lhs, rhs) ← target_lhs_rhs,
t ← infer_type lhs,
i_to_expr ``(%%q : %%t) >>= unify rhs
end
end interactive
end tactic
|
8f68d4c96dc74112e82365c73987120d254dbcf5 | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /Papyrus/IR/ConstantRef.lean | 30d9b7a6b80d6c36ae25fda52e824dac34ddb43b | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 275 | lean | import Papyrus.Context
import Papyrus.IR.ValueRef
namespace Papyrus
/--
A reference to an external LLVM
[Constant](https://llvm.org/doxygen/classllvm_1_1Constant.html).
-/
structure ConstantRef extends UserRef
instance : Coe ConstantRef UserRef := ⟨(·.toUserRef)⟩
|
3b7f73ece73da3aed39d069df2c95bdd610a0946 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/continued_fractions/computation/correctness_terminating.lean | 611c392ff48d849ab7e6490f89c5eb7026be5b01 | [] | 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 | 6,282 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.continued_fractions.computation.translations
import Mathlib.algebra.continued_fractions.terminated_stable
import Mathlib.algebra.continued_fractions.continuants_recurrence
import Mathlib.order.filter.at_top_bot
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Correctness of Terminating Continued Fraction Computations (`gcf.of`)
## Summary
Let us write `gcf` for `generalized_continued_fraction`. We show the correctness of the
algorithm computing continued fractions (`gcf.of`) in case of termination in the following sense:
At every step `n : ℕ`, we can obtain the value `v` by adding a specific residual term to the last
denominator of the fraction described by `(gcf.of v).convergents' n`. The residual term will be zero
exactly when the continued fraction terminated; otherwise, the residual term will be given by the
fractional part stored in `gcf.int_fract_pair.stream v n`.
For an example, refer to `gcf.comp_exact_value_correctness_of_stream_eq_some` and for more
information about the computation process, refer to `algebra.continued_fraction.computation.basic`.
## Main definitions
- `gcf.comp_exact_value` can be used to compute the exact value approximated by the continued
fraction `gcf.of v` by adding a residual term as described in the summary.
## Main Theorems
- `gcf.comp_exact_value_correctness_of_stream_eq_some` shows that `gcf.comp_exact_value` indeed
returns the value `v` when given the convergent and fractional part as described in the summary.
- `gcf.of_correctness_of_terminated_at` shows the equality `v = (gcf.of v).convergents n`
if `gcf.of v` terminated at position `n`.
-/
namespace generalized_continued_fraction
/--
Given two continuants `pconts` and `conts` and a value `fr`, this function returns
- `conts.a / conts.b` if `fr = 0`
- `exact_conts.a / exact_conts.b` where `exact_conts = next_continuants 1 fr⁻¹ pconts conts` otherwise.
This function can be used to compute the exact value approxmated by a continued fraction `gcf.of v`
as described in lemma `comp_exact_value_correctness_of_stream_eq_some`.
-/
-- if the fractional part is zero, we exactly approximated the value by the last continuants
protected def comp_exact_value {K : Type u_1} [linear_ordered_field K] (pconts : pair K) (conts : pair K) (fr : K) : K :=
ite (fr = 0) (pair.a conts / pair.b conts)
(let exact_conts : pair K := next_continuants 1 (fr⁻¹) pconts conts;
pair.a exact_conts / pair.b exact_conts)
-- otherwise, we have to include the fractional part in a final continuants step.
/-- Just a computational lemma we need for the next main proof. -/
protected theorem comp_exact_value_correctness_of_stream_eq_some_aux_comp {K : Type u_1} [linear_ordered_field K] [floor_ring K] {a : K} (b : K) (c : K) (fract_a_ne_zero : fract a ≠ 0) : (↑(floor a) * b + c) / fract a + b = (b * a + c) / fract a := sorry
/--
Shows the correctness of `comp_exact_value` in case the continued fraction `gcf.of v` did not
terminate at position `n`. That is, we obtain the value `v` if we pass the two successive
(auxiliary) continuants at positions `n` and `n + 1` as well as the fractional part at
`int_fract_pair.stream n` to `comp_exact_value`.
The correctness might be seen more readily if one uses `convergents'` to evaluate the continued
fraction. Here is an example to illustrate the idea:
Let `(v : ℚ) := 3.4`. We have
- `gcf.int_fract_pair.stream v 0 = some ⟨3, 0.4⟩`, and
- `gcf.int_fract_pair.stream v 1 = some ⟨2, 0.5⟩`.
Now `(gcf.of v).convergents' 1 = 3 + 1/2`, and our fractional term at position `2` is `0.5`. We hence
have `v = 3 + 1/(2 + 0.5) = 3 + 1/2.5 = 3.4`. This computation corresponds exactly to the one using
the recurrence equation in `comp_exact_value`.
-/
theorem comp_exact_value_correctness_of_stream_eq_some {K : Type u_1} [linear_ordered_field K] {v : K} {n : ℕ} [floor_ring K] {ifp_n : int_fract_pair K} : int_fract_pair.stream v n = some ifp_n →
v =
generalized_continued_fraction.comp_exact_value (continuants_aux (generalized_continued_fraction.of v) n)
(continuants_aux (generalized_continued_fraction.of v) (n + 1)) (int_fract_pair.fr ifp_n) := sorry
/-- The convergent of `gcf.of v` at step `n - 1` is exactly `v` if the `int_fract_pair.stream` of
the corresponding continued fraction terminated at step `n`. -/
theorem of_correctness_of_nth_stream_eq_none {K : Type u_1} [linear_ordered_field K] {v : K} {n : ℕ} [floor_ring K] (nth_stream_eq_none : int_fract_pair.stream v n = none) : v = convergents (generalized_continued_fraction.of v) (n - 1) := sorry
/-- If `gcf.of v` terminated at step `n`, then the `n`th convergent is exactly `v`. -/
theorem of_correctness_of_terminated_at {K : Type u_1} [linear_ordered_field K] {v : K} {n : ℕ} [floor_ring K] (terminated_at_n : terminated_at (generalized_continued_fraction.of v) n) : v = convergents (generalized_continued_fraction.of v) n :=
(fun (this : int_fract_pair.stream v (n + 1) = none) => of_correctness_of_nth_stream_eq_none this)
(iff.elim_left of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none terminated_at_n)
/-- If `gcf.of v` terminates, then there is `n : ℕ` such that the `n`th convergent is exactly `v`. -/
theorem of_correctness_of_terminates {K : Type u_1} [linear_ordered_field K] {v : K} [floor_ring K] (terminates : terminates (generalized_continued_fraction.of v)) : ∃ (n : ℕ), v = convergents (generalized_continued_fraction.of v) n :=
exists.elim terminates
fun (n : ℕ) (terminated_at_n : seq.terminated_at (s (generalized_continued_fraction.of v)) n) =>
exists.intro n (of_correctness_of_terminated_at terminated_at_n)
/-- If `gcf.of v` terminates, then its convergents will eventually always be `v`. -/
theorem of_correctness_at_top_of_terminates {K : Type u_1} [linear_ordered_field K] {v : K} [floor_ring K] (terminates : terminates (generalized_continued_fraction.of v)) : filter.eventually (fun (n : ℕ) => v = convergents (generalized_continued_fraction.of v) n) filter.at_top := sorry
|
c1fcfd061a263588ee7035c0ad49875ad7e0606d | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Meta/AbstractMVars.lean | cab8dd8a2a786f5a7be80100f162ea4e74e5a6a3 | [
"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 | 6,000 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Meta.Basic
namespace Lean
namespace Meta
structure AbstractMVarsResult :=
(paramNames : Array Name)
(numMVars : Nat)
(expr : Expr)
instance AbstractMVarsResult.inhabited : Inhabited AbstractMVarsResult := ⟨⟨#[], 0, arbitrary _⟩⟩
def AbstractMVarsResult.beq (r₁ r₂ : AbstractMVarsResult) : Bool :=
r₁.paramNames == r₂.paramNames && r₁.numMVars == r₂.numMVars && r₁.expr == r₂.expr
instance AbstractMVarsResult.hasBeq : HasBeq AbstractMVarsResult := ⟨AbstractMVarsResult.beq⟩
namespace AbstractMVars
structure State :=
(ngen : NameGenerator)
(lctx : LocalContext)
(nextParamIdx : Nat := 0)
(paramNames : Array Name := #[])
(fvars : Array Expr := #[])
(lmap : HashMap Name Level := {})
(emap : HashMap Name Expr := {})
abbrev M := ReaderT MetavarContext (StateM State)
def mkFreshId : M Name := do
s ← get;
let fresh := s.ngen.curr;
modify $ fun s => { ngen := s.ngen.next, .. s };
pure fresh
@[inline] private def visitLevel (f : Level → M Level) (u : Level) : M Level :=
if !u.hasMVar then pure u
else f u
@[inline] private def visitExpr (f : Expr → M Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e
else f e
private partial def abstractLevelMVars : Level → M Level
| u@(Level.zero _) => pure u
| u@(Level.param _ _) => pure u
| u@(Level.succ v _) => do v ← visitLevel abstractLevelMVars v; pure $ u.updateSucc v rfl
| u@(Level.max v w _) => do v ← visitLevel abstractLevelMVars v; w ← visitLevel abstractLevelMVars w; pure $ u.updateMax v w rfl
| u@(Level.imax v w _) => do v ← visitLevel abstractLevelMVars v; w ← visitLevel abstractLevelMVars w; pure $ u.updateIMax v w rfl
| u@(Level.mvar mvarId _) => do
mctx ← read;
let depth := mctx.getLevelDepth mvarId;
if depth != mctx.depth then pure u -- metavariables from lower depths are treated as constants
else do
s ← get;
match s.lmap.find? mvarId with
| some u => pure u
| none => do
let paramId := mkNameNum `_abstMVar s.nextParamIdx;
let u := mkLevelParam paramId;
modify $ fun s => { nextParamIdx := s.nextParamIdx + 1, lmap := s.lmap.insert mvarId u, paramNames := s.paramNames.push paramId, .. s };
pure u
partial def abstractExprMVars : Expr → M Expr
| e@(Expr.lit _ _) => pure e
| e@(Expr.bvar _ _) => pure e
| e@(Expr.fvar _ _) => pure e
| e@(Expr.sort u _) => do u ← visitLevel abstractLevelMVars u; pure $ e.updateSort u rfl
| e@(Expr.const _ us _) => do us ← us.mapM (visitLevel abstractLevelMVars); pure $ e.updateConst us rfl
| e@(Expr.proj _ _ s _) => do s ← visitExpr abstractExprMVars s; pure $ e.updateProj s rfl
| e@(Expr.app f a _) => do f ← visitExpr abstractExprMVars f; a ← visitExpr abstractExprMVars a; pure $ e.updateApp f a rfl
| e@(Expr.mdata _ b _) => do b ← visitExpr abstractExprMVars b; pure $ e.updateMData b rfl
| e@(Expr.lam _ d b _) => do d ← visitExpr abstractExprMVars d; b ← visitExpr abstractExprMVars b; pure $ e.updateLambdaE! d b
| e@(Expr.forallE _ d b _) => do d ← visitExpr abstractExprMVars d; b ← visitExpr abstractExprMVars b; pure $ e.updateForallE! d b
| e@(Expr.letE _ t v b _) => do t ← visitExpr abstractExprMVars t; v ← visitExpr abstractExprMVars v; b ← visitExpr abstractExprMVars b; pure $ e.updateLet t v b rfl
| e@(Expr.mvar mvarId _) => do
mctx ← read;
let decl := mctx.getDecl mvarId;
if decl.depth != mctx.depth then pure e -- metavariables from lower depths are treated as constants
else do
s ← get;
match s.emap.find? mvarId with
| some e => pure e
| none => do
type ← visitExpr abstractExprMVars decl.type;
fvarId ← mkFreshId;
let fvar := mkFVar fvarId;
let userName := if decl.userName.isAnonymous then (`x).appendIndexAfter s.fvars.size else decl.userName;
modify $ fun s => {
emap := s.emap.insert mvarId fvar,
fvars := s.fvars.push fvar,
lctx := s.lctx.mkLocalDecl fvarId userName type,
.. s };
pure fvar
| Expr.localE _ _ _ _ => unreachable!
end AbstractMVars
/--
Abstract (current depth) metavariables occurring in `e`.
The result contains
- An array of universe level parameters that replaced universe metavariables occurring in `e`.
- The number of (expr) metavariables abstracted.
- And an expression of the form `fun (m_1 : A_1) ... (m_k : A_k) => e'`, where
`k` equal to the number of (expr) metavariables abstracted, and `e'` is `e` after we
replace the metavariables.
Example: given `f.{?u} ?m1` where `?m1 : ?m2 Nat`, `?m2 : Type -> Type`. This function returns
`{ levels := #[u], size := 2, expr := (fun (m2 : Type -> Type) (m1 : m2 Nat) => f.{u} m1) }`
This API can be used to "transport" to a different metavariable context.
Given a new metavariable context, we replace the `AbstractMVarsResult.levels` with
new fresh universe metavariables, and instantiate the `(m_i : A_i)` in the lambda-expression
with new fresh metavariables.
Application: we use this method to cache the results of type class resolution. -/
def abstractMVars (e : Expr) : MetaM AbstractMVarsResult := do
e ← instantiateMVars e;
s ← get;
lctx ← getLCtx;
let (e, s) := AbstractMVars.abstractExprMVars e s.mctx { lctx := lctx, ngen := s.ngen };
modify $ fun s => { ngen := s.ngen, .. s };
let e := s.lctx.mkLambda s.fvars e;
pure { paramNames := s.paramNames, numMVars := s.fvars.size, expr := e }
def openAbstractMVarsResult (a : AbstractMVarsResult) : MetaM (Array Expr × Array BinderInfo × Expr) := do
us ← a.paramNames.mapM $ fun _ => mkFreshLevelMVar;
let e := a.expr.instantiateLevelParamsArray a.paramNames us;
lambdaMetaTelescope e (some a.numMVars)
end Meta
end Lean
|
99fcbd079a1f95898715041d0f1003f89d9ecc7c | 59a4b050600ed7b3d5826a8478db0a9bdc190252 | /src/category_theory/adjunctions/examples/fixed_points.lean | 0e16f5cbba64d577df14a278c5f3b6d30d00d0f6 | [] | no_license | rwbarton/lean-category-theory | f720268d800b62a25d69842ca7b5d27822f00652 | 00df814d463406b7a13a56f5dcda67758ba1b419 | refs/heads/master | 1,585,366,296,767 | 1,536,151,349,000 | 1,536,151,349,000 | 147,652,096 | 0 | 0 | null | 1,536,226,960,000 | 1,536,226,960,000 | null | UTF-8 | Lean | false | false | 937 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.adjunctions
import category_theory.full_subcategory
open category_theory
namespace category_theory.adjunctions
universe u
variable {C : Type (u+1)}
variable [large_category C]
variable {D : Type (u+1)}
variable [large_category D]
-- EXERCISE
-- cf Leinster 2.2.11
def left_fixed_points {L : C ⥤ D} {R : D ⥤ C} (A : Adjunction L R) : large_category (Σ X : C, is_iso (A.unit X)) := by apply_instance
def right_fixed_points {L : C ⥤ D} {R : D ⥤ C} (A : Adjunction L R) : large_category (Σ X : D, is_iso (A.counit X)) := by apply_instance
-- Now we need to express the idea that functors restrict to a full subcategory with image in another full subcategory,
-- and that these restrictions give an equivalence.
end category_theory.adjunctions |
cfe38076fbe7fceb522f0073c49d63499e8d96f3 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/real/irrational.lean | 790864790d39c30f3a488d90206c5b13273b5677 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 8,457 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov.
-/
import data.real.basic
import data.rat.sqrt
import algebra.gcd_monoid
import ring_theory.multiplicity
/-!
# Irrational real numbers
In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer
number is irrational if it is not integer, and that `sqrt q` is irrational if and only if
`rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`.
We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc.
-/
open rat real multiplicity
/-- A real number is irrational if it is not equal to any rational number. -/
def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ)
lemma irrational_iff_ne_rational (x : ℝ) : irrational x ↔ ∀ a b : ℤ, x ≠ a / b :=
by simp only [irrational, rat.forall, cast_mk, not_exists, set.mem_range, cast_coe_int, cast_div,
eq_comm]
/-!
### Irrationality of roots of integer and rational numbers
-/
/-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then
`x` is irrational. -/
theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ)
(hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) :
irrational x :=
begin
rintros ⟨⟨N, D, P, C⟩, rfl⟩,
rw [← cast_pow] at hxr,
have c1 : ((D : ℤ) : ℝ) ≠ 0,
{ rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P },
have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1,
rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2,
← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr,
have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr,
rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow,
nat.pow_dvd_pow_iff hnpos] at hdivn,
have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one],
subst D,
refine hv ⟨N, _⟩,
rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int]
end
/-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x`
is irrational. -/
theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ)
[hp : fact p.prime] (hxr : x ^ n = m)
(hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, hm⟩) % n ≠ 0) :
irrational x :=
begin
rcases nat.eq_zero_or_pos n with rfl | hnpos,
{ rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr,
simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1
(mt int.coe_nat_dvd.1 hp.not_dvd_one)), nat.zero_mod] using hv },
refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos,
rintro ⟨y, rfl⟩,
rw [← int.cast_pow, int.cast_inj] at hxr, subst m,
have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl },
erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp)
(finite_int_iff.2 ⟨hp.ne_one, this⟩), nat.mul_mod_right] at hv,
exact hv rfl
end
theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m)
(p : ℕ) [hp : fact p.prime]
(Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) :
irrational (sqrt m) :=
@irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp
(sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm))
(by rw Hpv; exact one_ne_zero)
theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) :=
@irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p hp $
by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)];
refl
theorem irrational_sqrt_two : irrational (sqrt 2) :=
by simpa using nat.prime_two.irrational_sqrt
theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔
rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q :=
if H1 : rat.sqrt q * rat.sqrt q = q
then iff_of_false (not_not_intro ⟨rat.sqrt q,
by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q),
sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1)
else if H2 : 0 ≤ q
then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r,
by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, cast_inj] at hr;
rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩
else iff_of_false (not_not_intro ⟨0,
by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩)
(λ h, H2 h.2)
instance (q : ℚ) : decidable (irrational (sqrt q)) :=
decidable_of_iff' _ (irrational_sqrt_rat_iff q)
/-!
### Adding/subtracting/multiplying by rational numbers
-/
lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩
namespace irrational
variables (q : ℚ) {x y : ℝ}
open_locale classical
theorem add_cases : irrational (x + y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx + ry, cast_add rx ry⟩
end
theorem of_rat_add (h : irrational (q + x)) : irrational x :=
h.add_cases.elim (λ h, absurd h q.not_irrational) id
theorem rat_add (h : irrational x) : irrational (q + x) :=
of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left]
theorem of_add_rat : irrational (x + q) → irrational x :=
add_comm ↑q x ▸ of_rat_add q
theorem add_rat (h : irrational x) : irrational (x + q) :=
add_comm ↑q x ▸ h.rat_add q
theorem of_neg (h : irrational (-x)) : irrational x :=
λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩
protected theorem neg (h : irrational x) : irrational (-x) :=
of_neg $ by rwa neg_neg
theorem sub_rat (h : irrational x) : irrational (x - q) :=
by simpa only [cast_neg] using h.add_rat (-q)
theorem rat_sub (h : irrational x) : irrational (q - x) :=
h.neg.rat_add q
theorem of_sub_rat (h : irrational (x - q)) : irrational x :=
of_add_rat (-q) $ by simpa only [cast_neg]
theorem of_rat_sub (h : irrational (q - x)) : irrational x :=
(h.of_rat_add _).of_neg
theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx * ry, cast_mul rx ry⟩
end
theorem of_mul_rat (h : irrational (x * q)) : irrational x :=
h.mul_cases.elim id (λ h, absurd h q.not_irrational)
theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) :=
of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one]
theorem of_rat_mul : irrational (q * x) → irrational x :=
mul_comm x q ▸ of_mul_rat q
theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) :=
mul_comm x q ▸ h.mul_rat hq
theorem of_mul_self (h : irrational (x * x)) : irrational x :=
h.mul_cases.elim id id
theorem of_inv (h : irrational x⁻¹) : irrational x :=
λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩
protected theorem inv (h : irrational x) : irrational x⁻¹ :=
of_inv $ by rwa inv_inv'
theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y :=
h.mul_cases.imp id of_inv
theorem of_rat_div (h : irrational (q / x)) : irrational x :=
(h.of_rat_mul q).of_inv
theorem of_one_div (h : irrational (1 / x)) : irrational x :=
of_rat_div 1 $ by rwa [cast_one]
theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x
| 0 := λ h, (h ⟨1, cast_one⟩).elim
| (n+1) := λ h, h.mul_cases.elim id (of_pow n)
theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x
| (n:ℕ) := of_pow n
| -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ }
end irrational
section
variables {q : ℚ} {x : ℝ}
open irrational
@[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x :=
⟨of_rat_add q, rat_add q⟩
@[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x :=
⟨of_add_rat q, add_rat q⟩
@[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x :=
⟨of_rat_sub q, rat_sub q⟩
@[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x :=
⟨of_sub_rat q, sub_rat q⟩
@[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x :=
⟨of_neg, irrational.neg⟩
@[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x :=
⟨of_inv, irrational.inv⟩
end
|
cd302dad2bf4135b48d906111e648afacf97ddeb | b561a44b48979a98df50ade0789a21c79ee31288 | /stage0/src/Lean/Elab/Term.lean | e97ad934a0ca93d0f4ce420873c041e74d2fbe5e | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 70,631 | 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.ResolveName
import Lean.Util.Sorry
import Lean.Util.ReplaceExpr
import Lean.Structure
import Lean.Meta.ExprDefEq
import Lean.Meta.AppBuilder
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Coe
import Lean.Meta.Tactic.Util
import Lean.Hygiene
import Lean.Util.RecDepth
import Lean.Elab.Log
import Lean.Elab.Level
import Lean.Elab.Attributes
import Lean.Elab.AutoBound
import Lean.Elab.InfoTree
import Lean.Elab.Open
import Lean.Elab.SetOption
namespace Lean.Elab.Term
/-
Set isDefEq configuration for the elaborator.
Note that we enable all approximations but `quasiPatternApprox`
In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.
The example:
```
def ex : StateT δ (StateT σ Id) σ :=
monadLift (get : StateT σ Id σ)
```
demonstrates why it produces counterintuitive behavior.
We have the `Monad-lift` application:
```
@monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α
```
It produces the following unification problem when we process the expected type:
```
?n ?α =?= StateT δ (StateT σ id) σ
==> (approximate using first-order unification)
?n := StateT δ (StateT σ id)
?α := σ
```
Then, we need to solve:
```
?m ?α =?= StateT σ id σ
==> instantiate metavars
?m σ =?= StateT σ id σ
==> (approximate since it is a quasi-pattern unification constraint)
?m := fun σ => StateT σ id σ
```
Note that the constraint is not a Milner pattern because σ is in
the local context of `?m`. We are ignoring the other possible solutions:
```
?m := fun σ' => StateT σ id σ
?m := fun σ' => StateT σ' id σ
?m := fun σ' => StateT σ id σ'
```
We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).
If we had use first-order unification, then we would have produced
the right answer: `?m := StateT σ id`
Haskell would work on this example since it always uses
first-order unification.
-/
def setElabConfig (cfg : Meta.Config) : Meta.Config :=
{ cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }
structure Context where
fileName : String
fileMap : FileMap
declName? : Option Name := none
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
/- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.
The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in
the list of pending synthetic metavariables, and returns `?m`. -/
mayPostpone : Bool := true
/- When `errToSorry` is set to true, the method `elabTerm` catches
exceptions and converts them into synthetic `sorry`s.
The implementation of choice nodes and overloaded symbols rely on the fact
that when `errToSorry` is set to false for an elaboration function `F`, then
`errToSorry` remains `false` for all elaboration functions invoked by `F`.
That is, it is safe to transition `errToSorry` from `true` to `false`, but
we must not set `errToSorry` to `true` when it is currently set to `false`. -/
errToSorry : Bool := true
/- When `autoBoundImplicit` is set to true, instead of producing
an "unknown identifier" error for unbound variables, we generate an
internal exception. This exception is caught at `elabBinders` and
`elabTypeWithUnboldImplicit`. Both methods add implicit declarations
for the unbound variable and try again. -/
autoBoundImplicit : Bool := false
autoBoundImplicits : Std.PArray Expr := {}
/-- Map from user name to internal unique name -/
sectionVars : NameMap Name := {}
/-- Map from internal name to fvar -/
sectionFVars : NameMap Expr := {}
/-- Enable/disable implicit lambdas feature. -/
implicitLambda : Bool := true
/-- Saved context for postponed terms and tactics to be executed. -/
structure SavedContext where
declName? : Option Name
options : Options
openDecls : List OpenDecl
macroStack : MacroStack
errToSorry : Bool
/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/
inductive SyntheticMVarKind where
-- typeclass instance search
| typeClass
/- Similar to typeClass, but error messages are different.
if `f?` is `some f`, we produce an application type mismatch error message.
Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)`
Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/
| coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)
-- tactic block execution
| tactic (tacticCode : Syntax) (ctx : SavedContext)
-- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)
| postponed (ctx : SavedContext)
instance : ToString SyntheticMVarKind where
toString
| SyntheticMVarKind.typeClass => "typeclass"
| SyntheticMVarKind.coe .. => "coe"
| SyntheticMVarKind.tactic .. => "tactic"
| SyntheticMVarKind.postponed .. => "postponed"
structure SyntheticMVarDecl where
mvarId : MVarId
stx : Syntax
kind : SyntheticMVarKind
inductive MVarErrorKind where
| implicitArg (ctx : Expr)
| hole
| custom (msgData : MessageData)
instance : ToString MVarErrorKind where
toString
| MVarErrorKind.implicitArg ctx => "implicitArg"
| MVarErrorKind.hole => "hole"
| MVarErrorKind.custom msg => "custom"
structure MVarErrorInfo where
mvarId : MVarId
ref : Syntax
kind : MVarErrorKind
structure LetRecToLift where
ref : Syntax
fvarId : FVarId
attrs : Array Attribute
shortDeclName : Name
declName : Name
lctx : LocalContext
localInstances : LocalInstances
type : Expr
val : Expr
mvarId : MVarId
structure State where
levelNames : List Name := []
syntheticMVars : List SyntheticMVarDecl := []
mvarErrorInfos : List MVarErrorInfo := []
messages : MessageLog := {}
letRecsToLift : List LetRecToLift := []
infoState : InfoState := {}
deriving Inhabited
abbrev TermElabM := ReaderT Context $ StateRefT State MetaM
abbrev TermElab := Syntax → Option Expr → TermElabM Expr
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind }
open Meta
instance : Inhabited (TermElabM α) where
default := throw arbitrary
structure SavedState where
meta : Meta.SavedState
«elab» : State
deriving Inhabited
protected def saveState : TermElabM SavedState := do
pure { meta := (← Meta.saveState), «elab» := (← get) }
def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do
let traceState ← getTraceState -- We never backtrack trace message
let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`
s.meta.restore
set s.elab
setTraceState traceState
unless restoreInfo do
modify fun s => { s with infoState := infoState }
instance : MonadBacktrack SavedState TermElabM where
saveState := Term.saveState
restoreState b := b.restore
abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α
instance [Inhabited α] : Inhabited (TermElabResult α) where
default := EStateM.Result.ok arbitrary arbitrary
def setMessageLog (messages : MessageLog) : TermElabM Unit :=
modify fun s => { s with messages := messages }
def resetMessageLog : TermElabM Unit :=
setMessageLog {}
def getMessageLog : TermElabM MessageLog :=
return (← get).messages
/--
Execute `x`, save resulting expression and new state.
We remove any `Info` created by `x`.
The info nodes are committed when we execute `applyResult`.
We use `observing` to implement overloaded notation and decls.
We want to save `Info` nodes for the chosen alternative.
-/
def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do
let s ← saveState
try
let e ← x
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.ok e sNew)
catch
| ex@(Exception.error _ _) =>
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.error ex sNew)
| ex@(Exception.internal id _) =>
if id == postponeExceptionId then
s.restore (restoreInfo := true)
throw ex
/--
Apply the result/exception and state captured with `observing`.
We use this method to implement overloaded notation and symbols. -/
def applyResult (result : TermElabResult α) : TermElabM α :=
match result with
| EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a
| EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex
/--
Execute `x`, but keep state modifications only if `x` did not postpone.
This method is useful to implement elaboration functions that cannot decide whether
they need to postpone or not without updating the state. -/
def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do
-- We just reuse the implementation of `observing` and `applyResult`.
let r ← observing x
applyResult r
def getLevelNames : TermElabM (List Name) :=
return (← get).levelNames
def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do
match (← getLCtx).find? fvar.fvarId! with
| some d => pure d
| none => unreachable!
instance : AddErrorMessageContext TermElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
pure (ref, msg)
instance : MonadLog TermElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let ctx ← readThe Core.Context
let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };
modify fun s => { s with messages := s.messages.add msg }
protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope
protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule
protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do
let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation TermElabM where
getCurrMacroScope := Term.getCurrMacroScope
getMainModule := Term.getMainModule
withFreshMacroScope := Term.withFreshMacroScope
instance : MonadInfoTree TermElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
/--
Execute `x` but discard changes performed at `Term.State` and `Meta.State`.
Recall that the environment is at `Core.State`. Thus, any updates to it will
be preserved. This method is useful for performing computations where all
metavariable must be resolved or discarded.
The info trees are not discarded, however, and wrapped in `InfoTree.Context`
to store their metavariable context. -/
def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do
let s ← get
let sMeta ← getThe Meta.State
try
withSaveInfoContext x
finally
modify ({ s with infoState := ·.infoState })
set sMeta
/--
Execute `x` bud discard changes performed to the state.
However, the info trees and messages are not discarded. -/
private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do
let saved ← saveState
try
x
finally
let s ← get
let saved := { saved with elab.infoState := s.infoState, elab.messages := s.messages }
restoreState saved
unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=
mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term"
@[implementedBy mkTermElabAttributeUnsafe]
constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)
builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute
/--
Auxiliary datatatype for presenting a Lean lvalue modifier.
We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.
Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list
`[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`.
Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/
inductive LVal where
| fieldIdx (ref : Syntax) (i : Nat)
/- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.
`ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/
| fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)
| getOp (ref : Syntax) (idx : Syntax)
def LVal.getRef : LVal → Syntax
| LVal.fieldIdx ref _ => ref
| LVal.fieldName ref .. => ref
| LVal.getOp ref _ => ref
def LVal.isFieldName : LVal → Bool
| LVal.fieldName .. => true
| _ => false
instance : ToString LVal where
toString
| LVal.fieldIdx _ i => toString i
| LVal.fieldName _ n .. => n
| LVal.getOp _ idx => "[" ++ toString idx ++ "]"
def getDeclName? : TermElabM (Option Name) := return (← read).declName?
def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift
def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId
def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId
def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }
def withDeclName (name : Name) (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with declName? := name }) x
def setLevelNames (levelNames : List Name) : TermElabM Unit :=
modify fun s => { s with levelNames := levelNames }
def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do
let levelNamesSaved ← getLevelNames
setLevelNames levelNames
try x finally setLevelNames levelNamesSaved
def withoutErrToSorry (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with errToSorry := false }) x
/-- For testing `TermElabM` methods. The #eval command will sign the error. -/
def throwErrorIfErrors : TermElabM Unit := do
if (← get).messages.hasErrors then
throwError "Error(s)"
def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit :=
withRef Syntax.missing $ trace cls msg
def ppGoal (mvarId : MVarId) : TermElabM Format :=
Meta.ppGoal mvarId
open Level (LevelElabM)
def liftLevelM (x : LevelElabM α) : TermElabM α := do
let ctx ← read
let mctx ← getMCtx
let ngen ← getNGen
let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit }
match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with
| EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a
| EStateM.Result.error ex _ => throw ex
def elabLevel (stx : Syntax) : TermElabM Level :=
liftLevelM $ Level.elabLevel stx
/- Elaborate `x` with `stx` on the macro stack -/
def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α :=
withMacroExpansionInfo beforeStx afterStx do
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-
Add the given metavariable to the list of pending synthetic metavariables.
The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/
def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }
def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
registerSyntheticMVar (← getRef) mvarId kind
def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }
def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }
def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }
def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=
match e.getAppFn with
| Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData
| _ => pure ()
/-
Auxiliary method for reporting errors of the form "... contains metavariables ...".
This kind of error is thrown, for example, at `Match.lean` where elaboration
cannot continue if there are metavariables in patterns.
We only want to log it if we haven't logged any error so far. -/
def throwMVarError (m : MessageData) : TermElabM α := do
if (← get).messages.hasErrors then
throwAbortTerm
else
throwError m
def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do
match mvarErrorInfo.kind with
| MVarErrorKind.implicitArg app => do
let app ← instantiateMVars app
let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (appendExtra msg)
| MVarErrorKind.hole => do
let msg : MessageData := "don't know how to synthesize placeholder"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)
| MVarErrorKind.custom msg =>
logErrorAt mvarErrorInfo.ref (appendExtra msg)
where
appendExtra (msg : MessageData) : MessageData :=
match extraMsg? with
| none => msg
| some extraMsg => msg ++ extraMsg
/--
Try to log errors for the unassigned metavariables `pendingMVarIds`.
Return `true` if there were "unfilled holes", and we should "abort" declaration.
TODO: try to fill "all" holes using synthetic "sorry's"
Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/
def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do
let s ← get
let hasOtherErrors := s.messages.hasErrors
let mut hasNewErrors := false
let mut alreadyVisited : MVarIdSet := {}
for mvarErrorInfo in s.mvarErrorInfos do
let mvarId := mvarErrorInfo.mvarId
unless alreadyVisited.contains mvarId do
alreadyVisited := alreadyVisited.insert mvarId
let foundError ← withMVarContext mvarId do
/- The metavariable `mvarErrorInfo.mvarId` may have been assigned or
delayed assigned to another metavariable that is unassigned. -/
let mvarDeps ← getMVars (mkMVar mvarId)
if mvarDeps.any pendingMVarIds.contains then do
unless hasOtherErrors do
mvarErrorInfo.logError extraMsg?
pure true
else
pure false
if foundError then
hasNewErrors := true
return hasNewErrors
/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/
def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do
let pendingMVarIds ← getMVarsAtDecl decl
if (← logUnassignedUsingErrorInfos pendingMVarIds) then
throwAbortCommand
/-
Execute `x` without allowing it to postpone elaboration tasks.
That is, `tryPostpone` is a noop. -/
def withoutPostponing (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with mayPostpone := false }) x
/-- Creates syntax for `(` <ident> `:` <type> `)` -/
def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=
mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"]
/--
Convert unassigned universe level metavariables into parameters.
The new parameter names are of the form `u_i` where `i >= nextParamIdx`.
The method returns the updated expression and new `nextParamIdx`.
Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/
def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do
let mctx ← getMCtx
let levelNames ← getLevelNames
let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx
setMCtx r.mctx
pure (r.expr, r.nextParamIdx)
/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/
def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do
let nextParamIdx ← get
let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx
set nextParamIdx
pure e
/--
Auxiliary method for creating fresh binder names.
Do not confuse with the method for creating fresh free/meta variable ids. -/
def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=
withFreshMacroScope $ MonadQuotation.addMacroScope `x
/--
Auxiliary method for creating a `Syntax.ident` containing
a fresh name. This method is intended for creating fresh binder names.
It is just a thin layer on top of `mkFreshUserName`. -/
def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=
return mkIdentFrom ref (← mkFreshBinderName)
private def applyAttributesCore
(declName : Name) (attrs : Array Attribute)
(applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=
for attr in attrs do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
match applicationTime? with
| none => attrImpl.add declName attr.stx attr.kind
| some applicationTime =>
if applicationTime == attrImpl.applicationTime then
attrImpl.add declName attr.stx attr.kind
/-- Apply given attributes **at** a given application time -/
def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=
applyAttributesCore declName attrs applicationTime
def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=
applyAttributesCore declName attrs none
def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do
let header : MessageData := match header? with
| some header => m!"{header} "
| none => m!"type mismatch{indentExpr e}\n"
return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}"
def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do
/-
We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was
always of the form:
```
failed to synthesize instance
CoeT <eType> <e> <expectedType>
```
We should revisit this decision in the future and decide whether it may contain useful information
or not. -/
let extraMsg := Format.nil
/-
let extraMsg : MessageData := match extraMsg? with
| none => Format.nil
| some extraMsg => Format.line ++ extraMsg;
-/
match f? with
| none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}"
| some f => Meta.throwAppTypeMismatch f e extraMsg
def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α :=
withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x
namespace ContainsPendingMVar
abbrev M := MonadCacheT Expr Unit (OptionT TermElabM)
/-- See `containsPostponedTerm` -/
partial def visit (e : Expr) : M Unit := do
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId .. =>
match (← getLocalDecl fvarId) with
| LocalDecl.cdecl .. => return ()
| LocalDecl.ldecl (value := v) .. => visit v
| Expr.mvar mvarId .. =>
let e' ← instantiateMVars e
if e' != e then
visit e'
else
match (← getDelayedAssignment? mvarId) with
| some d => visit d.val
| none => failure
| _ => return ()
end ContainsPendingMVar
/-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/
def containsPendingMVar (e : Expr) : TermElabM Bool := do
match (← ContainsPendingMVar.visit e |>.run.run) with
| some _ => return false
| none => return true
/- Try to synthesize metavariable using type class resolution.
This method assumes the local context and local instances of `instMVar` coincide
with the current local context and local instances.
Return `true` if the instance was synthesized successfully, and `false` if
the instance contains unassigned metavariables that are blocking the type class
resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/
def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do
let instMVarDecl ← getMVarDecl instMVar
let type := instMVarDecl.type
let type ← instantiateMVars type
let result ← trySynthInstance type maxResultSize?
match result with
| LOption.some val =>
if (← isExprMVarAssigned instMVar) then
let oldVal ← instantiateMVars (mkMVar instMVar)
unless (← isDefEq oldVal val) do
if (← containsPendingMVar oldVal <||> containsPendingMVar val) then
/- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration),
we return `false` to indicate we should try again later. This is very course grain since
the metavariable may not be responsible for the failure. We should refine the test in the future if needed.
This check has been added to address dependencies between postponed metavariables. The following
example demonstrates the issue fixed by this test.
```
structure Point where
x : Nat
y : Nat
def Point.compute (p : Point) : Point :=
let p := { p with x := 1 }
let p := { p with y := 0 }
if (p.x - p.y) > p.x then p else p
```
The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to
`p` has not been elaborated yet.
-/
return false -- we will try again later
let oldValType ← inferType oldVal
let valType ← inferType val
unless (← isDefEq oldValType valType) do
throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}"
throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}"
else
unless (← isDefEq (mkMVar instMVar) val) do
throwError "failed to assign synthesized type class instance{indentExpr val}"
pure true
| LOption.undef => pure false -- we will try later
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
register_builtin_option autoLift : Bool := {
defValue := true
descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed"
}
register_builtin_option maxCoeSize : Nat := {
defValue := 16
descr := "maximum number of instances used to construct an automatic coercion"
}
def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do
synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions)))
/-
The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would
eagerly evaluate `e` -/
def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do
match expectedType with
| Expr.app (Expr.const ``Thunk u _) arg _ =>
if (← isDefEq eType arg) then
pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))
else
pure none
| _ =>
pure none
def mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let u ← getLevel eType
let v ← getLevel expectedType
let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]
let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic
let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar]
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
expandCoe eNew
else
-- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`
-- after we syntheze `mvar`
let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque
registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)
return mvarAux
catch
| Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg
| _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f?
/--
Try to apply coercion to make sure `e` has type `expectedType`.
Relevant definitions:
```
class CoeT (α : Sort u) (a : α) (β : Sort v)
abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β
```
-/
private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
if (← isDefEq expectedType eType) then
return e
else match (← tryCoeThunk? expectedType eType e) with
| some r => return r
| none => mkCoe expectedType eType e f? errorMsgHeader?
def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do
let type ← withReducible $ whnf type
match type with
| Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α)))
| _ => pure none
def synthesizeInst (type : Expr) : TermElabM Expr := do
let type ← instantiateMVars type
match (← trySynthInstance type) with
| LOption.some val => pure val
| LOption.undef => throwError "failed to synthesize instance{indentExpr type}"
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
def isMonadApp (type : Expr) : TermElabM Bool := do
let some (m, _) ← isTypeApp? type | pure false
return (← isMonad? m) |>.isSome
/--
Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`.
The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol
of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`).
The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism
do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`
since none of them is polymorphic
```
def f (x : Bool) : IO Bool := do
let y ← if x == 0 then IO.println "hello"; true else false;
!y
```
On the other hand, the following fails since `+` is polymorphic
```
def f (x : Bool) : IO Nat := do
IO.prinln x
x + x -- Error: failed to synthesize `Add (IO Nat)`
```
-/
private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) :=
commitWhenSome? do
let doIt : TermElabM (Option Expr) := do
try
let aNew ← tryCoe errorMsgHeader? β α a none
let aNew ← mkPure m aNew
pure (some aNew)
catch _ =>
pure none
forallTelescope α fun _ α => do
if (← isMonadApp α) then
pure none
else if !α.getAppFn.isMVar then
doIt
else
pure none
/-
Try coercions and monad lifts to make sure `e` has type `expectedType`.
If `expectedType` is of the form `n β`, we try monad lifts and other extensions.
Otherwise, we just use the basic `tryCoe`.
Extensions for monads.
Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α`
1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`.
It only works if `n` implements `Pure`
If `eType` is of the form `m α`. We use the following approaches.
1- Try to unify `n` and `m`. If it succeeds, then we use
```
coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β
```
`n` must be a `Monad` to use this one.
2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use
```
liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α
```
Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as
```
def g (x : Nat) : IO Nat := do
IO.println x
pure x
def f {m} [MonadLiftT IO m] : m Nat :=
g 10
```
3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use
```
liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β
```
Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`.
This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and
we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`
using the instance `pureCoeDepProp`.
Note that, approach 2 is more powerful than `tryCoe`.
Recall that type class resolution never assigns metavariables created by other modules.
Now, consider the following scenario
```lean
def g (x : Nat) : IO Nat := ...
deg h (x : Nat) : StateT Nat IO Nat := do
v ← g x;
IO.Println v;
...
```
Let's assume there is no other occurrence of `v` in `h`.
Thus, we have that the expected of `g x` is `StateT Nat IO ?α`,
and the given type is `IO Nat`. So, even if we add a coercion.
```
instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ...
```
It is not applicable because TC would have to assign `?α := Nat`.
On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`
since this goal does not contain any metavariables. And then, we
convert `g x` into `liftM $ g x`.
-/
private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
let expectedType ← instantiateMVars expectedType
let eType ← instantiateMVars eType
let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f?
let tryCoeSimple : TermElabM Expr :=
tryCoe errorMsgHeader? expectedType eType e f?
let some (n, β) ← isTypeApp? expectedType | tryCoeSimple
let tryPureCoeAndSimple : TermElabM Expr := do
if autoLift.get (← getOptions) then
match (← tryPureCoe? errorMsgHeader? n β eType e) with
| some eNew => pure eNew
| none => tryCoeSimple
else
tryCoeSimple
let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple
if (← isDefEq m n) then
let some monadInst ← isMonad? n | tryCoeSimple
try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch
else if autoLift.get (← getOptions) then
try
-- Construct lift from `m` to `n`
let monadLiftType ← mkAppM ``MonadLiftT #[m, n]
let monadLiftVal ← synthesizeInst monadLiftType
let u_1 ← getDecLevel α
let u_2 ← getDecLevel eType
let u_3 ← getDecLevel expectedType
let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e]
let eNewType ← inferType eNew
if (← isDefEq expectedType eNewType) then
return eNew -- approach 2 worked
else
let some monadInst ← isMonad? n | tryCoeSimple
let u ← getLevel α
let v ← getLevel β
let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β]
let coeTInstVal ← synthesizeInst coeTInstType
let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e])
let eNewType ← inferType eNew
unless (← isDefEq expectedType eNewType) do throwMismatch
return eNew -- approach 3 worked
catch _ =>
/-
If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.
Otherwise, we just try `tryCoe?`.
-/
match (← isMonad? m) with
| none => tryPureCoeAndSimple
| some _ => tryCoeSimple
else
tryCoeSimple
/--
If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.
If they are not, then try coercions.
Argument `f?` is used only for generating error messages. -/
def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
match expectedType? with
| none => pure e
| some expectedType =>
if (← isDefEq eType expectedType) then
pure e
else
tryLiftAndCoe errorMsgHeader? expectedType eType e f?
/--
If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.
If they are not, then try coercions. -/
def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=
match expectedType? with
| none => pure e
| _ => do
let eType ← inferType e
ensureHasTypeAux expectedType? eType e none errorMsgHeader?
private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← match expectedType? with
| none => mkFreshTypeMVar
| some expectedType => pure expectedType
mkSyntheticSorry expectedType
private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do
let syntheticSorry ← mkSyntheticSorryFor expectedType?
logException ex
pure syntheticSorry
/-- If `mayPostpone == true`, throw `Expection.postpone`. -/
def tryPostpone : TermElabM Unit := do
if (← read).mayPostpone then
throwPostpone
/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/
def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do
if e.getAppFn.isMVar then
let e ← instantiateMVars e
if e.getAppFn.isMVar then
tryPostpone
def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=
match e? with
| some e => tryPostponeIfMVar e
| none => tryPostpone
def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType? |
throwError "{msg}, expected type must be known"
let expectedType ← instantiateMVars expectedType
if expectedType.hasExprMVar then
tryPostpone
throwError "{msg}, expected type contains metavariables{indentExpr expectedType}"
pure expectedType
def saveContext : TermElabM SavedContext :=
return {
macroStack := (← read).macroStack
declName? := (← read).declName?
options := (← getOptions)
openDecls := (← getOpenDecls)
errToSorry := (← read).errToSorry
}
def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|
withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })
x
private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
trace[Elab.postpone] "{stx} : {expectedType?}"
let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque
let ctx ← read
registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext))
pure mvar
def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=
return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId
/--
Create an auxiliary annotation to make sure we create a `Info` even if `e` is a metavariable.
See `mkTermInfo`.
We use this functions because some elaboration functions elaborate subterms that may not be immediately
part of the resulting term. Example:
```
let_mvar% ?m := b; wait_if_type_mvar% ?m; body
```
If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just return a fresh
metavariable `?n`. The elaborator for
```
let_mvar% ?m := b; wait_if_type_mvar% ?m; body
```
returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are "saved".
This is a bit hackish, but elaborators like `let_mvar%` are rare.
-/
def mkSaveInfoAnnotation (e : Expr) : Expr :=
if e.isMVar then
mkAnnotation `save_info e
else
e
def isSaveInfoAnnotation? (e : Expr) : Option Expr :=
annotation? `save_info e
partial def removeSaveInfoAnnotation (e : Expr) : Expr :=
match isSaveInfoAnnotation? e with
| some e => removeSaveInfoAnnotation e
| _ => e
def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do
let isHole? : TermElabM (Option MVarId) := do
match e with
| Expr.mvar mvarId _ =>
match (← getSyntheticMVarDecl? mvarId) with
| some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId
| some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId
| _ => return none
| _ => pure none
match (← isHole?) with
| some mvarId => return Sum.inr mvarId
| none =>
let e := removeSaveInfoAnnotation e
return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder }
def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do
withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard
/-
Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or
an error is found. -/
private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)
: List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr
| [] => do throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
try
-- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)
withInfoContext' (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx)
(try
elabFn.value stx expectedType?
catch ex => match ex with
| Exception.error ref msg =>
if (← read).errToSorry then
exceptionToSorry ex expectedType?
else
throw ex
| Exception.internal id _ =>
if (← read).errToSorry && id == abortTermExceptionId then
exceptionToSorry ex expectedType?
else if id == unsupportedSyntaxExceptionId then
throw ex -- to outer try
else if catchExPostpone && id == postponeExceptionId then
/- If `elab` threw `Exception.postpone`, we reset any state modifications.
For example, we want to make sure pending synthetic metavariables created by `elab` before
it threw `Exception.postpone` are discarded.
Note that we are also discarding the messages created by `elab`.
For example, consider the expression.
`((f.x a1).x a2).x a3`
Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.
Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`
because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and
finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would
keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is
wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch
and new metavariables are created for the nested functions. -/
s.restore
postponeElabTerm stx expectedType?
else
throw ex)
catch ex => match ex with
| Exception.internal id _ =>
if id == unsupportedSyntaxExceptionId then
s.restore -- also removes the info tree created above
elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
else
throw ex
| _ => throw ex
private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do
let s ← saveState
let k := stx.getKind
match termElabAttribute.getEntries (← getEnv) k with
| [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}"
| elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
instance : MonadMacroAdapter TermElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← getThe Core.State).nextMacroScope
setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }
private def isExplicit (stx : Syntax) : Bool :=
match stx with
| `(@$f) => true
| _ => false
private def isExplicitApp (stx : Syntax) : Bool :=
stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]
/--
Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.
Example: `fun {α} (a : α) => a` -/
private def isLambdaWithImplicit (stx : Syntax) : Bool :=
match stx with
| `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder
| _ => false
private partial def dropTermParens : Syntax → Syntax := fun stx =>
match stx with
| `(($stx)) => dropTermParens stx
| _ => stx
private def isHole (stx : Syntax) : Bool :=
match stx with
| `(_) => true
| `(? _) => true
| `(? $x:ident) => true
| _ => false
private def isTacticBlock (stx : Syntax) : Bool :=
match stx with
| `(by $x:tacticSeq) => true
| _ => false
private def isNoImplicitLambda (stx : Syntax) : Bool :=
match stx with
| `(no_implicit_lambda% $x:term) => true
| _ => false
private def isTypeAscription (stx : Syntax) : Bool :=
match stx with
| `(($e : $type)) => true
| _ => false
def mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=
mkAnnotation `noImplicitLambda type
def hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=
annotation? `noImplicitLambda type |>.isSome
/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/
def blockImplicitLambda (stx : Syntax) : Bool :=
let stx := dropTermParens stx
-- TODO: make it extensible
isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||
isNoImplicitLambda stx || isTypeAscription stx
/--
Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and
`blockImplicitLambda stx` is not true, else return `none`.
Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β`
-/
private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=
if blockImplicitLambda stx then
return none
else match expectedType? with
| some expectedType => do
if hasNoImplicitLambdaAnnotation expectedType then
return none
else
let expectedType ← whnfForall expectedType
match expectedType with
| Expr.forallE _ _ _ c =>
if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then
return some expectedType
else
return none
| _ => return none
| _ => return none
private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do
match ex with
| Exception.error ref msg =>
if impFVars.isEmpty then
return Exception.error ref msg
else
let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature"
for impFVar in impFVars do
let auxMsg := m!"{impFVar} : {← inferType impFVar}"
let auxMsg ← addMessageContext auxMsg
msg := m!"{msg}{indentD auxMsg}"
msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations."
return Exception.error ref msg
| _ => return ex
private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do
let body ← elabUsingElabFns stx expectedType catchExPostpone
try
let body ← ensureHasType expectedType body
let r ← mkLambdaFVars impFVars body
trace[Elab.implicitForall] r
pure r
catch ex =>
throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars)
private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=
loop type #[]
where
loop
| type@(Expr.forallE n d b c), fvars =>
if c.binderInfo.isExplicit then
elabImplicitLambdaAux stx catchExPostpone type fvars
else withFreshMacroScope do
let n ← MonadQuotation.addMacroScope n
withLocalDecl n c.binderInfo d fun fvar => do
let type ← whnfForall (b.instantiate1 fvar)
loop type (fvars.push fvar)
| type, fvars =>
elabImplicitLambdaAux stx catchExPostpone type fvars
/- Main loop for `elabTerm` -/
private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr
| Syntax.missing => mkSyntheticSorryFor expectedType?
| stx => withFreshMacroScope <| withIncRecDepth do
trace[Elab.step] "expected type: {expectedType?}, term\n{stx}"
checkMaxHeartbeats "elaborator"
withNestedTraces do
let env ← getEnv
match (← liftMacroM (expandMacroImpl? env stx)) with
| some (decl, stxNew) =>
withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|
withMacroExpansion stx stxNew <|
withRef stxNew <|
elabTermAux expectedType? catchExPostpone implicitLambda stxNew
| _ =>
let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none
match implicit? with
| some expectedType => elabImplicitLambda stx catchExPostpone expectedType
| none => elabUsingElabFns stx expectedType? catchExPostpone
/-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/
def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do
addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)
/--
Main function for elaborating terms.
It extracts the elaboration methods from the environment using the node kind.
Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.
It creates a fresh macro scope for executing the elaboration method.
All unlogged trace messages produced by the elaboration method are logged using
the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,
the error is logged and a synthetic sorry expression is returned.
If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,
a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,
and returned.
The option `catchExPostpone == false` is used to implement `resumeElabTerm`
to prevent the creation of another synthetic metavariable when resuming the elaboration.
If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.
We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.
-/
def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=
withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx
def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let e ← elabTerm stx expectedType? catchExPostpone implicitLambda
withRef stx <| ensureHasType expectedType? e errorMsgHeader?
/--
Execute `x` and then restore `syntheticMVars`, `levelNames`, `mvarErrorInfos`, and `letRecsToLift`.
We use this combinator when we don't want the pending problems created by `x` to persist after its execution. -/
def withoutPending (x : TermElabM α) : TermElabM α := do
let saved ← get
try
x
finally
modify fun s => { s with syntheticMVars := saved.syntheticMVars, levelNames := saved.levelNames,
letRecsToLift := saved.letRecsToLift, mvarErrorInfos := saved.mvarErrorInfos }
/-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/
def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do
let saved ← saveState
modify fun s => { s with messages := {} }
try
let a ← x
if (← get).messages.hasErrors then
restoreState saved
return none
else
modify fun s => { s with messages := saved.elab.messages ++ s.messages }
return a
catch _ =>
restoreState saved
return none
/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/
def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do
let stx' ← exp stx
withMacroExpansion stx stx' $ elabTerm stx' expectedType?
def mkInstMVar (type : Expr) : TermElabM Expr := do
let mvar ← mkFreshExprMVar type MetavarKind.synthetic
let mvarId := mvar.mvarId!
unless (← synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
pure mvar
/-
Relevant definitions:
```
class CoeSort (α : Sort u) (β : outParam (Sort v))
abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β
```
-/
private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do
let β ← mkFreshTypeMVar
let u ← getLevel α
let v ← getLevel β
let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β]
let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
let result ← expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar]
unless (← isType result) do
throwError "failed to coerse{indentExpr a}\nto a type, after applying `coeSort`, result is still not a type{indentExpr result}\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\nwas{indentExpr mvar}"
return result
else
throwError "type expected"
catch
| Exception.error _ msg => throwError "type expected\n{msg}"
| _ => throwError "type expected"
/--
Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`
or is unifiable with `Expr.sort`, or can be coerced into one. -/
def ensureType (e : Expr) : TermElabM Expr := do
if (← isType e) then
pure e
else
let eType ← inferType e
let u ← mkFreshLevelMVar
if (← isDefEq eType (mkSort u)) then
pure e
else
tryCoeSort eType e
/-- Elaborate `stx` and ensure result is a type. -/
def elabType (stx : Syntax) : TermElabM Expr := do
let u ← mkFreshLevelMVar
let type ← elabTerm stx (mkSort u)
withRef stx $ ensureType type
/--
Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,
a new local declaration is created, registered, and `k` is tried to be executed again. -/
partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
let flag := autoBoundImplicitLocal.get (← getOptions)
if flag then
withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do
let rec loop (s : SavedState) : TermElabM α := do
try
k
catch
| ex => match isAutoBoundImplicitLocalException? ex with
| some n =>
-- Restore state, declare `n`, and try again
s.restore
withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x =>
withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do
loop (← saveState)
| none => throw ex
loop (← saveState)
else
k
def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k
/--
Return `autoBoundImplicits ++ xs.
This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/
def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do
let autoBoundImplicits := (← read).autoBoundImplicits
for auto in autoBoundImplicits do
let localDecl ← getLocalDecl auto.fvarId!
for x in xs do
if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then
throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'"
return autoBoundImplicits.toArray ++ xs
def mkAuxName (suffix : Name) : TermElabM Name := do
match (← read).declName? with
| none => throwError "auxiliary declaration cannot be created when declaration name is not available"
| some declName => Lean.mkAuxName (declName ++ suffix) 1
builtin_initialize registerTraceClass `Elab.letrec
/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it
is delayed assigned to one. -/
def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do
trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}"
let mvarId := (← getMCtx).getDelayedRoot mvarId
trace[Elab.letrec] "mvarId root: {mkMVar mvarId}"
return (← get).letRecsToLift.any (·.mvarId == mvarId)
def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do
let lctx ← getLCtx
let view := extractMacroScopes n
let rec loop (n : Name) (projs : List String) :=
match lctx.findFromUserName? { view with name := n }.review with
| some decl =>
if decl.isAuxDecl && !projs.isEmpty then
/- We do not consider dot notation for local decls corresponding to recursive functions being defined.
The following example would not be elaborated correctly without this case.
```
def foo.aux := 1
def foo : Nat → Nat
| n => foo.aux -- should not be interpreted as `(foo).bar`
```
-/
none
else
some (decl.toExpr, projs)
| none => match n with
| Name.str pre s _ => loop pre (s::projs)
| _ => none
return loop view.name []
/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/
def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val _ => do
let r? ← resolveLocalName val
match r? with
| some (fvar, []) => pure (some fvar)
| _ => pure none
| _ => pure none
/--
Create an `Expr.const` using the given name and explicit levels.
Remark: fresh universe metavariables are created if the constant has more universe
parameters than `explicitLevels`. -/
def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do
let cinfo ← getConstInfo constName
if explicitLevels.length > cinfo.levelParams.length then
throwError "too many explicit universe levels for '{constName}'"
else
let numMissingLevels := cinfo.levelParams.length - explicitLevels.length
let us ← mkFreshLevelMVars numMissingLevels
pure $ Lean.mkConst constName (explicitLevels ++ us)
private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do
candidates.foldlM (init := []) fun result (constName, projs) => do
-- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.
let const ← mkConst constName explicitLevels
return (const, projs) :: result
def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do
try
if let some (e, projs) ← resolveLocalName n then
unless explicitLevels.isEmpty do
throwError "invalid use of explicit universe parameters, '{e}' is a local"
return [(e, projs)]
-- check for section variable capture by a quotation
let ctx ← read
if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then
return [(e, projs)] -- section variables should shadow global decls
if preresolved.isEmpty then
process (← resolveGlobalName n)
else
process preresolved
catch ex =>
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
throw ex
where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do
if candidates.isEmpty then
if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then
throwAutoBoundImplicitLocal n
else
throwError "unknown identifier '{Lean.mkConst n}'"
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
mkConsts candidates explicitLevels
/--
Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.
Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces
`(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/
def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do
match ident with
| Syntax.ident info rawStr n preresolved =>
let r ← resolveName ident n preresolved explicitLevels expectedType?
r.mapM fun (c, fields) => do
let ids := ident.identComponents (nFields? := fields.length)
return (c, ids.head!, ids.tail!)
| _ => throwError "identifier expected"
def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val preresolved => do
let rs ← try resolveName stx val preresolved [] catch _ => pure []
let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty
let fs := rs.map fun (f, _) => f
match fs with
| [] => pure none
| [f] =>
if withInfo then
addTermInfo stx f
pure (some f)
| _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}"
| _ => throwError "identifier expected"
private def mkSomeContext : Context := {
fileName := "<TermElabM>"
fileMap := arbitrary
}
def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) :=
withConfig setElabConfig (x ctx |>.run s)
@[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α :=
(·.1) <$> x.run ctx s
def TermElabM.toIO (x : TermElabM α)
(ctxCore : Core.Context) (sCore : Core.State)
(ctxMeta : Meta.Context) (sMeta : Meta.State)
(ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do
let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta
pure (a, sCore, sMeta, s)
instance [MetaEval α] : MetaEval (TermElabM α) where
eval env opts x _ :=
let x : TermElabM α := do
try x finally
let s ← get
s.messages.forM fun msg => do IO.println (← msg.toString)
MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext
unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α :=
withoutModifyingEnv do
let name ← mkFreshUserName `_tmp
let type ← inferType value
let type ← whnfD type
unless type.isConstOf typeName do
throwError "unexpected type at evalExpr{indentExpr type}"
let decl := Declaration.defnDecl {
name := name, levelParams := [], type := type,
value := value, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.unsafe
}
ensureNoUnassignedMVars decl
addAndCompile decl
evalConst α name
private def throwStuckAtUniverseCnstr : TermElabM Unit := do
-- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property
let entries ← getPostponed
let mut found : Std.HashSet (Level × Level) := {}
let mut uniqueEntries := #[]
for entry in entries do
let mut lhs := entry.lhs
let mut rhs := entry.rhs
if Level.normLt rhs lhs then
(lhs, rhs) := (rhs, lhs)
unless found.contains (lhs, rhs) do
found := found.insert (lhs, rhs)
uniqueEntries := uniqueEntries.push entry
for i in [1:uniqueEntries.size] do
logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i])
throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0])
def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do
let postponed ← getResetPostponed
try
let a ← x
unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do
throwStuckAtUniverseCnstr
setPostponed postponed
return a
catch ex =>
setPostponed postponed
throw ex
end Term
open Term in
def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do
controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x
builtin_initialize
registerTraceClass `Elab.postpone
registerTraceClass `Elab.coe
registerTraceClass `Elab.debug
export Term (TermElabM)
end Lean.Elab
|
ddf9ace338a4776adad05d469e544bfaef990365 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/group/opposite.lean | 72b86f1524c91e75a82b76e2608b7b58623bf0db | [
"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 | 21,345 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.group.inj_surj
import algebra.group.commute
import algebra.hom.equiv.basic
import algebra.opposites
import data.int.cast.defs
/-!
# Group structures on the multiplicative and additive opposites
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes u v
variables (α : Type u)
namespace mul_opposite
/-!
### Additive structures on `αᵐᵒᵖ`
-/
instance [add_semigroup α] : add_semigroup (αᵐᵒᵖ) :=
unop_injective.add_semigroup _ (λ x y, rfl)
instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup αᵐᵒᵖ :=
unop_injective.add_left_cancel_semigroup _ (λ x y, rfl)
instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup αᵐᵒᵖ :=
unop_injective.add_right_cancel_semigroup _ (λ x y, rfl)
instance [add_comm_semigroup α] : add_comm_semigroup αᵐᵒᵖ :=
unop_injective.add_comm_semigroup _ (λ x y, rfl)
instance [add_zero_class α] : add_zero_class αᵐᵒᵖ :=
unop_injective.add_zero_class _ rfl (λ x y, rfl)
instance [add_monoid α] : add_monoid αᵐᵒᵖ :=
unop_injective.add_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl)
instance [add_monoid_with_one α] : add_monoid_with_one αᵐᵒᵖ :=
{ nat_cast := λ n, op n,
nat_cast_zero := show op ((0 : ℕ) : α) = 0, by simp,
nat_cast_succ := show ∀ n, op ((n + 1 : ℕ) : α) = op (n : ℕ) + 1, by simp,
.. mul_opposite.add_monoid α, .. mul_opposite.has_one α }
instance [add_comm_monoid α] : add_comm_monoid αᵐᵒᵖ :=
unop_injective.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl)
instance [sub_neg_monoid α] : sub_neg_monoid αᵐᵒᵖ :=
unop_injective.sub_neg_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
instance [add_group α] : add_group αᵐᵒᵖ :=
unop_injective.add_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
instance [add_group_with_one α] : add_group_with_one αᵐᵒᵖ :=
{ int_cast := λ n, op n,
int_cast_of_nat := λ n, show op ((n : ℤ) : α) = op n, by rw int.cast_coe_nat,
int_cast_neg_succ_of_nat := λ n, show op _ = op (- unop (op ((n + 1 : ℕ) : α))),
by erw [unop_op, int.cast_neg_succ_of_nat]; refl,
.. mul_opposite.add_monoid_with_one α, .. mul_opposite.add_group α }
instance [add_comm_group α] : add_comm_group αᵐᵒᵖ :=
unop_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-!
### Multiplicative structures on `αᵐᵒᵖ`
We also generate additive structures on `αᵃᵒᵖ` using `to_additive`
-/
@[to_additive] instance [semigroup α] : semigroup αᵐᵒᵖ :=
{ mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x),
.. mul_opposite.has_mul α }
@[to_additive] instance [right_cancel_semigroup α] : left_cancel_semigroup αᵐᵒᵖ :=
{ mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H,
.. mul_opposite.semigroup α }
@[to_additive] instance [left_cancel_semigroup α] : right_cancel_semigroup αᵐᵒᵖ :=
{ mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H,
.. mul_opposite.semigroup α }
@[to_additive] instance [comm_semigroup α] : comm_semigroup αᵐᵒᵖ :=
{ mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x),
.. mul_opposite.semigroup α }
@[to_additive] instance [mul_one_class α] : mul_one_class αᵐᵒᵖ :=
{ one_mul := λ x, unop_injective $ mul_one $ unop x,
mul_one := λ x, unop_injective $ one_mul $ unop x,
.. mul_opposite.has_mul α, .. mul_opposite.has_one α }
@[to_additive] instance [monoid α] : monoid αᵐᵒᵖ :=
{ npow := λ n x, op $ x.unop ^ n,
npow_zero' := λ x, unop_injective $ monoid.npow_zero' x.unop,
npow_succ' := λ n x, unop_injective $ pow_succ' x.unop n,
.. mul_opposite.semigroup α, .. mul_opposite.mul_one_class α }
@[to_additive] instance [right_cancel_monoid α] : left_cancel_monoid αᵐᵒᵖ :=
{ .. mul_opposite.left_cancel_semigroup α, .. mul_opposite.monoid α }
@[to_additive] instance [left_cancel_monoid α] : right_cancel_monoid αᵐᵒᵖ :=
{ .. mul_opposite.right_cancel_semigroup α, .. mul_opposite.monoid α }
@[to_additive] instance [cancel_monoid α] : cancel_monoid αᵐᵒᵖ :=
{ .. mul_opposite.right_cancel_monoid α, .. mul_opposite.left_cancel_monoid α }
@[to_additive] instance [comm_monoid α] : comm_monoid αᵐᵒᵖ :=
{ .. mul_opposite.monoid α, .. mul_opposite.comm_semigroup α }
@[to_additive] instance [cancel_comm_monoid α] : cancel_comm_monoid αᵐᵒᵖ :=
{ .. mul_opposite.cancel_monoid α, .. mul_opposite.comm_monoid α }
@[to_additive add_opposite.sub_neg_monoid] instance [div_inv_monoid α] : div_inv_monoid αᵐᵒᵖ :=
{ zpow := λ n x, op $ x.unop ^ n,
zpow_zero' := λ x, unop_injective $ div_inv_monoid.zpow_zero' x.unop,
zpow_succ' := λ n x, unop_injective $
by rw [unop_op, zpow_of_nat, zpow_of_nat, pow_succ', unop_mul, unop_op],
zpow_neg' := λ z x, unop_injective $ div_inv_monoid.zpow_neg' z x.unop,
.. mul_opposite.monoid α, .. mul_opposite.has_inv α }
@[to_additive add_opposite.subtraction_monoid] instance [division_monoid α] :
division_monoid αᵐᵒᵖ :=
{ mul_inv_rev := λ a b, unop_injective $ mul_inv_rev _ _,
inv_eq_of_mul := λ a b h, unop_injective $ inv_eq_of_mul_eq_one_left $ congr_arg unop h,
.. mul_opposite.div_inv_monoid α, .. mul_opposite.has_involutive_inv α }
@[to_additive add_opposite.subtraction_comm_monoid] instance [division_comm_monoid α] :
division_comm_monoid αᵐᵒᵖ :=
{ ..mul_opposite.division_monoid α, ..mul_opposite.comm_semigroup α }
@[to_additive] instance [group α] : group αᵐᵒᵖ :=
{ mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x,
.. mul_opposite.div_inv_monoid α, }
@[to_additive] instance [comm_group α] : comm_group αᵐᵒᵖ :=
{ .. mul_opposite.group α, .. mul_opposite.comm_monoid α }
variable {α}
@[simp, to_additive] lemma unop_div [div_inv_monoid α] (x y : αᵐᵒᵖ) :
unop (x / y) = (unop y)⁻¹ * unop x :=
rfl
@[simp, to_additive] lemma op_div [div_inv_monoid α] (x y : α) :
op (x / y) = (op y)⁻¹ * op x :=
by simp [div_eq_mul_inv]
@[simp, to_additive] lemma semiconj_by_op [has_mul α] {a x y : α} :
semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y :=
by simp only [semiconj_by, ← op_mul, op_inj, eq_comm]
@[simp, to_additive] lemma semiconj_by_unop [has_mul α] {a x y : αᵐᵒᵖ} :
semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y :=
by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] }
@[to_additive] lemma _root_.semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) :
semiconj_by (op a) (op y) (op x) :=
semiconj_by_op.2 h
@[to_additive] lemma _root_.semiconj_by.unop [has_mul α] {a x y : αᵐᵒᵖ} (h : semiconj_by a x y) :
semiconj_by (unop a) (unop y) (unop x) :=
semiconj_by_unop.2 h
@[to_additive] lemma _root_.commute.op [has_mul α] {x y : α} (h : commute x y) :
commute (op x) (op y) := h.op
@[to_additive] lemma commute.unop [has_mul α] {x y : αᵐᵒᵖ} (h : commute x y) :
commute (unop x) (unop y) := h.unop
@[simp, to_additive] lemma commute_op [has_mul α] {x y : α} :
commute (op x) (op y) ↔ commute x y :=
semiconj_by_op
@[simp, to_additive] lemma commute_unop [has_mul α] {x y : αᵐᵒᵖ} :
commute (unop x) (unop y) ↔ commute x y :=
semiconj_by_unop
/-- The function `mul_opposite.op` is an additive equivalence. -/
@[simps { fully_applied := ff, simp_rhs := tt }]
def op_add_equiv [has_add α] : α ≃+ αᵐᵒᵖ :=
{ map_add' := λ a b, rfl, .. op_equiv }
@[simp] lemma op_add_equiv_to_equiv [has_add α] :
(op_add_equiv : α ≃+ αᵐᵒᵖ).to_equiv = op_equiv :=
rfl
end mul_opposite
/-!
### Multiplicative structures on `αᵃᵒᵖ`
-/
namespace add_opposite
instance [semigroup α] : semigroup (αᵃᵒᵖ) :=
unop_injective.semigroup _ (λ x y, rfl)
instance [left_cancel_semigroup α] : left_cancel_semigroup αᵃᵒᵖ :=
unop_injective.left_cancel_semigroup _ (λ x y, rfl)
instance [right_cancel_semigroup α] : right_cancel_semigroup αᵃᵒᵖ :=
unop_injective.right_cancel_semigroup _ (λ x y, rfl)
instance [comm_semigroup α] : comm_semigroup αᵃᵒᵖ :=
unop_injective.comm_semigroup _ (λ x y, rfl)
instance [mul_one_class α] : mul_one_class αᵃᵒᵖ :=
unop_injective.mul_one_class _ rfl (λ x y, rfl)
instance {β} [has_pow α β] : has_pow αᵃᵒᵖ β := { pow := λ a b, op (unop a ^ b) }
@[simp] lemma op_pow {β} [has_pow α β] (a : α) (b : β) : op (a ^ b) = op a ^ b := rfl
@[simp] lemma unop_pow {β} [has_pow α β] (a : αᵃᵒᵖ) (b : β) : unop (a ^ b) = unop a ^ b := rfl
instance [monoid α] : monoid αᵃᵒᵖ :=
unop_injective.monoid _ rfl (λ _ _, rfl) (λ _ _, rfl)
instance [comm_monoid α] : comm_monoid αᵃᵒᵖ :=
unop_injective.comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl)
instance [div_inv_monoid α] : div_inv_monoid αᵃᵒᵖ :=
unop_injective.div_inv_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
instance [group α] : group αᵃᵒᵖ :=
unop_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
instance [comm_group α] : comm_group αᵃᵒᵖ :=
unop_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
variable {α}
/-- The function `add_opposite.op` is a multiplicative equivalence. -/
@[simps { fully_applied := ff, simp_rhs := tt }]
def op_mul_equiv [has_mul α] : α ≃* αᵃᵒᵖ :=
{ map_mul' := λ a b, rfl, .. op_equiv }
@[simp] lemma op_mul_equiv_to_equiv [has_mul α] :
(op_mul_equiv : α ≃* αᵃᵒᵖ).to_equiv = op_equiv :=
rfl
end add_opposite
open mul_opposite
/-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is
`mul_equiv.inv`. -/
@[to_additive "Negation on an additive group is an `add_equiv` to the opposite group. When `G`
is commutative, there is `add_equiv.inv`.", simps { fully_applied := ff, simp_rhs := tt }]
def mul_equiv.inv' (G : Type*) [division_monoid G] : G ≃* Gᵐᵒᵖ :=
{ map_mul' := λ x y, unop_injective $ mul_inv_rev x y,
.. (equiv.inv G).trans op_equiv }
/-- A semigroup homomorphism `f : M →ₙ* N` such that `f x` commutes with `f y` for all `x, y`
defines a semigroup homomorphism to `Nᵐᵒᵖ`. -/
@[to_additive "An additive semigroup homomorphism `f : add_hom M N` such that `f x` additively
commutes with `f y` for all `x, y` defines an additive semigroup homomorphism to `Sᵃᵒᵖ`.",
simps {fully_applied := ff}]
def mul_hom.to_opposite {M N : Type*} [has_mul M] [has_mul N] (f : M →ₙ* N)
(hf : ∀ x y, commute (f x) (f y)) : M →ₙ* Nᵐᵒᵖ :=
{ to_fun := mul_opposite.op ∘ f,
map_mul' := λ x y, by simp [(hf x y).eq] }
/-- A semigroup homomorphism `f : M →ₙ* N` such that `f x` commutes with `f y` for all `x, y`
defines a semigroup homomorphism from `Mᵐᵒᵖ`. -/
@[to_additive "An additive semigroup homomorphism `f : add_hom M N` such that `f x` additively
commutes with `f y` for all `x`, `y` defines an additive semigroup homomorphism from `Mᵃᵒᵖ`.",
simps {fully_applied := ff}]
def mul_hom.from_opposite {M N : Type*} [has_mul M] [has_mul N] (f : M →ₙ* N)
(hf : ∀ x y, commute (f x) (f y)) : Mᵐᵒᵖ →ₙ* N :=
{ to_fun := f ∘ mul_opposite.unop,
map_mul' := λ x y, (f.map_mul _ _).trans (hf _ _).eq }
/-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines
a monoid homomorphism to `Nᵐᵒᵖ`. -/
@[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes
with `f y` for all `x, y` defines an additive monoid homomorphism to `Sᵃᵒᵖ`.",
simps {fully_applied := ff}]
def monoid_hom.to_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N)
(hf : ∀ x y, commute (f x) (f y)) : M →* Nᵐᵒᵖ :=
{ to_fun := mul_opposite.op ∘ f,
map_one' := congr_arg op f.map_one,
map_mul' := λ x y, by simp [(hf x y).eq] }
/-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines
a monoid homomorphism from `Mᵐᵒᵖ`. -/
@[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes
with `f y` for all `x`, `y` defines an additive monoid homomorphism from `Mᵃᵒᵖ`.",
simps {fully_applied := ff}]
def monoid_hom.from_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N)
(hf : ∀ x y, commute (f x) (f y)) : Mᵐᵒᵖ →* N :=
{ to_fun := f ∘ mul_opposite.unop,
map_one' := f.map_one,
map_mul' := λ x y, (f.map_mul _ _).trans (hf _ _).eq }
/-- The units of the opposites are equivalent to the opposites of the units. -/
@[to_additive "The additive units of the additive opposites are equivalent to the additive opposites
of the additive units."]
def units.op_equiv {M} [monoid M] : (Mᵐᵒᵖ)ˣ ≃* (Mˣ)ᵐᵒᵖ :=
{ to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩,
inv_fun := mul_opposite.rec $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩,
map_mul' := λ x y, unop_injective $ units.ext $ rfl,
left_inv := λ x, units.ext $ by simp,
right_inv := λ x, unop_injective $ units.ext $ rfl }
@[simp, to_additive]
lemma units.coe_unop_op_equiv {M} [monoid M] (u : (Mᵐᵒᵖ)ˣ) :
((units.op_equiv u).unop : M) = unop (u : Mᵐᵒᵖ) :=
rfl
@[simp, to_additive]
lemma units.coe_op_equiv_symm {M} [monoid M] (u : (Mˣ)ᵐᵒᵖ) :
(units.op_equiv.symm u : Mᵐᵒᵖ) = op (u.unop : M) :=
rfl
/-- A semigroup homomorphism `M →ₙ* N` can equivalently be viewed as a semigroup homomorphism
`Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/
@[to_additive "An additive semigroup homomorphism `add_hom M N` can equivalently be viewed as an
additive semigroup homomorphism `add_hom Mᵃᵒᵖ Nᵃᵒᵖ`. This is the action of the (fully faithful)
`ᵃᵒᵖ`-functor on morphisms.", simps]
def mul_hom.op {M N} [has_mul M] [has_mul N] :
(M →ₙ* N) ≃ (Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext x, simp } }
/-- The 'unopposite' of a semigroup homomorphism `Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ`. Inverse to `mul_hom.op`. -/
@[simp, to_additive "The 'unopposite' of an additive semigroup homomorphism `Mᵃᵒᵖ →ₙ+ Nᵃᵒᵖ`. Inverse
to `add_hom.op`."]
def mul_hom.unop {M N} [has_mul M] [has_mul N] :
(Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ) ≃ (M →ₙ* N) := mul_hom.op.symm
/-- An additive semigroup homomorphism `add_hom M N` can equivalently be viewed as an additive
homomorphism `add_hom Mᵐᵒᵖ Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on
morphisms. -/
@[simps]
def add_hom.mul_op {M N} [has_add M] [has_add N] :
(add_hom M N) ≃ (add_hom Mᵐᵒᵖ Nᵐᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of an additive semigroup hom `αᵐᵒᵖ →+ βᵐᵒᵖ`. Inverse to
`add_hom.mul_op`. -/
@[simp] def add_hom.mul_unop {α β} [has_add α] [has_add β] :
(add_hom αᵐᵒᵖ βᵐᵒᵖ) ≃ (add_hom α β) := add_hom.mul_op.symm
/-- A monoid homomorphism `M →* N` can equivalently be viewed as a monoid homomorphism
`Mᵐᵒᵖ →* Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/
@[to_additive "An additive monoid homomorphism `M →+ N` can equivalently be viewed as an
additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. This is the action of the (fully faithful)
`ᵃᵒᵖ`-functor on morphisms.", simps]
def monoid_hom.op {M N} [mul_one_class M] [mul_one_class N] :
(M →* N) ≃ (Mᵐᵒᵖ →* Nᵐᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_one' := congr_arg op f.map_one,
map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_one' := congr_arg unop f.map_one,
map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext x, simp } }
/-- The 'unopposite' of a monoid homomorphism `Mᵐᵒᵖ →* Nᵐᵒᵖ`. Inverse to `monoid_hom.op`. -/
@[simp, to_additive "The 'unopposite' of an additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. Inverse to
`add_monoid_hom.op`."]
def monoid_hom.unop {M N} [mul_one_class M] [mul_one_class N] :
(Mᵐᵒᵖ →* Nᵐᵒᵖ) ≃ (M →* N) := monoid_hom.op.symm
/-- An additive homomorphism `M →+ N` can equivalently be viewed as an additive homomorphism
`Mᵐᵒᵖ →+ Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/
@[simps]
def add_monoid_hom.mul_op {M N} [add_zero_class M] [add_zero_class N] :
(M →+ N) ≃ (Mᵐᵒᵖ →+ Nᵐᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_zero' := unop_injective f.map_zero,
map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_zero' := congr_arg unop f.map_zero,
map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of an additive monoid hom `αᵐᵒᵖ →+ βᵐᵒᵖ`. Inverse to
`add_monoid_hom.mul_op`. -/
@[simp] def add_monoid_hom.mul_unop {α β} [add_zero_class α] [add_zero_class β] :
(αᵐᵒᵖ →+ βᵐᵒᵖ) ≃ (α →+ β) := add_monoid_hom.mul_op.symm
/-- A iso `α ≃+ β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. -/
@[simps]
def add_equiv.mul_op {α β} [has_add α] [has_add β] :
(α ≃+ β) ≃ (αᵐᵒᵖ ≃+ βᵐᵒᵖ) :=
{ to_fun := λ f, op_add_equiv.symm.trans (f.trans op_add_equiv),
inv_fun := λ f, op_add_equiv.trans (f.trans op_add_equiv.symm),
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. Inverse to `add_equiv.mul_op`. -/
@[simp] def add_equiv.mul_unop {α β} [has_add α] [has_add β] :
(αᵐᵒᵖ ≃+ βᵐᵒᵖ) ≃ (α ≃+ β) := add_equiv.mul_op.symm
/-- A iso `α ≃* β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. -/
@[to_additive "A iso `α ≃+ β` can equivalently be viewed as an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`.", simps]
def mul_equiv.op {α β} [has_mul α] [has_mul β] :
(α ≃* β) ≃ (αᵐᵒᵖ ≃* βᵐᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
inv_fun := op ∘ f.symm ∘ unop,
left_inv := λ x, unop_injective (f.symm_apply_apply x.unop),
right_inv := λ x, unop_injective (f.apply_symm_apply x.unop),
map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
inv_fun := unop ∘ f.symm ∘ op,
left_inv := λ x, by simp,
right_inv := λ x, by simp,
map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. Inverse to `mul_equiv.op`. -/
@[simp, to_additive "The 'unopposite' of an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`. Inverse to `add_equiv.op`."]
def mul_equiv.unop {α β} [has_mul α] [has_mul β] :
(αᵐᵒᵖ ≃* βᵐᵒᵖ) ≃ (α ≃* β) := mul_equiv.op.symm
section ext
/-- This ext lemma change equalities on `αᵐᵒᵖ →+ β` to equalities on `α →+ β`.
This is useful because there are often ext lemmas for specific `α`s that will apply
to an equality of `α →+ β` such as `finsupp.add_hom_ext'`. -/
@[ext]
lemma add_monoid_hom.mul_op_ext {α β} [add_zero_class α] [add_zero_class β]
(f g : αᵐᵒᵖ →+ β)
(h : f.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom =
g.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom) : f = g :=
add_monoid_hom.ext $ mul_opposite.rec $ λ x, (add_monoid_hom.congr_fun h : _) x
end ext
|
7e754983b98ccbc0a84a49291a380fc0fe9a54f1 | 56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3 | /src/demo.lean | 18a679a3f74a7ba0b937c301621ab0288f22bc02 | [
"Apache-2.0"
] | permissive | DyeKuu/lean-tpe-public | 3a9968f286ca182723ef7e7d97e155d8cb6b1e70 | 750ade767ab28037e80b7a80360d213a875038f8 | refs/heads/master | 1,682,842,633,115 | 1,621,330,793,000 | 1,621,330,793,000 | 368,475,816 | 0 | 0 | Apache-2.0 | 1,621,330,745,000 | 1,621,330,744,000 | null | UTF-8 | Lean | false | false | 2,054 | lean | import algebra.archimedean
import data.list
import all
import .trythis
namespace nng
lemma add_assoc (a b c : ℕ)
: (a + b) + c = a + (b + c) :=
begin
-- rw [nat.add_assoc, nat.add_comm a],
simp [nat.add_assoc]
end
open nat
lemma succ_add (a b : ℕ)
: succ a + b = succ (a + b) :=
begin
-- rw [← add_succ, add_succ, succ_add]
apply succ_add; rw [nat.add_comm, nat.zero_add]; refl
end
lemma add_right_comm (a b c : ℕ)
: a + b + c = a + c + b :=
begin
-- rw [add_comm a, add_comm a, add_assoc],
-- rw [add_comm b, add_comm a, add_assoc]
rw add_right_comm; refl
end
lemma succ_mul (a b : ℕ)
: succ a * b = a * b + b :=
begin
-- rw [← nat.succ_mul],
rw [← add_one, succ_mul]
end
theorem add_le_add_right {a b : ℕ}
: a ≤ b → ∀ t, (a + t) ≤ (b + t) :=
begin
-- intros h t,
-- rw [nat.add_comm a t, nat.add_comm b t],
-- apply nat.add_le_add_left h _
apply nat.add_le_add_right
end
theorem mul_left_cancel (a b c : ℕ) (ha : a ≠ 0)
: a * b = (a + 0) * c → b = 1 * c :=
begin
-- simp,
-- rintro (⟨⟨h₁, h₂⟩, rfl⟩ | ⟨⟨h₁, h₂⟩, rfl⟩),
-- assumption,
-- contradiction
simpa [one_mul] using (mul_left_inj' ha).mp
end
lemma lt_aux_two (a b : ℕ) : succ a ≤ b → a ≤ b ∧ ¬ (b ≤ a) :=
begin
intro h, exact ⟨nat.le_of_succ_le h, not_le_of_gt h⟩
end
universe u
variables {R : Type u} [linear_ordered_ring R] [floor_ring R] {x : R}
lemma floor_ciel (z : ℤ) : z = ⌈(z:R)⌉ :=
begin
-- rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
simp
end
example (x y : ℤ) : (- - x) - y = -(y - x) :=
begin
-- simp
simp
end
variables {G : Type u} [group G]
example (x y z : G) : (x * z) * (z⁻¹ * y) = x * y :=
begin
-- group
rw [←mul_assoc, mul_inv_cancel_right]
end
open list
example {α: Type u} (a : α) (l : list α)
: list.reverse (l ++ [a]) = a :: l.reverse :=
begin
simp
-- induction l, {refl}, {simp only [*, cons_append, reverse_cons, append_assoc, reverse_nil, perm.nil, append_nil, perm.cons], simp}
end
end nng
|
d467ed7155a74b61724c0aab7ea4ab15b7cc36af | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/metric_space/basic.lean | cd0cafe93a0c2ebf7e541fb3d1be836ff7dc2459 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 131,317 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.int.interval
import topology.algebra.order.compact
import topology.metric_space.emetric_space
import topology.bornology.constructions
import topology.uniform_space.complete_separated
/-!
# Metric spaces
This file defines metric spaces. Many definitions and theorems expected
on metric spaces are already introduced on uniform spaces and topological spaces.
For example: open and closed sets, compactness, completeness, continuity and uniform continuity
## Main definitions
* `has_dist α`: Endows a space `α` with a function `dist a b`.
* `pseudo_metric_space α`: A space endowed with a distance function, which can
be zero even if the two elements are non-equal.
* `metric.ball x ε`: The set of all points `y` with `dist y x < ε`.
* `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded.
* `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`.
Additional useful definitions:
* `nndist a b`: `dist` as a function to the non-negative reals.
* `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`.
* `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`.
* `proper_space α`: A `pseudo_metric_space` where all closed balls are compact.
* `metric.diam s` : The `supr` of the distances of members of `s`.
Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite.
TODO (anyone): Add "Main results" section.
## Implementation notes
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize
to `metric_space` at the end.
## Tags
metric, pseudo_metric, dist
-/
open set filter topological_space bornology
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v}
/-- Construct a uniform structure core from a distance function and metric space axioms.
This is a technical construction that can be immediately used to construct a uniform structure
from a distance function and metric space axioms but is also useful when discussing
metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/
def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α :=
{ uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle)
/-- This is an internal lemma used to construct a bornology from a metric in `bornology.of_dist`. -/
private lemma bounded_iff_aux {α : Type*} (dist : α → α → ℝ)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(s : set α) (a : α) :
(∃ c, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ c) ↔ (∃ r, ∀ ⦃x⦄, x ∈ s → dist x a ≤ r) :=
begin
split; rintro ⟨C, hC⟩,
{ rcases s.eq_empty_or_nonempty with rfl | ⟨x, hx⟩,
{ exact ⟨0, by simp⟩ },
{ exact ⟨C + dist x a, λ y hy,
(dist_triangle y x a).trans (add_le_add_right (hC hy hx) _)⟩ } },
{ exact ⟨C + C, λ x hx y hy,
(dist_triangle x a y).trans (add_le_add (hC hx) (by {rw dist_comm, exact hC hy}))⟩ }
end
/-- Construct a bornology from a distance function and metric space axioms. -/
def bornology.of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) :
bornology α :=
bornology.of_bounded
{ s : set α | ∃ C, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C }
⟨0, λ x hx y, hx.elim⟩
(λ s ⟨c, hc⟩ t h, ⟨c, λ x hx y hy, hc (h hx) (h hy)⟩)
(λ s hs t ht,
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨z, hz⟩,
{ exact (empty_union t).symm ▸ ht },
{ simp only [λ u, bounded_iff_aux dist dist_comm dist_triangle u z] at hs ht ⊢,
rcases ⟨hs, ht⟩ with ⟨⟨r₁, hr₁⟩, ⟨r₂, hr₂⟩⟩,
exact ⟨max r₁ r₂, λ x hx, or.elim hx
(λ hx', (hr₁ hx').trans (le_max_left _ _))
(λ hx', (hr₂ hx').trans (le_max_right _ _))⟩ }
end)
(λ z, ⟨0, λ x hx y hy,
by { rw [eq_of_mem_singleton hx, eq_of_mem_singleton hy], exact (dist_self z).le }⟩)
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
@[ext] class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/
private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_right this zero_lt_two
/-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is
used. -/
protected meta def pseudo_metric_space.edist_dist_tac : tactic unit :=
tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac]
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
-/
class pseudo_metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ℝ≥0∞ := λ x y,
@coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩)
(edist_dist : ∀ x y : α,
edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
(to_bornology : bornology α := bornology.of_dist dist dist_self dist_comm dist_triangle)
(cobounded_sets : (bornology.cobounded α).sets =
{ s | ∃ C, ∀ ⦃x⦄, x ∈ sᶜ → ∀ ⦃y⦄, y ∈ sᶜ → dist x y ≤ C } . control_laws_tac)
/-- Two pseudo metric space structures with the same distance function coincide. -/
@[ext] lemma pseudo_metric_space.ext {α : Type*} {m m' : pseudo_metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
unfreezingI { rcases m, rcases m' },
dsimp at h,
unfreezingI { subst h },
congr,
{ ext x y : 2,
dsimp at m_edist_dist m'_edist_dist,
simp [m_edist_dist, m'_edist_dist] },
{ dsimp at m_uniformity_dist m'_uniformity_dist,
rw ← m'_uniformity_dist at m_uniformity_dist,
exact uniform_space_eq m_uniformity_dist },
{ ext1,
dsimp at m_cobounded_sets m'_cobounded_sets,
rw ← m'_cobounded_sets at m_cobounded_sets,
exact filter_eq m_cobounded_sets }
end
variables [pseudo_metric_space α]
attribute [priority 100, instance] pseudo_metric_space.to_uniform_space
attribute [priority 100, instance] pseudo_metric_space.to_bornology
@[priority 200] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩
/-- Construct a pseudo-metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) :
pseudo_metric_space α :=
{ dist := dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
to_uniform_space := { is_open_uniformity := begin
dsimp only [uniform_space.core_of_dist],
intros s,
change is_open s ↔ _,
rw H s,
refine forall₂_congr (λ x x_in, _),
erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff,
{ refine exists₂_congr (λ ε ε_pos, _),
simp only [prod.forall, set_of_subset_set_of],
split,
{ rintros h _ y H rfl,
exact h y H },
{ intros h y hxy,
exact h _ _ hxy rfl } },
{ exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ },
{ apply_instance }
end,
..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle },
uniformity_dist := rfl,
to_bornology := bornology.of_dist dist dist_self dist_comm dist_triangle,
cobounded_sets := rfl }
@[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x
theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
pseudo_metric_space.edist_dist x y
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
pseudo_metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 }
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 }
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico_self, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl
... = ∑ i in finset.Ico m (n+1), _ :
by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle
@[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b :=
abs_of_nonneg dist_nonneg
/-- A version of `has_dist` that takes value in `ℝ≥0`. -/
class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0)
export has_nndist (nndist)
/-- Distance as a nonnegative real number. -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] }
@[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y :=
(edist_nndist x y).symm
@[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} :
edist x y < c ↔ nndist x y < c :=
by rw [edist_nndist, ennreal.coe_lt_coe]
@[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} :
edist x y ≤ c ↔ nndist x y ≤ c :=
by rw [edist_nndist, ennreal.coe_le_coe]
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ :=
(edist_dist x y).symm ▸ ennreal.of_real_lt_top
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
@[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y :=
(dist_nndist x y).symm
@[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} :
dist x y < c ↔ nndist x y < c :=
iff.rfl
@[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} :
dist x y ≤ c ↔ nndist x y ≤ c :=
iff.rfl
@[simp] lemma edist_lt_of_real {x y : α} {r : ℝ} : edist x y < ennreal.of_real r ↔ dist x y < r :=
by rw [edist_dist, ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg]
@[simp] lemma edist_le_of_real {x y : α} {r : ℝ} (hr : 0 ≤ r) :
edist x y ≤ ennreal.of_real r ↔ dist x y ≤ r :=
by rw [edist_dist, ennreal.of_real_le_of_real_iff hr]
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) :=
by rw [dist_nndist, real.to_nnreal_coe]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
dist_triangle _ _ _
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
dist_triangle_left _ _ _
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
dist_triangle_right _ _ _
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate pseudometric space as a topology -/
variables {x y z : α} {δ ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw [dist_comm, mem_ball]
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
dist_nonneg.trans_lt hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
@[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε :=
⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩
@[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt]
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty]
/-- If a point belongs to an open ball, then there is a strictly smaller radius whose ball also
contains it.
See also `exists_lt_subset_ball`. -/
lemma exists_lt_mem_ball_of_mem_ball (h : x ∈ ball y ε) : ∃ ε' < ε, x ∈ ball y ε' :=
begin
simp only [mem_ball] at h ⊢,
exact ⟨(ε + dist x y) / 2, by linarith, by linarith⟩,
end
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
@[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x)
@[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ :=
Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn,
hn.trans (lt_add_one _)
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by rw [dist_comm, mem_closed_ball]
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl
theorem mem_sphere' : y ∈ sphere x ε ↔ dist x y = ε := by rw [dist_comm, mem_sphere]
theorem ne_of_mem_sphere (h : y ∈ sphere x ε) (hε : ε ≠ 0) : y ≠ x :=
by { contrapose! hε, symmetry, simpa [hε] using h }
theorem sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
sphere x ε = ∅ :=
set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, ne_of_mem_sphere hy hε (subsingleton.elim _ _)
theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
is_empty (sphere x ε) :=
by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α]
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
@[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε :=
⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩
@[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le]
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
lemma closed_ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (closed_ball x δ) (ball y ε) :=
λ a ha, (h.trans $ dist_triangle_left _ _ _).not_lt $ add_lt_add_of_le_of_lt ha.1 ha.2
lemma ball_disjoint_closed_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (closed_ball y ε) :=
(closed_ball_disjoint_ball $ by rwa [add_comm, dist_comm]).symm
lemma ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (ball y ε) :=
(closed_ball_disjoint_ball h).mono_left ball_subset_closed_ball
lemma closed_ball_disjoint_closed_ball (h : δ + ε < dist x y) :
disjoint (closed_ball x δ) (closed_ball y ε) :=
λ a ha, h.not_le $ (dist_triangle_left _ _ _).trans $ add_le_add ha.1 ha.2
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm]
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by rw [mem_ball', mem_ball]
theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε :=
by rw [mem_closed_ball', mem_closed_ball]
theorem mem_sphere_comm : x ∈ sphere y ε ↔ y ∈ sphere x ε :=
by rw [mem_sphere', mem_sphere]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... < ε₁ + dist x y : add_lt_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... ≤ ε₁ + dist x y : add_le_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_ball (h : ε₁ < ε₂) :
closed_ball x ε₁ ⊆ ball x ε₂ :=
λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h
lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball
(h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y ≤ ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2
lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2
lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
begin
rw inter_comm at h,
rw [add_comm, dist_comm],
exact dist_lt_add_of_nonempty_closed_ball_inter_ball h
end
lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
dist_lt_add_of_nonempty_closed_ball_inter_ball $
h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl)
@[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x)
lemma Union_inter_closed_ball_nat (s : set α) (x : α) :
(⋃ (n : ℕ), s ∩ closed_ball x n) = s :=
by rw [← inter_Union, Union_closed_ball_nat, inter_univ]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
/-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for
all points. -/
lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z :=
frequently_iff.1 H (Ici_mem_at_top (dist y x)),
exact h _ hR
end
/-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all
points. -/
lemma forall_of_forall_mem_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z :=
frequently_iff.1 H (Ioi_mem_at_top (dist y x)),
exact h _ hR
end
theorem is_bounded_iff {s : set α} :
is_bounded s ↔ ∃ C : ℝ, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
by rw [is_bounded_def, ← filter.mem_sets, (@pseudo_metric_space.cobounded_sets α _).out,
mem_set_of_eq, compl_compl]
theorem is_bounded_iff_eventually {s : set α} :
is_bounded s ↔ ∀ᶠ C in at_top, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
is_bounded_iff.trans ⟨λ ⟨C, h⟩, eventually_at_top.2 ⟨C, λ C' hC' x hx y hy, (h hx hy).trans hC'⟩,
eventually.exists⟩
theorem is_bounded_iff_exists_ge {s : set α} (c : ℝ) :
is_bounded s ↔ ∃ C, c ≤ C ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
⟨λ h, ((eventually_ge_at_top c).and (is_bounded_iff_eventually.1 h)).exists,
λ h, is_bounded_iff.2 $ h.imp $ λ _, and.right⟩
theorem is_bounded_iff_nndist {s : set α} :
is_bounded s ↔ ∃ C : ℝ≥0, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → nndist x y ≤ C :=
by simp only [is_bounded_iff_exists_ge 0, nnreal.exists, ← nnreal.coe_le_coe, ← dist_nndist,
nnreal.coe_mk, exists_prop]
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← pseudo_metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n,
by exact_mod_cast hn.le⟩)
theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) :=
metric.mk_uniformity_basis (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) :
(𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) :=
metric.mk_uniformity_basis (λ r, and.left) $ λ r hr,
⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩,
min_le_left _ _⟩
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) :=
metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist
lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε :=
metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le
theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩
/-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem eventually_nhds_iff {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y :=
mem_nhds_iff
lemma eventually_nhds_iff_ball {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y :=
mem_nhds_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1)
theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1)
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open_ball.mem_nhds (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) :
closed_ball c ε ∈ 𝓝 x :=
mem_of_superset (is_open_ball.mem_nhds h) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ,
forall_congr $ λ x, by simp; itauto
theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [pseudo_metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
/--
A variant of `tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_max_order β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε :=
(at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} :
is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x :=
by simp [is_open_iff, subset_singleton_iff, mem_ball]
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball
centered at `x` and intersecting `s` only at `x`. -/
lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.ball x ε ∩ s = {x} :=
nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball
of positive radius centered at `x` and intersecting `s` only at `x`. -/
lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.closed_ball x ε ∩ s = {x} :=
nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx
lemma _root_.dense.exists_dist_lt {s : set α} (hs : dense s) (x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y ∈ s, dist x y < ε :=
begin
have : (ball x ε).nonempty, by simp [hε],
simpa only [mem_ball'] using hs.exists_mem_open is_open_ball this
end
lemma _root_.dense_range.exists_dist_lt {β : Type*} {f : β → α} (hf : dense_range f)
(x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y, dist x (f y) < ε :=
exists_range_iff.1 (hf.exists_dist_lt x hε)
end metric
open metric
/-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma pseudo_metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
pseudo_metric.uniformity_basis_edist.eq_binfi
/-- A pseudometric space induces a pseudoemetric space -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹pseudo_metric_space α› }
/-- In a pseudometric space, an open ball of infinite radius is the whole space -/
lemma metric.eball_top_eq_univ (x : α) :
emetric.ball x ∞ = set.univ :=
set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x)
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
@[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ :=
eq_univ_of_forall $ λ y, edist_lt_top _ _
lemma metric.inseparable_iff {x y : α} : inseparable x y ↔ dist x y = 0 :=
by rw [emetric.inseparable_iff, edist_nndist, dist_nndist, ennreal.coe_eq_zero,
nnreal.coe_eq_zero]
/-- Build a new pseudometric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
pseudo_metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans pseudo_metric_space.uniformity_dist }
lemma pseudo_metric_space.replace_uniformity_eq {α} [U : uniform_space α]
(m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new pseudo metric space from an old one where the bundled topological structure is
provably (but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def pseudo_metric_space.replace_topology {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
pseudo_metric_space γ :=
@pseudo_metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma pseudo_metric_space.replace_topology_eq {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the
distance is given separately, to be able to prescribe some expression which is not defeq to the
push-forward of the edistance to reals. -/
def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
pseudo_metric_space α :=
let m : pseudo_metric_space α :=
{ dist := dist,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := edist,
edist_dist := λ x y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the emetric space. -/
def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α]
(h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α :=
pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new pseudometric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_bornology {α} [B : bornology α] (m : pseudo_metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space α :=
{ to_bornology := B,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, (H s).trans $
by rw [is_bounded_iff, mem_set_of_eq, compl_compl],
.. m }
lemma pseudo_metric_space.replace_bornology_eq {α} [m : pseudo_metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
(λ n, {p:α×α | dist p.1 p.2 < B n}) (λ n, dist_mem_uniformity $ hB n) H
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a pseudometric space. -/
noncomputable instance real.pseudo_metric_space : pseudo_metric_space ℝ :=
{ dist := λx y, |x - y|,
dist_self := by simp [abs_zero],
dist_comm := assume x y, abs_sub_comm _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl
theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl
theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| :=
by simp [real.dist_eq]
theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist x y ≤ dist x z :=
by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h
theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist y z ≤ dist x z :=
by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h
theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y')
(hy : y ∈ interval x' y') : dist x y ≤ dist x' y' :=
abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap)
theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ y' - x' :=
by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub]
using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy)
theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) :
dist x y ≤ 1 :=
by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x,
by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm]
lemma real.ball_eq_Ioo (x r : ℝ) : ball x r = Ioo (x - r) (x + r) :=
set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq,
abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt]
lemma real.closed_ball_eq_Icc {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.closed_ball_eq_Icc, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
section metric_ordered
variables [preorder α] [compact_Icc_space α]
lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) :=
is_compact_Icc.totally_bounded
lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) :=
totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) :=
totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) :=
totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b)
end metric_ordered
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
/-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball
`closed_ball x r` is contained in `u`. -/
lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) :
∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u :=
begin
obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u :=
nhds_basis_closed_ball.mem_iff.1 hu,
have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos,
filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε,
end
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the pseudometric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- In a pseudometric space, unifom Cauchy sequences are characterized by the fact that, eventually,
the distance between all its elements is uniformly, arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.uniform_cauchy_seq_on_iff {γ : Type*}
{F : β → γ → α} {s : set γ} :
uniform_cauchy_seq_on F at_top s ↔
∀ ε : ℝ, ε > 0 → ∃ (N : β), ∀ m : β, m ≥ N → ∀ n : β, n ≥ N → ∀ x : γ, x ∈ s →
dist (F m x) (F n x) < ε :=
begin
split,
{ intros h ε hε,
let u := { a : α × α | dist a.fst a.snd < ε },
have hu : u ∈ 𝓤 α := metric.mem_uniformity_dist.mpr ⟨ε, hε, (λ a b, by simp)⟩,
rw ←@filter.eventually_at_top_prod_self' _ _ _
(λ m, ∀ x : γ, x ∈ s → dist (F m.fst x) (F m.snd x) < ε),
specialize h u hu,
rw prod_at_top_at_top_eq at h,
exact h.mono (λ n h x hx, set.mem_set_of_eq.mp (h x hx)), },
{ intros h u hu,
rcases (metric.mem_uniformity_dist.mp hu) with ⟨ε, hε, hab⟩,
rcases h ε hε with ⟨N, hN⟩,
rw [prod_at_top_at_top_eq, eventually_at_top],
use (N, N),
intros b hb x hx,
rcases hb with ⟨hbl, hbr⟩,
exact hab (hN b.fst hbl.ge b.snd hbr.ge x hx), },
end
/-- If the distance between `s n` and `s m`, `n ≤ m` is bounded above by `b n`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0' {s : β → α} (b : β → ℝ)
(h : ∀ n m : β, n ≤ m → dist (s n) (s m) ≤ b n) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff'.2 $ λ ε ε0,
(h₀.eventually (gt_mem_nhds ε0)).exists.imp $ λ N hN n hn,
calc dist (s n) (s N) = dist (s N) (s n) : dist_comm _ _
... ≤ b N : h _ _ hn
... < ε : hN
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
cauchy_seq_of_le_tendsto_0' b (λ n m hnm, h _ _ _ le_rfl hnm) h₀
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_rfl, le_rfl⟩, dist_self _⟩,
have S0 := λ n, le_cSup (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ (le_trans hn hm') _ (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Pseudometric space structure pulled back by a function. -/
def pseudo_metric_space.induced {α β} (f : α → β)
(m : pseudo_metric_space β) : pseudo_metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine compl_surjective.forall.2 (λ s, compl_mem_comap.trans $ mem_uniformity_dist.trans _),
simp only [mem_compl_iff, @imp_not_comm _ (_ ∈ _), ← prod.forall', prod.mk.eta, ball_image_iff]
end,
to_bornology := bornology.induced f,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s,
by simp only [compl_mem_comap, filter.mem_sets, ← is_bounded_def, mem_set_of_eq, compl_compl,
is_bounded_iff, ball_image_iff] }
/-- Pull back a pseudometric space structure by an inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `topological_space`
structure. -/
def inducing.comap_pseudo_metric_space {α β} [topological_space α] [pseudo_metric_space β]
{f : α → β} (hf : inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_topology hf.induced
/-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space`
structure. -/
def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β]
(f : α → β) (h : uniform_inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm
instance subtype.pseudo_metric_space {p : α → Prop} : pseudo_metric_space (subtype p) :=
pseudo_metric_space.induced coe ‹_›
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
theorem subtype.nndist_eq {p : α → Prop} (x y : subtype p) : nndist x y = nndist (x : α) y := rfl
namespace mul_opposite
@[to_additive]
instance : pseudo_metric_space (αᵐᵒᵖ) := pseudo_metric_space.induced mul_opposite.unop ‹_›
@[simp, to_additive] theorem dist_unop (x y : αᵐᵒᵖ) : dist (unop x) (unop y) = dist x y := rfl
@[simp, to_additive] theorem dist_op (x y : α) : dist (op x) (op y) = dist x y := rfl
@[simp, to_additive] theorem nndist_unop (x y : αᵐᵒᵖ) : nndist (unop x) (unop y) = nndist x y := rfl
@[simp, to_additive] theorem nndist_op (x y : α) : nndist (op x) (op y) = nndist x y := rfl
end mul_opposite
section nnreal
noncomputable instance : pseudo_metric_space ℝ≥0 := subtype.pseudo_metric_space
lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl
lemma nnreal.nndist_eq (a b : ℝ≥0) :
nndist a b = max (a - b) (b - a) :=
begin
/- WLOG, `b ≤ a`. `wlog h : b ≤ a` works too but it is much slower because Lean tries to prove one
case from the other and fails; `tactic.skip` tells Lean not to try. -/
wlog h : b ≤ a := le_total b a using [a b, b a] tactic.skip,
{ rw [← nnreal.coe_eq, ← dist_nndist, nnreal.dist_eq, tsub_eq_zero_iff_le.2 h,
max_eq_left (zero_le $ a - b), ← nnreal.coe_sub h, abs_of_nonneg (a - b).coe_nonneg] },
{ rwa [nndist_comm, max_comm] }
end
@[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z :=
by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le']
@[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z :=
by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, }
lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b :=
begin
suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b),
{ exact nnreal.coe_le_coe.mp this, },
linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))],
end
end nnreal
section ulift
variables [pseudo_metric_space β]
instance : pseudo_metric_space (ulift β) :=
pseudo_metric_space.induced ulift.down ‹_›
lemma ulift.dist_eq (x y : ulift β) : dist x y = dist x.down y.down := rfl
lemma ulift.nndist_eq (x y : ulift β) : nndist x y = nndist x.down y.down := rfl
@[simp] lemma ulift.dist_up_up (x y : β) : dist (ulift.up x) (ulift.up y) = dist x y := rfl
@[simp] lemma ulift.nndist_up_up (x y : β) : nndist (ulift.up x) (ulift.up y) = nndist x y := rfl
end ulift
section prod
variables [pseudo_metric_space β]
noncomputable instance prod.pseudo_metric_space_max :
pseudo_metric_space (α × β) :=
(pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λ x y : α × β, max (dist x.1 y.1) (dist x.2 y.2))
(λ x y, (max_lt (edist_lt_top _ _) (edist_lt_top _ _)).ne)
(λ x y, by simp only [dist_edist, ← ennreal.to_real_max (edist_ne_top _ _) (edist_ne_top _ _),
prod.edist_eq])).replace_bornology $
λ s, by { simp only [← is_bounded_image_fst_and_snd, is_bounded_iff_eventually, ball_image_iff,
← eventually_and, ← forall_and_distrib, ← max_le_iff], refl }
lemma prod.dist_eq {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
@[simp]
lemma dist_prod_same_left {x : α} {y₁ y₂ : β} : dist (x, y₁) (x, y₂) = dist y₁ y₂ :=
by simp [prod.dist_eq, dist_nonneg]
@[simp]
lemma dist_prod_same_right {x₁ x₂ : α} {y : β} : dist (x₁, y) (x₂, y) = dist x₁ x₂ :=
by simp [prod.dist_eq, dist_nonneg]
theorem ball_prod_same (x : α) (y : β) (r : ℝ) :
ball x r ×ˢ ball y r = ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
theorem closed_ball_prod_same (x : α) (y : β) (r : ℝ) :
closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
@[continuity]
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
@[continuity]
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in pseudometric spaces-/
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {s : set α} (hs : is_closed s) {a : α} :
a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
lemma closed_ball_zero' (x : α) : closed_ball x 0 = closure {x} :=
subset.antisymm
(λ y hy, mem_closure_iff.2 $ λ ε ε0, ⟨x, mem_singleton x, (mem_closed_ball.1 hy).trans_lt ε0⟩)
(closure_minimal (singleton_subset_iff.2 (dist_self x).le) is_closed_ball)
lemma dense_iff {s : set α} :
dense s ↔ ∀ x, ∀ r > 0, (ball x r ∩ s).nonempty :=
forall_congr $ λ x, by simp only [mem_closure_iff, set.nonempty, exists_prop, mem_inter_eq,
mem_ball', and_comm]
lemma dense_range_iff {f : β → α} :
dense_range f ↔ ∀ x, ∀ r > 0, ∃ y, dist x (f y) < r :=
forall_congr $ λ x, by simp only [mem_closure_iff, exists_range_iff]
/-- If a set `s` is separable, then the corresponding subtype is separable in a metric space.
This is not obvious, as the countable set whose closure covers `s` does not need in general to
be contained in `s`. -/
lemma _root_.topological_space.is_separable.separable_space {s : set α} (hs : is_separable s) :
separable_space s :=
begin
classical,
rcases eq_empty_or_nonempty s with rfl|⟨⟨x₀, x₀s⟩⟩,
{ haveI : encodable (∅ : set α) := fintype.to_encodable ↥∅, exact encodable.to_separable_space },
rcases hs with ⟨c, hc, h'c⟩,
haveI : encodable c := hc.to_encodable,
obtain ⟨u, -, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧
tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ),
let f : c × ℕ → α := λ p, if h : (metric.ball (p.1 : α) (u p.2) ∩ s).nonempty then h.some else x₀,
have fs : ∀ p, f p ∈ s,
{ rintros ⟨y, n⟩,
by_cases h : (ball (y : α) (u n) ∩ s).nonempty,
{ simpa only [f, h, dif_pos] using h.some_spec.2 },
{ simpa only [f, h, not_false_iff, dif_neg] } },
let g : c × ℕ → s := λ p, ⟨f p, fs p⟩,
apply separable_space_of_dense_range g,
apply metric.dense_range_iff.2,
rintros ⟨x, xs⟩ r (rpos : 0 < r),
obtain ⟨n, hn⟩ : ∃ n, u n < r / 2 := ((tendsto_order.1 u_lim).2 _ (half_pos rpos)).exists,
obtain ⟨z, zc, hz⟩ : ∃ z ∈ c, dist x z < u n :=
metric.mem_closure_iff.1 (h'c xs) _ (u_pos n),
refine ⟨(⟨z, zc⟩, n), _⟩,
change dist x (f (⟨z, zc⟩, n)) < r,
have A : (metric.ball z (u n) ∩ s).nonempty := ⟨x, hz, xs⟩,
dsimp [f],
simp only [A, dif_pos],
calc dist x A.some
≤ dist x z + dist z A.some : dist_triangle _ _ _
... < r/2 + r/2 : add_lt_add (hz.trans hn) ((metric.mem_ball'.1 A.some_spec.1).trans hn)
... = r : add_halves _
end
/-- The preimage of a separable set by an inducing map is separable. -/
protected lemma _root_.inducing.is_separable_preimage {f : β → α} [topological_space β]
(hf : inducing f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
begin
haveI : second_countable_topology s,
{ haveI : separable_space s := hs.separable_space,
exact uniform_space.second_countable_of_separable _ },
let g : f ⁻¹' s → s := cod_restrict (f ∘ coe) s (λ x, x.2),
have : inducing g := (hf.comp inducing_coe).cod_restrict _,
haveI : second_countable_topology (f ⁻¹' s) := this.second_countable_topology,
rw show f ⁻¹' s = coe '' (univ : set (f ⁻¹' s)),
by simpa only [image_univ, subtype.range_coe_subtype],
exact (is_separable_of_separable_space _).image continuous_subtype_coe
end
protected lemma _root_.embedding.is_separable_preimage {f : β → α} [topological_space β]
(hf : embedding f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
hf.to_inducing.is_separable_preimage hs
/-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/
lemma _root_.continuous_on.is_separable_image [topological_space β] {f : α → β} {s : set α}
(hf : continuous_on f s) (hs : is_separable s) :
is_separable (f '' s) :=
begin
rw show f '' s = s.restrict f '' univ, by ext ; simp,
exact (is_separable_univ_iff.2 hs.separable_space).image
(continuous_on_iff_continuous_restrict.1 hf),
end
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
/-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/
noncomputable instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) :=
begin
/- we construct the instance from the pseudoemetric space instance to avoid checking again that
the uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine (pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λf g : Π b, π b, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ))
(λ f g, _) (λ f g, _)).replace_bornology (λ s, _),
show edist f g ≠ ⊤,
from ne_of_lt ((finset.sup_lt_iff bot_lt_top).2 $ λ b hb, edist_lt_top _ _),
show ↑(sup univ (λ b, nndist (f b) (g b))) = (sup univ (λ b, edist (f b) (g b))).to_real,
by simp only [edist_nndist, ← ennreal.coe_finset_sup, ennreal.coe_to_real],
show (@is_bounded _ pi.bornology s ↔ @is_bounded _ pseudo_metric_space.to_bornology _),
{ simp only [← is_bounded_def, is_bounded_iff_eventually, ← forall_is_bounded_image_eval_iff,
ball_image_iff, ← eventually_all, function.eval_apply, @dist_nndist (π _)],
refine eventually_congr ((eventually_ge_at_top 0).mono $ λ C hC, _),
lift C to ℝ≥0 using hC,
refine ⟨λ H x hx y hy, nnreal.coe_le_coe.2 $ finset.sup_le $ λ b hb, H b x hx y hy,
λ H b x hx y hy, nnreal.coe_le_coe.2 _⟩,
simpa only using finset.sup_le_iff.1 (nnreal.coe_le_coe.1 $ H hx hy) b (finset.mem_univ b) }
end
lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) :=
nnreal.eq rfl
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl
@[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b :=
by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b)
@[simp] lemma nndist_pi_const [nonempty β] (a b : α) :
nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b
lemma nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} :
nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r :=
by simp [nndist_pi_def]
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to ℝ≥0 using hr.le,
simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)],
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to ℝ≥0 using hr,
exact nndist_pi_le_iff
end
lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g :=
by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) }
lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g :=
by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b]
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'`
for a version assuming `nonempty β` instead of `0 < r`. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi`
for a version assuming `0 < r` instead of `nonempty β`. -/
lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
(lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr]
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'`
for a version assuming `nonempty β` instead of `0 ≤ r`. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
by { ext p, simp [dist_pi_le_iff hr] }
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi`
for a version assuming `0 ≤ r` instead of `nonempty β`. -/
lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
(le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr]
@[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) :=
eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above]
@[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) :=
by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max]
lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ dist x' y' :=
begin
refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans
(dist_le_pi_dist _ _ b)); refine Icc_subset_interval _,
exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩]
end
end pi
section compact
/-- Any compact set in a pseudometric space can be covered by finitely many balls of a given
positive radius -/
lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, set.finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A pseudometric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [pseudo_metric_space α] : Prop :=
(is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
export proper_space (is_compact_closed_ball)
/-- In a proper pseudometric space, all spheres are compact. -/
lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
is_compact (sphere x r) :=
compact_of_is_closed_subset (is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball
/-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/
instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
compact_space (sphere x r) :=
is_compact_iff_compact_space.mp (is_compact_sphere _ _)
/-- A proper pseudo metric space is sigma compact, and therefore second countable. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
-- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't
-- add an instance for `sigma_compact_space`.
suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α,
rcases em (nonempty α) with ⟨⟨x⟩⟩|hn,
{ exact ⟨⟨λ n, closed_ball x n, λ n, is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ },
{ exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ }
end
lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) :
tendsto (λ y, dist y x) (cocompact α) at_top :=
(has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr,
⟨closed_ball x r, is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩
lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) :
tendsto (dist x) (cocompact α) at_top :=
by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R le_rfl).inter_right is_closed_ball }
end⟩
/- A compact pseudometric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, is_closed_ball.is_compact⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $
λ x ε ε0, is_compact_closed_ball _ _
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 :=
(metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y yt x xt).le),
rcases (compact_iff_totally_bounded_complete.1 (is_compact_closed_ball x 1)).2 f hf
(le_principal_iff.2 this) with ⟨y, -, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply is_compact_univ_pi (λb, _),
apply (h b).is_compact_closed_ball
end
variables [proper_space α] {x : α} {r : ℝ} {s : set α}
/-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty
ball with the same center and a strictly smaller radius that includes `s`. -/
lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' ∈ Ioo 0 r, s ⊆ ball x r' :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne },
{ exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ },
have : is_compact s,
from compact_of_is_closed_subset (is_compact_closed_ball x r) hs
(subset.trans h ball_subset_closed_ball),
obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x),
from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on,
have hyr : dist y x < r, from h hys,
rcases exists_between hyr with ⟨r', hyr', hrr'⟩,
exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩
end
/-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same
center and a strictly smaller radius that includes `s`. -/
lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' < r, s ⊆ ball x r' :=
begin
cases le_or_lt r 0 with hr hr,
{ rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s },
exact (exists_lt r).imp (λ r' hr', ⟨hr', empty_subset _⟩) },
{ exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) }
end
end proper_space
lemma is_compact.is_separable {s : set α} (hs : is_compact s) :
is_separable s :=
begin
haveI : compact_space s := is_compact_iff_compact_space.mp hs,
exact is_separable_of_separable_space_subtype s,
end
namespace metric
section second_countable
open topological_space
/-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which
is `ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, s.countable ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _),
rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩,
choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0),
refine ⟨s, hsc, Union₂_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩,
exact_mod_cast hyx x
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a pseudometric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y hy z hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.mono ball_subset_closed_ball
/-- Spheres are bounded -/
lemma bounded_sphere : bounded (sphere x r) :=
bounded_closed_ball.mono sphere_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y hy x hx) _⟩ } },
{ exact bounded_closed_ball.mono hC }
end
lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r :=
(bounded_iff_subset_ball c).1 h
lemma bounded.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r :=
begin
rcases h.subset_ball c with ⟨r, hr⟩,
refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩,
exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _))
end
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
let ⟨C, h⟩ := h in
⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb
$ ball_mem_comm.mp h⟩
alias bounded_closure_of_bounded ← bounded.closure
@[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s :=
⟨λ h, h.mono subset_closure, λ h, h.closure⟩
/-- The union of two bounded sets is bounded. -/
lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) :=
begin
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end
/-- The union of two sets is bounded iff each of the sets is bounded. -/
@[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : I.finite) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
protected lemma bounded.prod [pseudo_metric_space β] {s : set α} {t : set β}
(hs : bounded s) (ht : bounded t) : bounded (s ×ˢ t) :=
begin
refine bounded_iff_mem_bounded.mpr (λ x hx, _),
rcases hs.subset_ball x.1 with ⟨rs, hrs⟩,
rcases ht.subset_ball x.2 with ⟨rt, hrt⟩,
suffices : s ×ˢ t ⊆ closed_ball x (max rs rt),
from bounded_closed_ball.mono this,
rw [← @prod.mk.eta _ _ x, ← closed_ball_prod_same],
exact prod_mono (hrs.trans $ closed_ball_subset_closed_ball $ le_max_left _ _)
(hrt.trans $ closed_ball_subset_closed_ball $ le_max_right _ _)
end
/-- A totally bounded set is bounded -/
lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s :=
-- We cover the totally bounded set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in
bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A compact set is bounded -/
lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s :=
-- A compact set is totally bounded, thus bounded
h.totally_bounded.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : s.finite) : bounded s :=
h.is_compact.bounded
alias bounded_of_finite ← _root_.set.finite.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩,
by rintro H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩; exact H x y⟩
lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α}
(hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) :
bounded (range f) :=
begin
rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one
with ⟨s, hsf, hs1⟩,
rw [← image_univ, ← union_compl_self s, image_union, bounded_union],
use [(hsf.image f).bounded, 1],
rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩)
end
lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2
lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) :=
bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top
lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $
(hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.mono (subset_univ _)
lemma bounded_range_of_tendsto {α : Type*} [pseudo_metric_space α] (u : ℕ → α) {x : α}
(hu : tendsto u at_top (𝓝 x)) :
bounded (range u) :=
hu.cauchy_seq.bounded_range
/-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/
lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) :
is_compact s :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) },
{ exact is_compact_empty },
{ rcases hb.subset_ball x with ⟨r, hr⟩,
exact compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr }
end
/-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/
lemma bounded.is_compact_closure [proper_space α] (h : bounded s) :
is_compact (closure s) :=
is_compact_of_is_closed_bounded is_closed_closure h.closure
/-- The **Heine–Borel theorem**:
In a proper Hausdorff space, a set is compact if and only if it is closed and bounded. -/
lemma compact_iff_closed_bounded [t2_space α] [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩
lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) :=
⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩
section conditionally_complete_linear_order
variables [preorder α] [compact_Icc_space α]
lemma bounded_Icc (a b : α) : bounded (Icc a b) :=
(totally_bounded_Icc a b).bounded
lemma bounded_Ico (a b : α) : bounded (Ico a b) :=
(totally_bounded_Ico a b).bounded
lemma bounded_Ioc (a b : α) : bounded (Ioc a b) :=
(totally_bounded_Ioc a b).bounded
lemma bounded_Ioo (a b : α) : bounded (Ioo a b) :=
(totally_bounded_Ioo a b).bounded
/-- In a pseudo metric space with a conditionally complete linear order such that the order and the
metric structure give the same topology, any order-bounded set is metric-bounded. -/
lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) :
bounded s :=
let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in
bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u)
end conditionally_complete_linear_order
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top $ ediam_le_of_forall_dist_le hC)
(λ h, ⟨diam s, λ x hx y hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
lemma ediam_univ_eq_top_iff_noncompact [proper_space α] :
emetric.diam (univ : set α) = ∞ ↔ noncompact_space α :=
by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not]
@[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] :
emetric.diam (univ : set α) = ∞ :=
ediam_univ_eq_top_iff_noncompact.mpr ‹_›
@[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] :
diam (univ : set α) = 0 :=
by simp [diam]
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ :=
by rwa [bounded_iff_ediam_ne_top, not_not] at h
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
by rw [diam, ediam_of_unbounded h, ennreal.top_to_real]
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.mono (subset_union_left _ _),
have ht : bounded t, from H.mono (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) :
diam s ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add (h ha) (h hb)
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h subset.rfl
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h ball_subset_closed_ball
/-- If a family of complete sets with diameter tending to `0` is such that each finite intersection
is nonempty, then the total intersection is also nonempty. -/
lemma _root_.is_complete.nonempty_Inter_of_nonempty_bInter {s : ℕ → set α} (h0 : is_complete (s 0))
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
begin
let u := λ N, (h N).some,
have I : ∀ n N, n ≤ N → u N ∈ s n,
{ assume n N hn,
apply mem_of_subset_of_mem _ ((h N).some_spec),
assume x hx,
simp only [mem_Inter] at hx,
exact hx n hn },
have : ∀ n, u n ∈ s 0 := λ n, I 0 n (zero_le _),
have : cauchy_seq u,
{ apply cauchy_seq_of_le_tendsto_0 _ _ h',
assume m n N hm hn,
exact dist_le_diam_of_mem (h's N) (I _ _ hm) (I _ _ hn) },
obtain ⟨x, hx, xlim⟩ : ∃ (x : α) (H : x ∈ s 0), tendsto (λ (n : ℕ), u n) at_top (𝓝 x) :=
cauchy_seq_tendsto_of_is_complete h0 (λ n, I 0 n (zero_le _)) this,
refine ⟨x, mem_Inter.2 (λ n, _)⟩,
apply (hs n).mem_of_tendsto xlim,
filter_upwards [Ici_mem_at_top n] with p hp,
exact I n p hp,
end
/-- In a complete space, if a family of closed sets with diameter tending to `0` is such that each
finite intersection is nonempty, then the total intersection is also nonempty. -/
lemma nonempty_Inter_of_nonempty_bInter [complete_space α] {s : ℕ → set α}
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
(hs 0).is_complete.nonempty_Inter_of_nonempty_bInter hs h's h h'
end diam
end metric
lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α :=
begin
refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _),
rcases hs.bounded.subset_ball x with ⟨r, hr⟩,
exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩
end
lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α :=
by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x
lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) :
comap (λ y, dist y x) at_top = cocompact α :=
(comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap
lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) :
comap (dist x) at_top = cocompact α :=
(comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap
lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α)
(h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) :=
by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff }
namespace int
open metric
/-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/
lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) :=
begin
refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _,
simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball],
change ∀ r : ℝ, (coe ⁻¹' (ball (0 : ℝ) r)).finite,
simp [real.ball_eq_Ioo, set.finite_Ioo],
end
end int
/-- We now define `metric_space`, extending `pseudo_metric_space`. -/
class metric_space (α : Type u) extends pseudo_metric_space α : Type u :=
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
/-- Two metric space structures with the same distance coincide. -/
@[ext] lemma metric_space.ext {α : Type*} {m m' : metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
have h' : m.to_pseudo_metric_space = m'.to_pseudo_metric_space := pseudo_metric_space.ext h,
unfreezingI { rcases m, rcases m' },
dsimp at h',
unfreezingI { subst h' },
end
/-- Construct a metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s)
(eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α :=
{ eq_of_dist_eq_zero := eq_of_dist_eq_zero,
..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H }
variables {γ : Type w} [metric_space γ]
theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
@[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y :=
by simpa only [not_iff_not] using dist_eq_zero
@[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
namespace metric
variables {x : γ} {s : set γ}
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
@[simp] lemma sphere_zero : sphere x 0 = {x} :=
set.ext $ λ y, dist_eq_zero
lemma subsingleton_closed_ball (x : γ) {r : ℝ} (hr : r ≤ 0) : (closed_ball x r).subsingleton :=
begin
rcases hr.lt_or_eq with hr|rfl,
{ rw closed_ball_eq_empty.2 hr, exact subsingleton_empty },
{ rw closed_ball_zero, exact subsingleton_singleton }
end
lemma subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).subsingleton :=
(subsingleton_closed_ball x hr).mono sphere_subset_closed_ball
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
@[priority 100] -- see Note [lower instance priority]
instance _root_.metric_space.to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-- If a `pseudo_metric_space` is a T₀ space, then it is a `metric_space`. -/
def of_t0_pseudo_metric_space (α : Type*) [pseudo_metric_space α] [t0_space α] :
metric_space α :=
{ eq_of_dist_eq_zero := λ x y hdist, inseparable.eq $ metric.inseparable_iff.2 hdist,
..‹pseudo_metric_space α› }
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space γ :=
emetric.of_t0_pseudo_emetric_space γ
lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε)
(hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s :=
is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs
lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α]
{ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) :
closed_embedding f :=
closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
/-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then
`f` is a uniform embedding with respect to the discrete uniformity on `β`. -/
lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α}
(hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f :=
uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
end metric
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
metric_space γ :=
{ eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, }
lemma metric_space.replace_uniformity_eq {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new metric space from an old one where the bundled topological structure is provably
(but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def metric_space.replace_topology {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
metric_space γ :=
@metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy,
by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new metric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_bornology {α} [B : bornology α] (m : metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space α :=
{ to_bornology := B,
.. pseudo_metric_space.replace_bornology _ H,
.. m }
lemma metric_space.replace_bornology_eq {α} [m : metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : metric_space β) : metric_space γ :=
{ eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
..pseudo_metric_space.induced f m.to_pseudo_metric_space }
/-- Pull back a metric space structure by a uniform embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/
@[reducible] def uniform_embedding.comap_metric_space
{α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) :
metric_space α :=
(metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm
/-- Pull back a metric space structure by an embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/
@[reducible] def embedding.comap_metric_space
{α β} [topological_space α] [metric_space β] (f : α → β) (h : embedding f) :
metric_space α :=
begin
letI : uniform_space α := embedding.comap_uniform_space f h,
exact uniform_embedding.comap_metric_space f (h.to_uniform_embedding f),
end
instance subtype.metric_space {α : Type*} {p : α → Prop} [metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe subtype.coe_injective ‹_›
@[to_additive] instance {α : Type*} [metric_space α] : metric_space (αᵐᵒᵖ) :=
metric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_›
local attribute [instance] filter.unique
instance : metric_space empty :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := empty.uniform_space,
uniformity_dist := subsingleton.elim _ _ }
instance : metric_space punit.{u + 1} :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := punit.uniform_space,
uniformity_dist :=
begin
simp only,
haveI : ne_bot (⨅ ε > (0 : ℝ), 𝓟 {p : punit.{u + 1} × punit.{u + 1} | 0 < ε}),
{ exact @uniformity.ne_bot _ (uniform_space_of_dist (λ _ _, 0) (λ _, rfl) (λ _ _, rfl)
(λ _ _ _, by rw zero_add)) _ },
refine (eq_top_of_ne_bot _).trans (eq_top_of_ne_bot _).symm,
end}
section real
/-- Instantiate the reals as a metric space. -/
noncomputable instance real.metric_space : metric_space ℝ :=
{ eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h,
..real.pseudo_metric_space }
end real
section nnreal
noncomputable instance : metric_space ℝ≥0 := subtype.metric_space
end nnreal
instance [metric_space β] : metric_space (ulift β) :=
metric_space.induced ulift.down ulift.down_injective ‹_›
section prod
noncomputable instance prod.metric_space_max [metric_space β] : metric_space (γ × β) :=
{ eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
..prod.pseudo_metric_space_max, }
end prod
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
noncomputable instance metric_space_pi : metric_space (Πb, π b) :=
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
{ eq_of_dist_eq_zero := assume f g eq0,
begin
have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero],
have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1,
simp only [finset.sup_le_iff] at eq2,
exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b)
end,
..pseudo_metric_space_pi }
end pi
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
section eq_rel
/-- The canonical equivalence relation on a pseudometric space. -/
def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α :=
setoid.mk (λx y, dist x y = 0)
begin
unfold equivalence,
repeat { split },
{ exact pseudo_metric_space.dist_self },
{ assume x y h, rwa pseudo_metric_space.dist_comm },
{ assume x y z hxy hyz,
refine le_antisymm _ dist_nonneg,
calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _
... = 0 + 0 : by rw [hxy, hyz]
... = 0 : by simp }
end
local attribute [instance] pseudo_metric.dist_setoid
/-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/
@[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* :=
quotient (pseudo_metric.dist_setoid α)
instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] :
has_dist (pseudo_metric_quot α) :=
{ dist := quotient.lift₂ (λp q : α, dist p q)
begin
assume x y x' y' hxx' hyy',
have Hxx' : dist x x' = 0 := hxx',
have Hyy' : dist y y' = 0 := hyy',
have A : dist x y ≤ dist x' y' := calc
dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y : by simp [Hxx']
... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'],
have B : dist x' y' ≤ dist x y := calc
dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx']
... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y : by simp [Hyy'],
exact le_antisymm A B
end }
lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) :
dist ⟦p⟧ ⟦q⟧ = dist p q := rfl
instance metric_space_quot {α : Type u} [pseudo_metric_space α] :
metric_space (pseudo_metric_quot α) :=
{ dist_self := begin
refine quotient.ind (λy, _),
exact pseudo_metric_space.dist_self _
end,
eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H),
dist_comm :=
λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _),
dist_triangle :=
λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) }
end eq_rel
|
26d5c33e44661ccb308426d6be53f13ae5cc911a | 367134ba5a65885e863bdc4507601606690974c1 | /src/geometry/manifold/times_cont_mdiff_map.lean | 03006b28d4ab3c9123fb304b6ee6ea7a096e4db7 | [
"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 | 3,277 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Nicolò Cavalleri.
-/
import geometry.manifold.times_cont_mdiff
import topology.continuous_map
/-!
# Smooth bundled map
In this file we define the type `times_cont_mdiff_map` of `n` times continuously differentiable
bundled maps.
-/
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]
{H' : Type*} [topological_space H']
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(M : Type*) [topological_space M] [charted_space H M]
(M' : Type*) [topological_space M'] [charted_space H' M']
{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'']
(n : with_top ℕ)
/-- Bundled `n` times continuously differentiable maps. -/
@[protect_proj]
structure times_cont_mdiff_map :=
(to_fun : M → M')
(times_cont_mdiff_to_fun : times_cont_mdiff I I' n to_fun)
/-- Bundled smooth maps. -/
@[reducible] def smooth_map := times_cont_mdiff_map I I' M M' ⊤
localized "notation `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` :=
times_cont_mdiff_map I I' M M' n" in manifold
localized "notation `C^` n `⟮` I `, ` M `; ` k `⟯` :=
times_cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold
open_locale manifold
namespace times_cont_mdiff_map
variables {I} {I'} {M} {M'} {n}
instance : has_coe_to_fun C^n⟮I, M; I', M'⟯ := ⟨_, times_cont_mdiff_map.to_fun⟩
instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') :=
⟨λ f, ⟨f.to_fun, f.times_cont_mdiff_to_fun.continuous⟩⟩
variables {f g : C^n⟮I, M; I', M'⟯}
protected lemma times_cont_mdiff (f : C^n⟮I, M; I', M'⟯) :
times_cont_mdiff I I' n f := f.times_cont_mdiff_to_fun
protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) :
smooth I I' f := f.times_cont_mdiff_to_fun
lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr'; exact funext h
/-- The identity as a smooth map. -/
def id : C^n⟮I, M; I, M⟯ := ⟨id, times_cont_mdiff_id⟩
/-- The composition of smooth maps, as a smooth map. -/
def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ :=
{ to_fun := λ a, f (g a),
times_cont_mdiff_to_fun := f.times_cont_mdiff_to_fun.comp g.times_cont_mdiff_to_fun, }
@[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) :
f.comp g x = f (g x) := rfl
instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ :=
⟨⟨λ _, default _, times_cont_mdiff_const⟩⟩
/-- Constant map as a smooth map -/
def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, times_cont_mdiff_const⟩
end times_cont_mdiff_map
instance continuous_linear_map.has_coe_to_times_cont_mdiff_map :
has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ :=
⟨λ f, ⟨f.to_fun, f.times_cont_mdiff⟩⟩
|
7828f74f94fcc2fd12ed8daa1f4dda68f33546bc | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/group_theory/group_action/option.lean | 2d4471145ccf5b695def21fa5ca66560f58447bc | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 1,986 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import group_theory.group_action.defs
/-!
# Option instances for additive and multiplicative actions
This file defines instances for additive and multiplicative actions on `option` type. Scalar
multiplication is defined by `a • some b = some (a • b)` and `a • none = none`.
## See also
* `group_theory.group_action.pi`
* `group_theory.group_action.prod`
* `group_theory.group_action.sigma`
* `group_theory.group_action.sum`
-/
variables {M N α : Type*}
namespace option
section has_smul
variables [has_smul M α] [has_smul N α] (a : M) (b : α) (x : option α)
@[to_additive option.has_vadd] instance : has_smul M (option α) := ⟨λ a, option.map $ (•) a⟩
@[to_additive] lemma smul_def : a • x = x.map ((•) a) := rfl
@[simp, to_additive] lemma smul_none : a • (none : option α) = none := rfl
@[simp, to_additive] lemma smul_some : a • some b = some (a • b) := rfl
instance [has_smul M N] [is_scalar_tower M N α] : is_scalar_tower M N (option α) :=
⟨λ a b x, by { cases x, exacts [rfl, congr_arg some (smul_assoc _ _ _)] }⟩
@[to_additive] instance [smul_comm_class M N α] : smul_comm_class M N (option α) :=
⟨λ a b, function.commute.option_map $ smul_comm _ _⟩
instance [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] : is_central_scalar M (option α) :=
⟨λ a x, by { cases x, exacts [rfl, congr_arg some (op_smul_eq_smul _ _)] }⟩
@[to_additive] instance [has_faithful_smul M α] : has_faithful_smul M (option α) :=
⟨λ x y h, eq_of_smul_eq_smul $ λ b : α, by injection h (some b)⟩
end has_smul
instance [monoid M] [mul_action M α] : mul_action M (option α) :=
{ smul := (•),
one_smul := λ b, by { cases b, exacts [rfl, congr_arg some (one_smul _ _)] },
mul_smul := λ a₁ a₂ b, by { cases b, exacts [rfl, congr_arg some (mul_smul _ _ _)] } }
end option
|
e24c00d3c8dd0b7ce2c915c84a4945f84bc12706 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/widget/tactic_component.lean | bdb6286d1f0516ac38bea04e0f476f628cc1a235 | [] | 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 | 407 | lean | /-
Copyright (c) E.W.Ayers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: E.W.Ayers
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.widget.basic
namespace Mathlib
namespace widget
/-- A component that implicitly depends on tactic_state. For efficiency we always assume that the tactic_state is unchanged between component renderings. -/
|
d1b1689dfe935b89c87e34772acd1fe562a7ba51 | 83c8119e3298c0bfc53fc195c41a6afb63d01513 | /tests/lean/run/tc_right_to_left.lean | 0d46ac5538912a5e7a2d41ae68103ec1343ac495 | [
"Apache-2.0"
] | permissive | anfelor/lean | 584b91c4e87a6d95f7630c2a93fb082a87319ed0 | 31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1 | refs/heads/master | 1,610,067,141,310 | 1,585,992,232,000 | 1,585,992,232,000 | 251,683,543 | 0 | 0 | Apache-2.0 | 1,585,676,570,000 | 1,585,676,569,000 | null | UTF-8 | Lean | false | false | 473 | lean | -- verify that class resolution is done from right to left
class a (α : Type) (x : bool)
class b (α : Type) (x : bool)
class c (α : Type)
instance (α) : a α tt := ⟨_, _⟩
instance (α) : b α tt := ⟨_, _⟩
instance b.to_c (α x) [a α x] [b α x] : c α := ⟨α⟩
-- make all type-class resolution queries for `a α ff` fail
instance (α) [a α ff] : a α ff := ‹a α ff›
set_option trace.class_instances true
example (α) : c α :=
by apply_instance
|
6a712223d4a048cb73f0fb648174bad57d2bdacd | e42ba0bcfa11e5be053e2ce1ce1f49f027680525 | /src/separation/examples.lean | f150854d6a7d5b19125d6336066b13823e5cd45c | [] | no_license | unitb/separation-logic | 8e17c5b466f86caa143265f4c04c78eec9d3c3b8 | bdde6fc8f16fd43932aea9827d6c63cadd91c2e8 | refs/heads/master | 1,540,936,751,653 | 1,535,050,181,000 | 1,535,056,425,000 | 109,461,809 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,492 | lean | import data.bitvec
import data.dlist
import data.list.basic
import util.logic
import util.control.applicative
import util.control.monad.non_termination
import separation.heap
import separation.program
import separation.specification
import separation.tactic
universes u v w w'
open nat list function nonterm
variables {α β : Type}
namespace separation
namespace examples
def swap_ptr (p q : pointer) : program unit :=
do t ← alloc1 0,
copy t p,
copy p q,
copy q t,
free1 t
lemma swap_ptr_spec (p q : pointer) (v₀ v₁ : word)
: sat (swap_ptr p q) { pre := p ↦ v₀ :*: q ↦ v₁
, post := λ _, p ↦ v₁ :*: q ↦ v₀ } :=
begin
unfold swap_ptr,
bind_step with t h,
bind_step,
bind_step,
bind_step,
last_step',
end
open program
def map_list : pointer → program unit :=
fix (λ map_list p,
if p = 0
then return ()
else do
modify_nth p 0 2 (+1),
p' ← read_nth p 1 2,
map_list p'.to_ptr)
lemma map_list_def (p : pointer)
: map_list p =
if p = 0 then return ()
else do
modify_nth p 0 2 (+1),
p' ← read_nth p 1 2,
map_list p'.to_ptr :=
begin
unfold map_list,
-- transitivity,
admit -- rw [program.fix_unroll,dif_eq_if], refl
end
@[ptr_abstraction]
def is_list : pointer → list word → hprop
| p [] := [| p = 0 |]
| p (v :: vs) := [| p ≠ 0 |] :*: ∃∃ nx : word, p ↦* [v,nx] :*: is_list nx.to_ptr vs
lemma map_list_spec (p : pointer) (vs : list word)
: sat (map_list p)
{ pre := is_list p vs
, post := λ _, is_list p (list.map (+1) vs) } :=
begin
revert p,
induction vs ; intros p,
case nil
{ unfold map is_list,
rw ← embed_s_and_self,
extract_context h,
rw embed_s_and_self,
rw [map_list_def],
simp [h],
apply return.spec' },
case cons : x xs
{ unfold map is_list,
s_intros nx Hp_nz,
rw [map_list_def],
rw if_neg Hp_nz, simp,
bind_step,
bind_step with _ h,
unfold replace nth_le at *,
last_step' (vs_ih nx.to_ptr), }
end
def list_reverse_aux : ∀ (p r : pointer), program pointer :=
fix2 (λ list_reverse_aux p r,
if p = 0 then return r
else do
p' ← read_nth p 1 2,
write_nth p 1 2 ⟨ r ⟩,
list_reverse_aux p'.to_ptr p)
lemma list_reverse_aux_def (p r : pointer)
: list_reverse_aux p r =
if p = 0 then return r
else do
p' ← read_nth p 1 2 dec_trivial,
write_nth p 1 2 ⟨ r ⟩ dec_trivial,
list_reverse_aux p'.to_ptr p :=
begin
unfold list_reverse_aux,
-- transitivity,
admit -- rw [program.fix2_unroll], refl
end
lemma list_reverse_aux.spec (p r : pointer) (xs ys : list word)
: sat (list_reverse_aux p r)
{ pre := is_list p xs :*: is_list r ys
, post := λ r', is_list r' (reverse xs ++ ys) } :=
begin
revert ys p r,
induction xs ; intros ys p r,
case nil
{ simp [is_list],
extract_context h,
rw [list_reverse_aux_def,if_pos h],
last_step', },
case cons : x xs
{ simp [is_list],
s_intros nx h,
rw [list_reverse_aux_def,if_neg h],
bind_step with p' h',
bind_step, unfold replace const,
last_step' (xs_ih (x :: ys)), }
end
def list_reverse (p : pointer) : program pointer :=
list_reverse_aux p 0
lemma list_reverse.spec (p : pointer) (xs : list word)
: sat (list_reverse p)
{ pre := is_list p xs
, post := λ r, is_list r (reverse xs) } :=
begin
unfold list_reverse,
apply precondition (is_list p xs :*: is_list 0 []),
apply postcondition _ (list_reverse_aux.spec p 0 xs []),
{ intros, simp },
{ simp [is_list,embed_eq_emp], }
end
def list_reverse' (p : pointer) : program pointer :=
sorry
lemma list_reverse_spec' (p : pointer) (vs : list word)
: sat (list_reverse' p) { pre := is_list p vs,
post := λ q, is_list q (list.reverse vs) } :=
sorry
def list_reverse_dup_aux : pointer → pointer → program pointer :=
fix2 (λ list_reverse_dup_aux p q,
if p = 0 then return q
else do
x ← read_nth p 0 2,
new ← alloc [x,⟨ q ⟩],
next ← read_nth p 1 2,
list_reverse_dup_aux next.to_ptr new)
lemma list_reverse_dup_aux_def (p q : pointer)
: list_reverse_dup_aux p q =
if p = 0 then return q
else do
x ← read_nth p 0 2,
new ← alloc [x,⟨ q ⟩],
next ← read_nth p 1 2,
list_reverse_dup_aux next.to_ptr new :=
sorry
def segment : pointer → pointer → list word → hprop
| p q [] := [| p = q |]
| p q (x :: xs) := [| p ≠ q |] :*: ∃∃ nx, p ↦* [x,nx] :*: segment nx.to_ptr q xs
lemma segment_nil (p : pointer) (xs : list word)
: segment p 0 xs = is_list p xs :=
sorry
@[ptr_abstraction]
lemma segment_append (p r : pointer) (xs ys : list word)
: segment p r (xs++ys) = ∃∃ q, segment p q xs :*: segment q r ys :=
sorry
@[ptr_abstraction]
lemma segment_single (p q : pointer) (x : word)
: segment p q [x] = p ↦* [x,⟨ q ⟩] :=
sorry
@[ptr_abstraction]
lemma word_to_pointer_eq_self (x : word)
: { word . to_ptr := x.to_ptr } = x := sorry
open tactic
lemma list_reverse_dup_aux_spec (p q r : pointer) (xs ys zs : list word)
: sat (list_reverse_dup_aux q r)
{ pre := segment p q xs :*: is_list q ys :*: is_list r zs,
post := λ q, is_list p (xs ++ ys) :*: is_list q (list.reverse ys ++ zs) } :=
begin
revert xs zs q r,
induction ys ; intros xs zs q r,
case nil
{ unfold is_list,
extract_context h,
rw [list_reverse_dup_aux_def],
subst q, simp [segment_nil],
apply postcondition _ (return.spec _ _),
{ intros, dsimp [list.reverse_nil], ac_refl } },
case cons : y ys
{ unfold is_list,
extract_context h,
s_exists nx,
rw [list_reverse_dup_aux_def,if_neg h],
bind_step with x h₀,
bind_step with new h₁,
bind_step with next h,
last_step' ys_ih (xs ++ [x]) (x :: zs), }
end
def list_reverse_dup (p : pointer) : program pointer :=
list_reverse_dup_aux p 0
lemma list_reverse_dup_spec (p : pointer) (vs : list word)
: sat (list_reverse_dup p)
{ pre := is_list p vs,
post := λ q, is_list p vs :*: is_list q (list.reverse vs) } :=
begin
unfold list_reverse_dup,
apply adapt_spec (list_reverse_dup_aux_spec p p 0 [] vs []),
{ simp [segment,is_list,embed_eq_emp] },
{ intro r, simp }
end
inductive tree (α : Type u)
| leaf {} : tree
| node : tree → α → tree → tree
@[ptr_abstraction]
def is_tree : pointer → tree word → hprop
| p tree.leaf := [| p = 0 |]
| p (tree.node l x r) := ∃∃ lp rp : word,
[| p ≠ 0 |] :*:
p ↦* [lp,x,rp] :*:
is_tree lp.to_ptr l :*:
is_tree rp.to_ptr r
def free_tree : pointer → program unit :=
fix λ free_tree p, do
if p = 0 then return ()
else do
l ← read_nth p 0 3,
r ← read_nth p 2 3,
free p 3,
free_tree l.to_ptr,
free_tree r.to_ptr
lemma free_tree_def (p : pointer)
: free_tree p =
if p = 0 then return ()
else do
l ← read_nth p 0 3,
r ← read_nth p 2 3,
free p 3,
free_tree l.to_ptr,
free_tree r.to_ptr :=
sorry
lemma free_tree_spec (p : pointer) (t : tree word)
: sat (free_tree p) { pre := is_tree p t
, post := λ _, emp } :=
begin
revert p,
induction t ; intro p,
case tree.leaf
{ unfold is_tree,
rw free_tree_def,
s_intros h,
simp [h],
apply return.spec', },
case tree.node : l x r
{ unfold is_tree,
s_intros lp rp h,
rw [free_tree_def,if_neg h],
bind_step with l hl,
bind_step with r hr,
bind_step,
bind_step t_ih_a,
last_step' t_ih_a_1 }
end
end examples
end separation
|
1db8c184906a821d0f6c34294b54bd0c5bd3d5f2 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/sum/basic.lean | f4f14c3790c3b6e680d9f191dd538ec8f7e4d2eb | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 532 | 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, Jeremy Avigad
The sum type, aka disjoint union.
-/
prelude
import init.logic
notation α ⊕ β := sum α β
universes u v
variables {α : Type u} {β : Type v}
instance sum.inhabited_left [h : inhabited α] : inhabited (α ⊕ β) :=
⟨sum.inl (default α)⟩
instance sum.inhabited_right [h : inhabited β] : inhabited (α ⊕ β) :=
⟨sum.inr (default β)⟩
|
2d49461cd43abe1c73cf84b805fb1066afc0c9a8 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/simplifier8.lean | 7a167e6a6a038b5994375fc1fe62c87f801a8156 | [
"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 | 382 | lean | -- deeper congruence
universe l
constants (T : Type.{l}) (x1 x2 x3 x4 x5 x6 : T) (f : T → T → T)
constants (f_comm : ∀ x y, f x y = f y x)
(f_l : ∀ x y z, f (f x y) z = f x (f y z))
(f_r : ∀ x y z, f x (f y z) = f y (f x z))
attribute f_comm [simp]
attribute f_l [simp]
attribute f_r [simp]
#simplify eq env 0 (f (f x2 x4) (f x5 (f x3 (f x1 x6))))
|
df7fe28d5d563ef6f362f8c72f73388c07950a92 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/data/int/order.lean | d98449e5b4103662e016086ff35d0f9dd4a97e7f | [
"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 | 8,802 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The order relation on the integers.
-/
prelude
import init.data.int.basic
namespace int
private def nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false)
protected def le (a b : ℤ) : Prop := nonneg (b - a)
instance : has_le int := ⟨int.le⟩
protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b
instance : has_lt int := ⟨int.lt⟩
private def decidable_nonneg (a : ℤ) : decidable (nonneg a) :=
int.cases_on a (take a, decidable.true) (take a, decidable.false)
instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _
lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _
private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n :=
int.cases_on a (take n H, exists.intro n rfl) (take n', false.elim)
private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial)
lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b :=
have ↑n = b - a, begin rw -h, simp end,
show nonneg (b - a), from this ▸ trivial
lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b :=
match (nonneg.elim h) with
| ⟨n, h₁⟩ := exists.intro n begin rw [-h₁, add_comm], simp end
end
lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P :=
exists.elim (le.dest h) h'
protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.imp_right
(assume H : nonneg (-(b - a)),
have -(b - a) = a - b, by simp,
show nonneg (a - b), from this ▸ H)
(nonneg_or_nonneg_neg (b - a))
lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n :=
match nat.le.dest h with
| ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [-hk], reflexivity end)
end
lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n :=
le.elim h (take k, assume hk : ↑m + ↑k = ↑n,
have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k)^.trans hk),
nat.le.intro this)
lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n :=
iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le
lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) :=
le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq], reflexivity end)
lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b :=
h ▸ lt_add_succ a n
lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b :=
le.elim h (take n, assume hn : a + 1 + n = b,
exists.intro n begin rw [-hn, add_assoc, add_comm (1 : int)], reflexivity end)
lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P :=
exists.elim (lt.dest h) h'
lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m :=
begin rw [lt_iff_add_one_le, -int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end
lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n :=
(coe_nat_lt_coe_nat_iff _ _)^.mp h
lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n :=
(coe_nat_lt_coe_nat_iff _ _)^.mpr h
/- show that the integers form an ordered additive group -/
protected lemma le_refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c :=
le.elim h₁ (take n, assume hn : a + n = b,
le.elim h₂ (take m, assume hm : b + m = c,
begin apply le.intro, rw [-hm, -hn, add_assoc], reflexivity end))
protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b :=
le.elim h₁ (take n, assume hn : a + n = b,
le.elim h₂ (take m, assume hm : b + m = a,
have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, -add_assoc, hn, hm, add_zero a],
have (↑(n + m) : ℤ) = 0, from add_left_cancel this,
have n + m = 0, from int.coe_nat_inj this,
have n = 0, from nat.eq_zero_of_add_eq_zero_right this,
show a = b, begin rw [-hn, this, int.coe_nat_zero, add_zero a] end))
protected lemma lt_irrefl (a : ℤ) : ¬ a < a :=
suppose a < a,
lt.elim this (take n, assume hn : a + nat.succ n = a,
have a + nat.succ n = a + 0, by rw [hn, add_zero],
have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this),
show false, from nat.succ_ne_zero _ this)
protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b :=
(suppose a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b))
lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b :=
lt.elim h (take n, assume hn : a + nat.succ n = b, le.intro hn)
protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume h, ⟨le_of_lt h, int.ne_of_lt h⟩)
(assume ⟨aleb, aneb⟩,
le.elim aleb (take n, assume hn : a + n = b,
have n ≠ 0,
from (suppose n = 0, aneb begin rw [-hn, this, int.coe_nat_zero, add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
lt.intro (begin rewrite this at hn, exact hn end)))
protected lemma le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) :=
iff.intro
(assume h,
decidable.by_cases
(suppose a = b, or.inr this)
(suppose a ≠ b,
le.elim h (take n, assume hn : a + n = b,
have n ≠ 0, from
(suppose n = 0, ‹a ≠ b› begin rw [-hn, this, int.coe_nat_zero, add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
or.inl (lt.intro (begin rewrite this at hn, exact hn end)))))
(assume h,
or.elim h
(assume h', le_of_lt h')
(assume h', h' ▸ int.le_refl a))
lemma lt_succ (a : ℤ) : a < a + 1 :=
int.le_refl (a + 1)
protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
le.elim h (take n, assume hn : a + n = b,
le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end))
protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b :=
iff.mpr (int.lt_iff_le_and_ne _ _)
(and.intro
(int.add_le_add_left (le_of_lt h) _)
(take heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end))
protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
le.elim ha (take n, assume hn,
le.elim hb (take m, assume hm,
le.intro (show 0 + ↑n * ↑m = a * b, begin rw [-hn, -hm], repeat {rw zero_add} end)))
protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
lt.elim ha (take n, assume hn,
lt.elim hb (take m, assume hm,
lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b,
begin rw [-hn, -hm], repeat {rw int.coe_nat_zero}, simp,
rw [-int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end)))
protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial
protected lemma not_le_of_gt {a b : ℤ} (h : a < b) : ¬ b ≤ a :=
assume hba : b ≤ a,
have a = b, from int.le_antisymm (le_of_lt h) hba,
show false, from int.lt_irrefl b (begin rw this at h, exact h end)
protected lemma lt_of_lt_of_le {a b c : ℤ} (hab : a < b) (hbc : b ≤ c) : a < c :=
have hac : a ≤ c, from int.le_trans (le_of_lt hab) hbc,
iff.mpr
(int.lt_iff_le_and_ne _ _)
(and.intro hac (assume heq, int.not_le_of_gt begin rw -heq, assumption end hbc))
protected lemma lt_of_le_of_lt {a b c : ℤ} (hab : a ≤ b) (hbc : b < c) : a < c :=
have hac : a ≤ c, from int.le_trans hab (le_of_lt hbc),
iff.mpr
(int.lt_iff_le_and_ne _ _)
(and.intro hac (assume heq, int.not_le_of_gt begin rw heq, exact hbc end hab))
instance : decidable_linear_ordered_comm_ring int :=
{ int.comm_ring with
le := int.le,
le_refl := int.le_refl,
le_trans := @int.le_trans,
le_antisymm := @int.le_antisymm,
lt := int.lt,
le_of_lt := @int.le_of_lt,
lt_of_lt_of_le := @int.lt_of_lt_of_le,
lt_of_le_of_lt := @int.lt_of_le_of_lt,
lt_irrefl := int.lt_irrefl,
add_le_add_left := @int.add_le_add_left,
add_lt_add_left := @int.add_lt_add_left,
zero_ne_one := int.zero_ne_one,
mul_nonneg := @int.mul_nonneg,
mul_pos := @int.mul_pos,
le_iff_lt_or_eq := int.le_iff_lt_or_eq,
le_total := int.le_total,
zero_lt_one := int.zero_lt_one,
decidable_eq := int.decidable_eq,
decidable_le := int.decidable_le,
decidable_lt := int.decidable_lt }
instance : decidable_linear_ordered_comm_group int :=
by apply_instance
end int
-- TODO(Jeremy): add more facts specific to the integers
|
426443cda5e9533c5aa68f9302524403d7cbc0c9 | 0003047346476c031128723dfd16fe273c6bc605 | /src/data/finsupp.lean | 2b4510d485cee4933c46c3bfba400be250568f02 | [
"Apache-2.0"
] | permissive | ChandanKSingh/mathlib | d2bf4724ccc670bf24915c12c475748281d3fb73 | d60d1616958787ccb9842dc943534f90ea0bab64 | refs/heads/master | 1,588,238,823,679 | 1,552,867,469,000 | 1,552,867,469,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 49,615 | 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
Type of functions with finite support.
Functions with finite support provide the basis for the following concrete instances:
* ℕ →₀ α: Polynomials (where α is a ring)
* (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names)
* α →₀ ℕ: Multisets
* α →₀ ℤ: Abelian groups freely generated by α
* β →₀ α: Linear combinations over β where α is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
reserve infix ` →₀ `:25
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infix →₀ := finsupp
namespace finsupp
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm
@[extensionality]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨set.fintype_of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
def equiv_fun_on_fintype [fintype α] [decidable_eq β]: (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
section single
variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)):=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [finsupp.ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
end single
section on_finset
variables [decidable_eq β] [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s := filter_subset _
end on_finset
section map_range
variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
finsupp.ext $ λ a, by simp [hf]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
variables [decidable_eq α] [decidable_eq β₁]
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin
haveI := classical.dec_eq β₁,
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
section erase
variables [decidable_eq α] [decidable_eq β]
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
end erase
-- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive finsupp.sum]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1
@[to_additive finsupp.sum_map_range_index]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive finsupp.sum_zero_index]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 := rfl
section decidable
variables [decidable_eq α] [decidable_eq β]
section add_monoid
variables [add_monoid β]
@[to_additive finsupp.sum_single_index]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support):
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
by refine_struct {..}; simp
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [decidable_eq β₁] [decidable_eq β₂] [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive finsupp.sum_neg_index]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(finset.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive finsupp.sum_add_index]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive finsupp.sum_finset_sum_index]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂):
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive finsupp.sum_sum_index]
lemma prod_sum_index
[decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂):
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(finset.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(finset.sum_hom multiset.sum).symm
section map_range
variables
[decidable_eq β₁] [decidable_eq β₂] [add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.1 : (α →₀ β₁) → (α →₀ β₂)) :=
⟨map_range_zero, assume a b, map_range_add hf.2 _ _⟩
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.1 m.sum = (m.map $ λx, map_range f hf.1 x).sum :=
(m.sum_hom (map_range f hf.1)).symm
lemma map_range_finset_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.1 (s.sum g) = s.sum (λx, map_range f hf.1 (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
section map_domain
variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v := sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive finsupp.sum_map_domain_index]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
end map_domain
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
section filter
section has_zero
variables [has_zero β] (p : α → Prop) [decidable_pred p] (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h' h
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) [decidable_pred p] :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
section frange
variables [has_zero β]
def frange (f : α →₀ β) : finset β :=
finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive finsupp.sum_subtype_domain_index]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom [add_monoid β] :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
by refine_struct {..}; simp
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, by by_cases p a; simp [h]
instance filter.is_add_monoid_hom (p : α → Prop) [decidable_pred p] :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
⟨filter_zero p, assume x y, filter_add⟩
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(finset.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
⟨to_multiset_zero, to_multiset_add⟩
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(finset.sum_hom _).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
def of_multiset [decidable_eq α] (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply [decidable_eq α] (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
def equiv_multiset [decidable_eq α] : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [decidable_eq α] [decidable_eq β] [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
section curry_uncurry
protected def curry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
protected def uncurry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
def finsupp_prod_equiv [add_comm_monoid γ] [decidable_eq α] [decidable_eq β] [decidable_eq γ] :
((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β]
(f : α₁ × α₂ →₀ β) (p : α₁ → Prop) [decidable_pred p] :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ _ _ p _ _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry
[decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
def to_semiring : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
local attribute [instance] to_semiring
def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.to_semiring }
local attribute [instance] to_comm_semiring
def to_ring [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.to_semiring }
def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.to_ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [decidable_eq ι] [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
section
variables (α β)
def to_has_scalar' [R:semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
local attribute [instance] to_has_scalar'
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
def to_semimodule {R:semiring γ} [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
def to_module {R:ring γ} [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..to_semimodule α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
@[simp] lemma filter_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, by by_cases p a; simp [h]
end
lemma map_domain_smul {α'} [decidable_eq α'] {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, {simp},
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]]
end
def to_has_scalar [ring β] : has_scalar β (α →₀ β) := to_has_scalar' α β
local attribute [instance] to_has_scalar
@[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
end decidable
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
end
def restrict_support_equiv [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
(s : set α) [decidable_pred (λx, x ∈ s)] :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
protected def dom_congr [decidable_eq α₁] [decidable_eq α₂] [decidable_eq β] [add_comm_monoid β]
(e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
end finsupp
|
7b28aeba3498b9c3b04420a05c1dc9a3d034b5ea | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/kb_defs.lean | 14bc4a8835850b5872ead643adb590fc16f0c052 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,179 | lean | import tactic
open_locale classical
open set
namespace xena
variables {X : Type} (a : X) {x : X} {A B : set X}
/-- Humans want these in levels 1-6 -/
lemma mem_union_iff : x ∈ A ∪ B ↔ x ∈ A ∨ x ∈ B := iff.rfl
lemma mem_inter_iff : x ∈ A ∩ B ↔ x ∈ A ∧ x ∈ B := iff.rfl
lemma mem_sdiff_iff : x ∈ A \ B ↔ x ∈ A ∧ x ∉ B := iff.rfl
lemma mem_neg_iff : x ∈ Aᶜ ↔ x ∉ A := iff.rfl
lemma ext_iff : A = B ↔ ∀ x : X, x ∈ A ↔ x ∈ B := ext_iff
lemma subset_iff : A ⊆ B ↔ ∀ x : X, x ∈ A → x ∈ B := iff.rfl
/-- Humans want these in level 7 -/
--lemma mem_univ (a : X) : a ∈ (univ : set X) := mem_univ a
lemma mem_empty_iff (a : X) : a ∈ (∅ : set X) ↔ false := iff.rfl
--lemma not_mem_empty (a : X) : ¬ (a ∈ (∅ : set X)) := not_false
--lemma mem_set_iff (a : X) (P : X → Prop) : a ∈ {b : X | P b} ↔ P a := iff.rfl
variables (ι : Type) (f : ι → set X)
/-- Humans might want these but we don't use them yet -/
lemma mem_Union_iff : (x ∈ ⋃(i : ι), f i) ↔ ∃ (i : ι), x ∈ f i := mem_Union
lemma mem_Inter_iff : (x ∈ ⋂(i : ι), f i) ↔ ∀ (i : ι), x ∈ f i := mem_Inter
end xena
|
b88394a7918450b6b50fb207a7d02d41e5193d24 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/analysis/special_functions/exp_log.lean | 759e7ad45b4b4b98d8a6c14a86c0af91454a61cf | [
"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 | 22,051 | 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_val),
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_val,
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 has_sum_iff_tendsto_nat_of_summable,
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 (nat.cast_nonneg i)],
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
|
3011958481f7eecb300660cf7a381dd547294b31 | 200b12985a863d01fbbde6abfc9326bb82424a8b | /src/propLogic/Ex010.lean | 0f1ce3aa185f3c4ade10b0f104715ddcd3d9169c | [] | no_license | SvenWille/LeanLogicExercises | 38eacd36733ac48e5a7aacf863c681c9a9a48271 | 2dbc920feadd63bbc50f87e69646c0081db26eba | refs/heads/master | 1,629,676,667,365 | 1,512,161,459,000 | 1,512,161,459,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 190 | lean |
theorem Ex010(a : Prop): a ∨ ¬false :=
have A:false → false,from
(
assume H1:false,
show false, from H1
),
have ¬false, from not.intro A,
show a ∨ ¬false, from or.inr this
|
fab29740d9baadac98c8d78b364d933225394386 | df7bb3acd9623e489e95e85d0bc55590ab0bc393 | /lean/love05_inductive_predicates_exercise_sheet.lean | 56a615b67457bdf79404fc5b87b71d3dd9ebb46b | [] | no_license | MaschavanderMarel/logical_verification_2020 | a41c210b9237c56cb35f6cd399e3ac2fe42e775d | 7d562ef174cc6578ca6013f74db336480470b708 | refs/heads/master | 1,692,144,223,196 | 1,634,661,675,000 | 1,634,661,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,302 | lean | import .love05_inductive_predicates_demo
/- # LoVe Exercise 5: Inductive Predicates -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Question 1: Even and Odd
The `even` predicate is true for even numbers and false for odd numbers. -/
#check even
/- We define `odd` as the negation of `even`: -/
def odd (n : ℕ) : Prop :=
¬ even n
/- 1.1. Prove that 1 is odd and register this fact as a simp rule.
Hint: `cases'` is useful to reason about hypotheses of the form `even …`. -/
@[simp] lemma odd_1 :
odd 1 :=
sorry
/- 1.2. Prove that 3, 5, and 7 are odd. -/
-- enter your answer here
/- 1.3. Complete the following proof by structural induction. -/
lemma even_two_times :
∀m : ℕ, even (2 * m)
| 0 := even.zero
| (m + 1) :=
sorry
/- 1.4. Complete the following proof by rule induction.
Hint: You can use the `cases'` tactic (or `match … with`) to destruct an
existential quantifier and extract the witness. -/
lemma even_imp_exists_two_times :
∀n : ℕ, even n → ∃m, n = 2 * m :=
begin
intros n hen,
induction' hen,
case zero {
apply exists.intro 0,
refl },
case add_two : k hek ih {
sorry }
end
/- 1.6. Using `even_two_times` and `even_imp_exists_two_times`, prove the
following equivalence. -/
lemma even_iff_exists_two_times (n : ℕ) :
even n ↔ ∃m, n = 2 * m :=
sorry
/- ## Question 2: Binary Trees
2.1. Prove the converse of `is_full_mirror`. You may exploit already proved
lemmas (e.g., `is_full_mirror`, `mirror_mirror`). -/
#check is_full_mirror
#check mirror_mirror
lemma mirror_is_full {α : Type} :
∀t : btree α, is_full (mirror t) → is_full t :=
sorry
/- 2.2. Define a `map` function on binary trees, similar to `list.map`. -/
def btree.map {α β : Type} (f : α → β) : btree α → btree β
| _ := sorry -- remove this dummy case and enter the missing cases
/- 2.3. Prove the following lemma by case distinction. -/
lemma btree.map_eq_empty_iff {α β : Type} (f : α → β) :
∀t : btree α, btree.map f t = btree.empty ↔ t = btree.empty :=
sorry
/- 2.4. Prove the following lemma by rule induction. -/
lemma btree.map_mirror {α β : Type} (f : α → β) :
∀t : btree α, is_full t → is_full (btree.map f t) :=
sorry
end LoVe
|
98e6b78693a5a7d4ac6ee232626bbfca10e15a16 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/obviously_auto.lean | 9b44485e300558900056e832ef026ebde5e705e6 | [] | 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,436 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.tidy
import Mathlib.tactic.replacer
import Mathlib.PostPort
namespace Mathlib
/-!
# The `obviously` tactic
This file sets up a tactic called `obviously`,
which is subsequently used throughout the category theory library
as an `auto_param` to discharge easy proof obligations when building structures.
In this file, we set up `obviously` as a "replacer" tactic,
whose implementation can be modified after the fact.
Then we set the default implementation to be `tidy`.
## Implementation note
At present we don't actually take advantage of the replacer mechanism in mathlib.
In the past it had been used by an external category theory library which wanted to incorporate
`rewrite_search` as part of `obviously`.
-/
/-
The propositional fields of `category` are annotated with the auto_param `obviously`,
which is defined here as a
[`replacer` tactic](https://leanprover-community.github.io/mathlib_docs/commands.html#def_replacer).
We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more
powerful tactics.
(In fact, at present this mechanism is not actually used, and the implementation of
`obviously` below stays in place throughout mathlib.)
-/
end Mathlib |
31055958c8d03b0a49996f71215562e7c8280145 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/pointwise.lean | 82282819d3f1c6438707bd50aac5089332341272 | [
"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 | 18,572 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import algebra.module.basic
import data.set.finite
import group_theory.submonoid.basic
/-!
# Pointwise addition, multiplication, and scalar multiplication of sets.
This file defines pointwise algebraic operations on sets.
* For a type `α` with multiplication, multiplication is defined on `set α` by taking
`s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition.
* For `α` a semigroup, `set α` is a semigroup.
* If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then
becomes a (commutative) semiring with union as addition and pointwise multiplication as
multiplication.
* For a type `β` with scalar multiplication by another type `α`, this
file defines a scalar multiplication of `set β` by `set α` and a separate scalar
multiplication of `set β` by `α`.
* We also define pointwise multiplication on `finset`.
Appropriate definitions and results are also transported to the additive theory via `to_additive`.
## Implementation notes
* The following expressions are considered in simp-normal form in a group:
`(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`,
`s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants).
Expressions equal to one of these will be simplified.
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication
-/
namespace set
open function
variables {α : Type*} {β : Type*} {s s₁ s₂ t t₁ t₂ u : set α} {a b : α} {x y : β}
/-! ### Properties about 1 -/
@[to_additive]
instance [has_one α] : has_one (set α) := ⟨{1}⟩
@[to_additive]
lemma singleton_one [has_one α] : ({1} : set α) = 1 := rfl
@[simp, to_additive]
lemma mem_one [has_one α] : a ∈ (1 : set α) ↔ a = 1 := iff.rfl
@[to_additive]
lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : set α) := eq.refl _
@[simp, to_additive]
theorem one_subset [has_one α] : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff
@[to_additive]
theorem one_nonempty [has_one α] : (1 : set α).nonempty := ⟨1, rfl⟩
@[simp, to_additive]
theorem image_one [has_one α] {f : α → β} : f '' 1 = {f 1} := image_singleton
/-! ### Properties about multiplication -/
@[to_additive]
instance [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩
@[simp, to_additive]
lemma image2_mul [has_mul α] : image2 has_mul.mul s t = s * t := rfl
@[to_additive]
lemma mem_mul [has_mul α] : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl
@[to_additive]
lemma mul_mem_mul [has_mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb
@[to_additive add_image_prod]
lemma image_mul_prod [has_mul α] : (λ x : α × α, x.fst * x.snd) '' s.prod t = s * t := image_prod _
@[simp, to_additive]
lemma image_mul_left [group α] : (λ b, a * b) '' t = (λ b, a⁻¹ * b) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[simp, to_additive]
lemma image_mul_right [group α] : (λ a, a * b) '' t = (λ a, a * b⁻¹) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[to_additive]
lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp
@[to_additive]
lemma image_mul_right' [group α] : (λ a, a * b⁻¹) '' t = (λ a, a * b) ⁻¹' t := by simp
@[simp, to_additive]
lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} :=
by rw [← image_mul_left', image_singleton]
@[simp, to_additive]
lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} :=
by rw [← image_mul_right', image_singleton]
@[simp, to_additive]
lemma preimage_mul_left_one [group α] : (λ b, a * b) ⁻¹' 1 = {a⁻¹} :=
by rw [← image_mul_left', image_one, mul_one]
@[simp, to_additive]
lemma preimage_mul_right_one [group α] : (λ a, a * b) ⁻¹' 1 = {b⁻¹} :=
by rw [← image_mul_right', image_one, one_mul]
@[to_additive]
lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp
@[to_additive]
lemma preimage_mul_right_one' [group α] : (λ a, a * b⁻¹) ⁻¹' 1 = {b} := by simp
@[simp, to_additive]
lemma mul_singleton [has_mul α] : s * {b} = (λ a, a * b) '' s := image2_singleton_right
@[simp, to_additive]
lemma singleton_mul [has_mul α] : {a} * t = (λ b, a * b) '' t := image2_singleton_left
@[simp, to_additive]
lemma singleton_mul_singleton [has_mul α] : ({a} : set α) * {b} = {a * b} := image2_singleton
@[to_additive set.add_semigroup]
instance [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, image2_assoc mul_assoc,
..set.has_mul }
@[to_additive set.add_monoid]
instance [monoid α] : monoid (set α) :=
{ mul_one := λ s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] },
one_mul := λ s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] },
..set.semigroup,
..set.has_one }
@[to_additive]
protected lemma mul_comm [comm_semigroup α] : s * t = t * s :=
by simp only [← image2_mul, image2_swap _ s, mul_comm]
@[to_additive set.add_comm_monoid]
instance [comm_monoid α] : comm_monoid (set α) :=
{ mul_comm := λ _ _, set.mul_comm, ..set.monoid }
@[to_additive]
lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) :=
{ map_mul := λ a b, singleton_mul_singleton.symm }
@[simp, to_additive]
lemma empty_mul [has_mul α] : ∅ * s = ∅ := image2_empty_left
@[simp, to_additive]
lemma mul_empty [has_mul α] : s * ∅ = ∅ := image2_empty_right
@[to_additive]
lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ :=
image2_subset h₁ h₂
@[to_additive]
lemma union_mul [has_mul α] : (s ∪ t) * u = (s * u) ∪ (t * u) := image2_union_left
@[to_additive]
lemma mul_union [has_mul α] : s * (t ∪ u) = (s * t) ∪ (s * u) := image2_union_right
@[to_additive]
lemma Union_mul_left_image [has_mul α] : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t :=
Union_image_left _
@[to_additive]
lemma Union_mul_right_image [has_mul α] : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t :=
Union_image_right _
@[simp, to_additive]
lemma univ_mul_univ [monoid α] : (univ : set α) * univ = univ :=
begin
have : ∀x, ∃a b : α, a * b = x := λx, ⟨x, ⟨1, mul_one x⟩⟩,
simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and]
end
/-- `singleton` is a monoid hom. -/
@[to_additive singleton_add_hom "singleton is an add monoid hom"]
def singleton_hom [monoid α] : α →* set α :=
{ to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm }
@[to_additive]
lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2
@[to_additive]
lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) :=
hs.image2 _ ht
/-- multiplication preserves finiteness -/
@[to_additive "addition preserves finiteness"]
def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set α) :=
set.fintype_image2 _ s t
@[to_additive]
lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} :
bdd_above A → bdd_above B → bdd_above (A * B) :=
begin
rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩,
use bA * bB,
rintros x ⟨xa, xb, hxa, hxb, rfl⟩,
exact mul_le_mul' (hbA hxa) (hbB hxb),
end
/-! ### Properties about inversion -/
@[to_additive set.has_neg'] -- todo: remove prime once name becomes available
instance [has_inv α] : has_inv (set α) :=
⟨preimage has_inv.inv⟩
@[simp, to_additive]
lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl
@[to_additive]
lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s :=
by simp only [mem_inv, inv_inv]
@[simp, to_additive]
lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl
@[simp, to_additive]
lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ :=
by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] }
@[simp, to_additive]
lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter
@[simp, to_additive]
lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union
@[simp, to_additive]
lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl
@[simp, to_additive]
protected lemma inv_inv [group α] : s⁻¹⁻¹ = s :=
by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] }
@[simp, to_additive]
protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ
@[simp, to_additive]
lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t :=
(equiv.inv α).surjective.preimage_subset_preimage_iff
@[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ :=
by { rw [← inv_subset_inv, set.inv_inv] }
/-! ### Properties about scalar multiplication -/
/-- Scaling a set: multiplying every element by a scalar. -/
instance has_scalar_set [has_scalar α β] : has_scalar α (set β) :=
⟨λ a, image (has_scalar.smul a)⟩
@[simp]
lemma image_smul [has_scalar α β] {t : set β} : (λ x, a • x) '' t = a • t := rfl
lemma mem_smul_set [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl
lemma smul_mem_smul_set [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t :=
⟨y, hy, rfl⟩
lemma smul_set_union [has_scalar α β] {s t : set β} : a • (s ∪ t) = a • s ∪ a • t :=
by simp only [← image_smul, image_union]
@[simp]
lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ :=
by rw [← image_smul, image_empty]
lemma smul_set_mono [has_scalar α β] {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t :=
by { simp only [← image_smul, image_subset, h] }
/-- Pointwise scalar multiplication by a set of scalars. -/
instance [has_scalar α β] : has_scalar (set α) (set β) := ⟨image2 has_scalar.smul⟩
@[simp]
lemma image2_smul [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl
lemma mem_smul [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ a y, a ∈ s ∧ y ∈ t ∧ a • y = x :=
iff.rfl
lemma image_smul_prod [has_scalar α β] {t : set β} :
(λ x : α × β, x.fst • x.snd) '' s.prod t = s • t :=
image_prod _
theorem range_smul_range [has_scalar α β] {ι κ : Type*} (b : ι → α) (c : κ → β) :
range b • range c = range (λ p : ι × κ, b p.1 • c p.2) :=
ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in
⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩,
λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩
lemma singleton_smul [has_scalar α β] {t : set β} : ({a} : set α) • t = a • t :=
image2_singleton_left
section monoid
/-! ### `set α` as a `(∪,*)`-semiring -/
/-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise
multiplication `*` as "multiplication". -/
@[derive inhabited] def set_semiring (α : Type*) : Type* := set α
/-- The identitiy function `set α → set_semiring α`. -/
protected def up (s : set α) : set_semiring α := s
/-- The identitiy function `set_semiring α → set α`. -/
protected def set_semiring.down (s : set_semiring α) : set α := s
@[simp] protected lemma down_up {s : set α} : s.up.down = s := rfl
@[simp] protected lemma up_down {s : set_semiring α} : s.down.up = s := rfl
instance set_semiring.semiring [monoid α] : semiring (set_semiring α) :=
{ add := λ s t, (s ∪ t : set α),
zero := (∅ : set α),
add_assoc := union_assoc,
zero_add := empty_union,
add_zero := union_empty,
add_comm := union_comm,
zero_mul := λ s, empty_mul,
mul_zero := λ s, mul_empty,
left_distrib := λ _ _ _, mul_union,
right_distrib := λ _ _ _, union_mul,
..set.monoid }
instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) :=
{ ..set.comm_monoid, ..set_semiring.semiring }
/-- A multiplicative action of a monoid on a type β gives also a
multiplicative action on the subsets of β. -/
instance mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) :=
{ mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] },
one_smul := by { intros, simp only [← image_smul, image_eta, one_smul, image_id'] },
..set.has_scalar_set }
section is_mul_hom
open is_mul_hom
variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m]
@[to_additive]
lemma image_mul : m '' (s * t) = m '' s * m '' t :=
by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, map_mul m] }
@[to_additive]
lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) :=
by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (map_mul _ _ _).symm ⟩ }
end is_mul_hom
/-- The image of a set under function is a ring homomorphism
with respect to the pointwise operations on sets. -/
def image_hom [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β :=
{ to_fun := image f,
map_zero' := image_empty _,
map_one' := by simp only [← singleton_one, image_singleton, is_monoid_hom.map_one f],
map_add' := image_union _,
map_mul' := λ _ _, image_mul _ }
end monoid
end set
open set
section
variables {α : Type*} {β : Type*}
/-- A nonempty set in a semimodule is scaled by zero to the singleton
containing 0 in the semimodule. -/
lemma zero_smul_set [semiring α] [add_comm_monoid β] [semimodule α β] {s : set β} (h : s.nonempty) :
(0 : α) • s = (0 : set β) :=
by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero]
lemma mem_inv_smul_set_iff [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) :
x ∈ a⁻¹ • A ↔ a • x ∈ A :=
by simp only [← image_smul, mem_image, inv_smul_eq_iff' ha, exists_eq_right]
lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β)
(x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A :=
by rw [← mem_inv_smul_set_iff $ inv_ne_zero ha, inv_inv']
end
namespace finset
variables {α : Type*} [decidable_eq α]
/-- The pointwise product of two finite sets `s` and `t`:
`st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/
@[to_additive "The pointwise sum of two finite sets `s` and `t`:
`s + t = { x + y | x ∈ s, y ∈ t }`."]
instance [has_mul α] : has_mul (finset α) :=
⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩
@[to_additive]
lemma mul_def [has_mul α] {s t : finset α} :
s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl
@[to_additive]
lemma mem_mul [has_mul α] {s t : finset α} {x : α} :
x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x :=
by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] }
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul α] {s t : finset α} : (↑(s * t) : set α) = ↑s * ↑t :=
by { ext, simp only [mem_mul, set.mem_mul, mem_coe] }
@[to_additive]
lemma mul_mem_mul [has_mul α] {s t : finset α} {x y : α} (hx : x ∈ s) (hy : y ∈ t) :
x * y ∈ s * t :=
by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ }
lemma add_card_le [has_add α] {s t : finset α} : (s + t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
@[to_additive]
lemma mul_card_le [has_mul α] {s t : finset α} : (s * t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
open_locale classical
/-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product
of two finite sets `T * T' ⊆ S * S'`. -/
@[to_additive]
lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') :
∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' :=
begin
apply finset.induction_on' U,
{ use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], },
rintros a s haU hs has ⟨T, T', hS, hS', h⟩,
obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU),
use [insert x T, insert y T'],
simp only [finset.coe_insert],
repeat { rw [set.insert_subset], },
use [hx, hS, hy, hS'],
refine finset.insert_subset.mpr ⟨_, _⟩,
{ rw finset.mem_mul,
use [x,y],
simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], },
{ suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, },
transitivity ↑(T * T'),
apply h,
rw finset.coe_mul,
apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), },
end
end finset
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
variables {M : Type*} [monoid M]
@[to_additive]
lemma mul_subset {s t : set M} {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S :=
by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) }
@[to_additive]
lemma mul_subset_closure {s t u : set M} (hs : s ⊆ u) (ht : t ⊆ u) :
s * t ⊆ submonoid.closure u :=
mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure)
@[to_additive]
lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s :=
begin
ext x,
refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩,
rintros ⟨a, b, ha, hb, rfl⟩,
exact s.mul_mem ha hb
end
@[to_additive]
lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T :=
Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem
(le_def.mp le_sup_left $ subset_closure hs)
(le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) :=
le_antisymm
(sup_le
(λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩)
(λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩))
(by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le)
end submonoid
|
1cfcc5b087f39497e5d1b9e99c97aaf90671bca1 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/calculus/deriv.lean | 15b565b864e926efb0af0b238429c6df78466406 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 92,217 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sébastien Gouëzel
-/
import analysis.calculus.fderiv
import data.polynomial.derivative
import linear_algebra.affine_space.slope
/-!
# One-dimensional derivatives
This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a
normed field and `F` is a normed space over this field. The derivative of
such a function `f` at a point `x` is given by an element `f' : F`.
The theory is developed analogously to the [Fréchet
derivatives](./fderiv.html). We first introduce predicates defined in terms
of the corresponding predicates for Fréchet derivatives:
- `has_deriv_at_filter f f' x L` states that the function `f` has the
derivative `f'` at the point `x` as `x` goes along the filter `L`.
- `has_deriv_within_at f f' s x` states that the function `f` has the
derivative `f'` at the point `x` within the subset `s`.
- `has_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x`.
- `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x` in the sense of strict differentiability, i.e.,
`f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`.
For the last two notions we also define a functional version:
- `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the
derivative does not exist, then `deriv_within f s x` equals zero.
- `deriv f x` is a derivative of `f` at `x`. If the derivative does not
exist, then `deriv f x` equals zero.
The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the
one-dimensional derivatives coincide with the general Fréchet derivatives.
We also show the existence and compute the derivatives of:
- constants
- the identity function
- linear maps
- addition
- sum of finitely many functions
- negation
- subtraction
- multiplication
- inverse `x → x⁻¹`
- multiplication of two functions in `𝕜 → 𝕜`
- multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E`
- composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜`
- composition of a function in `F → E` with a function in `𝕜 → F`
- inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
- division
- polynomials
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.
We set up the simplifier so that it can compute the derivative of simple functions. For instance,
```lean
example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) :=
by { simp, ring }
```
## Implementation notes
Most of the theorems are direct restatements of the corresponding theorems
for Fréchet derivatives.
The strategy to construct simp lemmas that give the simplifier the possibility to compute
derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`.
See the explanations there.
-/
universes u v w
noncomputable theory
open_locale classical topological_space big_operators filter ennreal polynomial
open filter asymptotics set
open continuous_linear_map (smul_right smul_right_one_eq_iff)
variables {𝕜 : Type u} [nontrivially_normed_field 𝕜]
section
variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F]
variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E]
/--
`f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`.
-/
def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) :=
has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L
/--
`f` has the derivative `f'` at the point `x` within the subset `s`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝[s] x)
/--
`f` has the derivative `f'` at the point `x`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`.
-/
def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝 x)
/-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability.
That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/
def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x
/--
Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then
`f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) :=
fderiv_within 𝕜 f s x 1
/--
Derivative of `f` at the point `x`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then
`f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`.
-/
def deriv (f : 𝕜 → F) (x : 𝕜) :=
fderiv 𝕜 f x 1
variables {f f₀ f₁ g : 𝕜 → F}
variables {f' f₀' f₁' g' : F}
variables {x : 𝕜}
variables {s t : set 𝕜}
variables {L L₁ L₂ : filter 𝕜}
/-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/
lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L :=
by simp [has_deriv_at_filter]
lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L :=
has_fderiv_at_filter_iff_has_deriv_at_filter.mp
/-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/
lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
/-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/
lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x ↔
has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
iff.rfl
lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x :=
has_fderiv_within_at_iff_has_deriv_within_at.mp
lemma has_deriv_within_at.has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
has_deriv_within_at_iff_has_fderiv_within_at.mp
/-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/
lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x → has_deriv_at f (f' 1) x :=
has_fderiv_at_iff_has_deriv_at.mp
lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x :=
by simp [has_strict_deriv_at, has_strict_fderiv_at]
protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x :=
has_strict_fderiv_at_iff_has_strict_deriv_at.mp
lemma has_strict_deriv_at_iff_has_strict_fderiv_at :
has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _
/-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/
lemma has_deriv_at_iff_has_fderiv_at {f' : F} :
has_deriv_at f f' x ↔
has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _
lemma deriv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 :=
by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption }
lemma differentiable_within_at_of_deriv_within_ne_zero (h : deriv_within f s x ≠ 0) :
differentiable_within_at 𝕜 f s x :=
not_imp_comm.1 deriv_within_zero_of_not_differentiable_within_at h
lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 :=
by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption }
lemma differentiable_at_of_deriv_ne_zero (h : deriv f x ≠ 0) : differentiable_at 𝕜 f x :=
not_imp_comm.1 deriv_zero_of_not_differentiable_at h
theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x)
(h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' :=
smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁
theorem has_deriv_at_filter_iff_is_o :
has_deriv_at_filter f f' x L ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[L] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_filter_iff_tendsto :
has_deriv_at_filter f f' x L ↔
tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_within_at_iff_is_o :
has_deriv_within_at f f' s x
↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝[s] x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_at_iff_is_o :
has_deriv_at f f' x ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝 x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) :
has_deriv_at f f' x :=
h.has_fderiv_at
/-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical
definition with a limit. In this version we have to take the limit along the subset `-{x}`,
because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/
lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} :
has_deriv_at_filter f f' x L ↔ tendsto (slope f x) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') :=
begin
conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (norm_inv _).symm,
(norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] },
conv_rhs { rw [← nhds_translation_sub f', tendsto_comap_iff] },
refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _),
refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right,
simp only [(∘)],
rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul, slope_def_module]
end
lemma has_deriv_within_at_iff_tendsto_slope :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s \ {x}] x) (𝓝 f') :=
begin
simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm],
exact has_deriv_at_filter_iff_tendsto_slope
end
lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s] x) (𝓝 f') :=
begin
convert ← has_deriv_within_at_iff_tendsto_slope,
exact diff_singleton_eq_self hs
end
lemma has_deriv_at_iff_tendsto_slope :
has_deriv_at f f' x ↔ tendsto (slope f x) (𝓝[≠] x) (𝓝 f') :=
has_deriv_at_filter_iff_tendsto_slope
theorem has_deriv_within_at_congr_set {s t u : set 𝕜}
(hu : u ∈ 𝓝 x) (h : s ∩ u = t ∩ u) :
has_deriv_within_at f f' s x ↔ has_deriv_within_at f f' t x :=
by simp_rw [has_deriv_within_at, nhds_within_eq_nhds_within' hu h]
alias has_deriv_within_at_congr_set ↔ has_deriv_within_at.congr_set _
@[simp] lemma has_deriv_within_at_diff_singleton :
has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x :=
by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem]
@[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] :
has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x :=
by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Ioi_iff_Ici ↔
has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici
@[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] :
has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x :=
by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Iio_iff_Iic ↔
has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic
theorem has_deriv_within_at.Ioi_iff_Ioo [linear_order 𝕜] [order_closed_topology 𝕜] {x y : 𝕜}
(h : x < y) :
has_deriv_within_at f f' (Ioo x y) x ↔ has_deriv_within_at f f' (Ioi x) x :=
has_deriv_within_at_congr_set (is_open_Iio.mem_nhds h) $
by { rw [Ioi_inter_Iio, inter_eq_left_iff_subset], exact Ioo_subset_Iio_self }
alias has_deriv_within_at.Ioi_iff_Ioo ↔
has_deriv_within_at.Ioi_of_Ioo has_deriv_within_at.Ioo_of_Ioi
theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔
(λh, f (x + h) - f x - h • f') =o[𝓝 0] (λh, h) :=
has_fderiv_at_iff_is_o_nhds_zero
theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_deriv_at_filter f f' x L₁ :=
has_fderiv_at_filter.mono h hst
theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) :
has_deriv_within_at f f' s x :=
has_fderiv_within_at.mono h hst
theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) :
has_deriv_at_filter f f' x L :=
has_fderiv_at.has_fderiv_at_filter h hL
theorem has_deriv_at.has_deriv_within_at
(h : has_deriv_at f f' x) : has_deriv_within_at f f' s x :=
has_fderiv_at.has_fderiv_within_at h
lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
has_fderiv_within_at.differentiable_within_at h
lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x :=
has_fderiv_at.differentiable_at h
@[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x :=
has_fderiv_within_at_univ
theorem has_deriv_at.unique
(h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' :=
smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁
lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter' h
lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter h
lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x)
(ht : has_deriv_within_at f f' t x) :
has_deriv_within_at f f' (s ∪ t) x :=
hs.has_fderiv_within_at.union ht.has_fderiv_within_at
lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x :=
(has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_deriv_at f f' x :=
has_fderiv_within_at.has_fderiv_at h hs
lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_deriv_within_at f (deriv_within f s x) s x :=
h.has_fderiv_within_at.has_deriv_within_at
lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x :=
h.has_fderiv_at.has_deriv_at
@[simp] lemma has_deriv_at_deriv_iff : has_deriv_at f (deriv f x) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, h.differentiable_at, λ h, h.has_deriv_at⟩
@[simp] lemma has_deriv_within_at_deriv_within_iff :
has_deriv_within_at f (deriv_within f s x) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, h.differentiable_within_at, λ h, h.has_deriv_within_at⟩
lemma differentiable_on.has_deriv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
has_deriv_at f (deriv f x) x :=
(h.has_fderiv_at hs).has_deriv_at
lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' :=
h.differentiable_at.has_deriv_at.unique h
lemma deriv_eq {f' : 𝕜 → F} (h : ∀ x, has_deriv_at f (f' x) x) : deriv f = f' :=
funext $ λ x, (h x).deriv
lemma has_deriv_within_at.deriv_within
(h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within f s x = f' :=
hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h
lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x :=
rfl
lemma deriv_within_fderiv_within :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x :=
by simp [deriv_within]
lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x :=
rfl
lemma deriv_fderiv :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x :=
by simp [deriv]
lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x)
(hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x :=
by { unfold deriv_within deriv, rw h.fderiv_within hxs }
theorem has_deriv_within_at.deriv_eq_zero (hd : has_deriv_within_at f 0 s x)
(H : unique_diff_within_at 𝕜 s x) : deriv f x = 0 :=
(em' (differentiable_at 𝕜 f x)).elim deriv_zero_of_not_differentiable_at $
λ h, H.eq_deriv _ h.has_deriv_at.has_deriv_within_at hd
lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
deriv_within f s x = deriv_within f t x :=
((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht
@[simp] lemma deriv_within_univ : deriv_within f univ = deriv f :=
by { ext, unfold deriv_within deriv, rw fderiv_within_univ }
lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
deriv_within f (s ∩ t) x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_inter ht hs }
lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) :
deriv_within f s x = deriv f x :=
by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl }
lemma deriv_mem_iff {f : 𝕜 → F} {s : set F} {x : 𝕜} :
deriv f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ deriv f x ∈ s) ∨
(¬differentiable_at 𝕜 f x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_at 𝕜 f x; simp [deriv_zero_of_not_differentiable_at, *]
lemma deriv_within_mem_iff {f : 𝕜 → F} {t : set 𝕜} {s : set F} {x : 𝕜} :
deriv_within f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ deriv_within f t x ∈ s) ∨
(¬differentiable_within_at 𝕜 f t x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_within_at 𝕜 f t x;
simp [deriv_within_zero_of_not_differentiable_within_at, *]
lemma differentiable_within_at_Ioi_iff_Ici [partial_order 𝕜] :
differentiable_within_at 𝕜 f (Ioi x) x ↔ differentiable_within_at 𝕜 f (Ici x) x :=
⟨λ h, h.has_deriv_within_at.Ici_of_Ioi.differentiable_within_at,
λ h, h.has_deriv_within_at.Ioi_of_Ici.differentiable_within_at⟩
lemma deriv_within_Ioi_eq_Ici {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] (f : ℝ → E)
(x : ℝ) :
deriv_within f (Ioi x) x = deriv_within f (Ici x) x :=
begin
by_cases H : differentiable_within_at ℝ f (Ioi x) x,
{ have A := H.has_deriv_within_at.Ici_of_Ioi,
have B := (differentiable_within_at_Ioi_iff_Ici.1 H).has_deriv_within_at,
simpa using (unique_diff_on_Ici x).eq le_rfl A B },
{ rw [deriv_within_zero_of_not_differentiable_within_at H,
deriv_within_zero_of_not_differentiable_within_at],
rwa differentiable_within_at_Ioi_iff_Ici at H }
end
section congr
/-! ### Congruence properties of derivatives -/
theorem filter.eventually_eq.has_deriv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') :
has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L :=
h₀.has_fderiv_at_filter_iff hx (by simp [h₁])
lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L :=
by rwa hL.has_deriv_at_filter_iff hx rfl
lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x :=
has_fderiv_within_at.congr_mono h ht hx h₁
lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_deriv_within_at.congr_of_mem (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr hs (hs _ hx)
lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx)
lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _)
lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw hL.fderiv_within_eq hs hx }
lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr hs hL hx }
lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x :=
by { unfold deriv, rwa filter.eventually_eq.fderiv_eq }
protected lemma filter.eventually_eq.deriv (h : f₁ =ᶠ[𝓝 x] f) : deriv f₁ =ᶠ[𝓝 x] deriv f :=
h.eventually_eq_nhds.mono $ λ x h, h.deriv_eq
end congr
section id
/-! ### Derivative of the identity -/
variables (s x L)
theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L :=
(has_fderiv_at_filter_id x L).has_deriv_at_filter
theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id : has_deriv_at id 1 x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x :=
has_deriv_at_filter_id _ _
theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x :=
(has_strict_fderiv_at_id x).has_strict_deriv_at
lemma deriv_id : deriv id x = 1 :=
has_deriv_at.deriv (has_deriv_at_id x)
@[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id
@[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) = λ _, 1 := deriv_id'
lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 :=
(has_deriv_within_at_id x s).deriv_within hxs
end id
section const
/-! ### Derivative of constant functions -/
variables (c : F) (s x L)
theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L :=
(has_fderiv_at_filter_const c x L).has_deriv_at_filter
theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x :=
(has_strict_fderiv_at_const c x).has_strict_deriv_at
theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x :=
has_deriv_at_filter_const _ _ _
theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x :=
has_deriv_at_filter_const _ _ _
lemma deriv_const : deriv (λ x, c) x = 0 :=
has_deriv_at.deriv (has_deriv_at_const x c)
@[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 :=
funext (λ x, deriv_const x c)
lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 :=
(has_deriv_within_at_const _ _ _).deriv_within hxs
end const
section continuous_linear_map
/-! ### Derivative of continuous linear maps -/
variables (e : 𝕜 →L[𝕜] F)
protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.has_fderiv_at_filter.has_deriv_at_filter
protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.has_strict_fderiv_at.has_strict_deriv_at
protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end continuous_linear_map
section linear_map
/-! ### Derivative of bundled linear maps -/
variables (e : 𝕜 →ₗ[𝕜] F)
protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.to_continuous_linear_map₁.has_deriv_at_filter
protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.to_continuous_linear_map₁.has_strict_deriv_at
protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end linear_map
section add
/-! ### Derivative of the sum of two functions -/
theorem has_deriv_at_filter.add
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ y, f y + g y) (f' + g') x L :=
by simpa using (hf.add hg).has_deriv_at_filter
theorem has_strict_deriv_at.add
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ y, f y + g y) (f' + g') x :=
by simpa using (hf.add hg).has_strict_deriv_at
theorem has_deriv_within_at.add
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_deriv_at.add
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x :=
(hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λy, f y + g y) x = deriv f x + deriv g x :=
(hf.has_deriv_at.add hg.has_deriv_at).deriv
theorem has_deriv_at_filter.add_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c)
theorem has_deriv_within_at.add_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_deriv_at.add_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y + c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_add_const hxs]
lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x :=
by simp only [deriv, fderiv_add_const]
@[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f :=
funext $ λ x, deriv_add_const c
theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf
theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c + f y) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_const_add hxs]
lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x :=
by simp only [deriv, fderiv_const_add]
@[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f :=
funext $ λ x, deriv_const_add c
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F}
theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) :
has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter
theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) :
has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at
theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) :
has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_deriv_at_filter.sum h
theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) :
has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_deriv_at_filter.sum h
lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x :=
(has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs
@[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x :=
(has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv
end sum
section pi
/-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/
variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)]
[Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i}
@[simp] lemma has_strict_deriv_at_pi :
has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_deriv_at_filter_pi :
has_deriv_at_filter φ φ' x L ↔
∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L :=
has_fderiv_at_filter_pi'
lemma has_deriv_at_pi :
has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:=
has_deriv_at_filter_pi
lemma has_deriv_within_at_pi :
has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:=
has_deriv_at_filter_pi
lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x :=
(has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs
lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) :
deriv φ x = λ i, deriv (λ x, φ x i) x :=
(has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv
end pi
section smul
/-! ### Derivative of the multiplication of a scalar function and a vector function -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : 𝕜 → 𝕜'} {c' : 𝕜'}
theorem has_deriv_within_at.smul
(hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x :=
by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at
theorem has_deriv_at.smul
(hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul hf
end
theorem has_strict_deriv_at.smul
(hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
by simpa using (hc.smul hf).has_strict_deriv_at
lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x :=
(hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs
lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x :=
(hc.has_deriv_at.smul hf.has_deriv_at).deriv
theorem has_strict_deriv_at.smul_const
(hc : has_strict_deriv_at c c' x) (f : F) :
has_strict_deriv_at (λ y, c y • f) (c' • f) x :=
begin
have := hc.smul (has_strict_deriv_at_const x f),
rwa [smul_zero, zero_add] at this,
end
theorem has_deriv_within_at.smul_const
(hc : has_deriv_within_at c c' s x) (f : F) :
has_deriv_within_at (λ y, c y • f) (c' • f) s x :=
begin
have := hc.smul (has_deriv_within_at_const x s f),
rwa [smul_zero, zero_add] at this
end
theorem has_deriv_at.smul_const
(hc : has_deriv_at c c' x) (f : F) :
has_deriv_at (λ y, c y • f) (c' • f) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul_const f
end
lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f :=
(hc.has_deriv_within_at.smul_const f).deriv_within hxs
lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
deriv (λ y, c y • f) x = (deriv c x) • f :=
(hc.has_deriv_at.smul_const f).deriv
end smul
section const_smul
variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F]
[has_continuous_const_smul R F]
theorem has_strict_deriv_at.const_smul
(c : R) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c • f y) (c • f') x :=
by simpa using (hf.const_smul c).has_strict_deriv_at
theorem has_deriv_at_filter.const_smul
(c : R) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c • f y) (c • f') x L :=
by simpa using (hf.const_smul c).has_deriv_at_filter
theorem has_deriv_within_at.const_smul
(c : R) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c • f y) (c • f') s x :=
hf.const_smul c
theorem has_deriv_at.const_smul (c : R) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c • f y) (c • f') x :=
hf.const_smul c
lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(c : R) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c • f y) s x = c • deriv_within f s x :=
(hf.has_deriv_within_at.const_smul c).deriv_within hxs
lemma deriv_const_smul (c : R) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c • f y) x = c • deriv f x :=
(hf.has_deriv_at.const_smul c).deriv
end const_smul
section neg
/-! ### Derivative of the negative of a function -/
theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, -f x) (-f') x L :=
by simpa using h.neg.has_deriv_at_filter
theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x :=
h.neg
theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, -f x) (-f') x :=
by simpa using h.neg.has_strict_deriv_at
lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λy, -f y) s x = - deriv_within f s x :=
by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply]
lemma deriv.neg : deriv (λy, -f y) x = - deriv f x :=
by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply]
@[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) :=
funext $ λ x, deriv.neg
end neg
section neg2
/-! ### Derivative of the negation function (i.e `has_neg.neg`) -/
variables (s x L)
theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L :=
has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _
theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x :=
has_strict_deriv_at.neg $ has_strict_deriv_at_id _
lemma deriv_neg : deriv has_neg.neg x = -1 :=
has_deriv_at.deriv (has_deriv_at_neg x)
@[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 :=
funext deriv_neg
@[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 :=
deriv_neg x
lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 :=
(has_deriv_within_at_neg x s).deriv_within hxs
lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) :=
differentiable.neg differentiable_id
lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s :=
differentiable_on.neg differentiable_on_id
end neg2
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_deriv_at_filter.sub
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_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_deriv_within_at.sub
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_deriv_at.sub
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
theorem has_strict_deriv_at.sub
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x :=
(hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λ y, f y - g y) x = deriv f x - deriv g x :=
(hf.has_deriv_at.sub hg.has_deriv_at).deriv
theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) :
(λ x', f x' - f x) =O[L] (λ x', x' - x) :=
has_fderiv_at_filter.is_O_sub h
theorem has_deriv_at_filter.is_O_sub_rev (hf : has_deriv_at_filter f f' x L) (hf' : f' ≠ 0) :
(λ x', x' - x) =O[L] (λ x', f x' - f x) :=
suffices antilipschitz_with ∥f'∥₊⁻¹ (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f'), from hf.is_O_sub_rev this,
add_monoid_hom_class.antilipschitz_of_bound (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') $
λ x, by simp [norm_smul, ← div_eq_inv_mul, mul_div_cancel _ (mt norm_eq_zero.1 hf')]
theorem has_deriv_at_filter.sub_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_deriv_within_at.sub_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_deriv_at.sub_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y - c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_sub_const hxs]
lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x :=
by simp only [deriv, fderiv_sub_const]
theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c - f y) s x = -deriv_within f s x :=
by simp [deriv_within, fderiv_within_const_sub hxs]
lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x :=
by simp only [← deriv_within_univ,
deriv_within_const_sub (unique_diff_within_at_univ : unique_diff_within_at 𝕜 _ _)]
end sub
section continuous
/-! ### Continuity of a function admitting a derivative -/
theorem has_deriv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem has_deriv_within_at.continuous_within_at
(h : has_deriv_within_at f f' s x) : continuous_within_at f s x :=
has_deriv_at_filter.tendsto_nhds inf_le_left h
theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x :=
has_deriv_at_filter.tendsto_nhds le_rfl h
protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F}
(hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s :=
λ x hx, (hderiv x hx).continuous_at.continuous_within_at
end continuous
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {G : Type w} [normed_add_comm_group G] [normed_space 𝕜 G]
variables {f₂ : 𝕜 → G} {f₂' : G}
lemma has_deriv_at_filter.prod
(hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) :
has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L :=
hf₁.prod hf₂
lemma has_deriv_within_at.prod
(hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) :
has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x :=
hf₁.prod hf₂
lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) :
has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
lemma has_strict_deriv_at.prod (hf₁ : has_strict_deriv_at f₁ f₁' x)
(hf₂ : has_strict_deriv_at f₂ f₂' x) :
has_strict_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
end cartesian_product
section composition
/-!
### Derivative of the composition of a vector function and a scalar function
We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp`
in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also
because the `comp` version with the shorter name will show up much more often in applications).
The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to
usual multiplication in `comp` lemmas.
-/
/- 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 -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {s' t' : set 𝕜'}
{h : 𝕜 → 𝕜'} {h₁ : 𝕜 → 𝕜} {h₂ : 𝕜' → 𝕜'} {h' h₂' : 𝕜'} {h₁' : 𝕜}
{g₁ : 𝕜' → F} {g₁' : F} {L' : filter 𝕜'} (x)
theorem has_deriv_at_filter.scomp
(hg : has_deriv_at_filter g₁ g₁' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L'):
has_deriv_at_filter (g₁ ∘ h) (h' • g₁') x L :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh hL).has_deriv_at_filter
theorem has_deriv_within_at.scomp_has_deriv_at
(hg : has_deriv_within_at g₁ g₁' s' (h x))
(hh : has_deriv_at h h' x) (hs : ∀ x, h x ∈ s') :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh $ tendsto_inf.2 ⟨hh.continuous_at, tendsto_principal.2 $ eventually_of_forall hs⟩
theorem has_deriv_within_at.scomp
(hg : has_deriv_within_at g₁ g₁' t' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s t') :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
hg.scomp x hh $ hh.continuous_within_at.tendsto_nhds_within hst
/-- The chain rule. -/
theorem has_deriv_at.scomp
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh hh.continuous_at
theorem has_strict_deriv_at.scomp
(hg : has_strict_deriv_at g₁ g₁' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (g₁ ∘ h) (h' • g₁') x :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh).has_strict_deriv_at
theorem has_deriv_at.scomp_has_deriv_within_at
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
has_deriv_within_at.scomp x hg.has_deriv_within_at hh (maps_to_univ _ _)
lemma deriv_within.scomp
(hg : differentiable_within_at 𝕜' g₁ t' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s t') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (g₁ ∘ h) s x = deriv_within h s x • deriv_within g₁ t' (h x) :=
(has_deriv_within_at.scomp x hg.has_deriv_within_at hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.scomp
(hg : differentiable_at 𝕜' g₁ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (g₁ ∘ h) x = deriv h x • deriv g₁ (h x) :=
(has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at).deriv
/-! ### Derivative of the composition of a scalar and vector functions -/
theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
{L'' : filter E} (hh₂ : has_deriv_at_filter h₂ h₂' (f x) L')
(hf : has_fderiv_at_filter f f' x L'') (hL : tendsto f L'' L') :
has_fderiv_at_filter (h₂ ∘ f) (h₂' • f') x L'' :=
by { convert (hh₂.restrict_scalars 𝕜).comp x hf hL, ext x, simp [mul_comm] }
theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_strict_deriv_at h₂ h₂' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
begin
rw has_strict_deriv_at at hh,
convert (hh.restrict_scalars 𝕜).comp x hf,
ext x,
simp [mul_comm]
end
theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_at
theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_within_at
theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s t} (x)
(hh : has_deriv_within_at h₂ h₂' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : maps_to f s t) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf $ hf.continuous_within_at.tendsto_nhds_within hst
/-! ### Derivative of the composition of two scalar functions -/
theorem has_deriv_at_filter.comp
(hh₂ : has_deriv_at_filter h₂ h₂' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L') :
has_deriv_at_filter (h₂ ∘ h) (h₂' * h') x L :=
by { rw mul_comm, exact hh₂.scomp x hh hL }
theorem has_deriv_within_at.comp
(hh₂ : has_deriv_within_at h₂ h₂' s' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s s') :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
by { rw mul_comm, exact hh₂.scomp x hh hst, }
/-- The chain rule. -/
theorem has_deriv_at.comp
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (h₂ ∘ h) (h₂' * h') x :=
hh₂.comp x hh hh.continuous_at
theorem has_strict_deriv_at.comp
(hh₂ : has_strict_deriv_at h₂ h₂' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (h₂ ∘ h) (h₂' * h') x :=
by { rw mul_comm, exact hh₂.scomp x hh }
theorem has_deriv_at.comp_has_deriv_within_at
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
hh₂.has_deriv_within_at.comp x hh (maps_to_univ _ _)
lemma deriv_within.comp
(hh₂ : differentiable_within_at 𝕜' h₂ s' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s s') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (h₂ ∘ h) s x = deriv_within h₂ s' (h x) * deriv_within h s x :=
(hh₂.has_deriv_within_at.comp x hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.comp
(hh₂ : differentiable_at 𝕜' h₂ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (h₂ ∘ h) x = deriv h₂ (h x) * deriv h x :=
(hh₂.has_deriv_at.comp x hh.has_deriv_at).deriv
protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_deriv_at_filter (f^[n]) (f'^n) x L :=
begin
have := hf.iterate hL hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_deriv_at (f^[n]) (f'^n) x :=
begin
have := has_fderiv_at.iterate hf hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_deriv_within_at (f^[n]) (f'^n) s x :=
begin
have := has_fderiv_within_at.iterate hf hx hs n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_deriv_at (f^[n]) (f'^n) x :=
begin
have := hf.iterate hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
end composition
section composition_vector
/-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/
open continuous_linear_map
variables {l : F → E} {l' : F →L[𝕜] E}
variable (x)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set
equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F}
(hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x)
(hst : maps_to f s t) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_fderiv_within_at hst).has_deriv_within_at
theorem has_fderiv_at.comp_has_deriv_within_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
hl.has_fderiv_within_at.comp_has_deriv_within_at x hf (maps_to_univ _ _)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the
Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) :
has_deriv_at (l ∘ f) (l' f') x :=
has_deriv_within_at_univ.mp $ hl.comp_has_deriv_within_at x hf.has_deriv_within_at
theorem has_strict_fderiv_at.comp_has_strict_deriv_at
(hl : has_strict_fderiv_at l l' (f x)) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (l ∘ f) (l' f') x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_strict_fderiv_at).has_strict_deriv_at
lemma fderiv_within.comp_deriv_within {t : set F}
(hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hs : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) :=
(hl.has_fderiv_within_at.comp_has_deriv_within_at x hf.has_deriv_within_at hs).deriv_within hxs
lemma fderiv.comp_deriv
(hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) :
deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) :=
(hl.has_fderiv_at.comp_has_deriv_at x hf.has_deriv_at).deriv
end composition_vector
section mul
/-! ### Derivative of the multiplication of two functions -/
variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜']
[normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'}
theorem has_deriv_within_at.mul
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x :=
begin
have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul hd
end
theorem has_strict_deriv_at.mul
(hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x :=
(hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x :=
(hc.has_deriv_at.mul hd.has_deriv_at).deriv
theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) :
has_deriv_within_at (λ y, c y * d) (c' * d) s x :=
begin
convert hc.mul (has_deriv_within_at_const x s d),
rw [mul_zero, add_zero]
end
theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) :
has_deriv_at (λ y, c y * d) (c' * d) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul_const d
end
theorem has_deriv_at_mul_const (c : 𝕜) : has_deriv_at (λ x, x * c) c x :=
by simpa only [one_mul] using (has_deriv_at_id' x).mul_const c
theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) :
has_strict_deriv_at (λ y, c y * d) (c' * d) x :=
begin
convert hc.mul (has_strict_deriv_at_const x d),
rw [mul_zero, add_zero]
end
lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) :
deriv_within (λ y, c y * d) s x = deriv_within c s x * d :=
(hc.has_deriv_within_at.mul_const d).deriv_within hxs
lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) :
deriv (λ y, c y * d) x = deriv c x * d :=
(hc.has_deriv_at.mul_const d).deriv
lemma deriv_mul_const_field (v : 𝕜') :
deriv (λ y, u y * v) x = deriv u x * v :=
begin
by_cases hu : differentiable_at 𝕜 u x,
{ exact deriv_mul_const hu v },
{ rw [deriv_zero_of_not_differentiable_at hu, zero_mul],
rcases eq_or_ne v 0 with rfl|hd,
{ simp only [mul_zero, deriv_const] },
{ refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu),
simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } }
end
@[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v :=
funext $ λ _, deriv_mul_const_field v
theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c * d y) (c * d') s x :=
begin
convert (has_deriv_within_at_const x s c).mul hd,
rw [zero_mul, zero_add]
end
theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c * d y) (c * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hd.const_mul c
end
theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c * d y) (c * d') x :=
begin
convert (has_strict_deriv_at_const _ _).mul hd,
rw [zero_mul, zero_add]
end
lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c * d y) s x = c * deriv_within d s x :=
(hd.has_deriv_within_at.const_mul c).deriv_within hxs
lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c * d y) x = c * deriv d x :=
(hd.has_deriv_at.const_mul c).deriv
lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x :=
by simp only [mul_comm u, deriv_mul_const_field]
@[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x :=
funext (λ x, deriv_const_mul_field u)
end mul
section inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x :=
begin
suffices : (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)]
(λ p, (p.1 - p.2) * 1),
{ refine this.congr' _ (eventually_of_forall $ λ _, mul_one _),
refine eventually.mono (is_open.mem_nhds (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _,
rintro ⟨y, z⟩ ⟨hy, hz⟩,
simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz], ring, },
refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _),
rw [← sub_self (x * x)⁻¹],
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx)
end
theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) :
has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x :=
(has_strict_deriv_at_inv x_ne_zero).has_deriv_at
theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x :=
(has_deriv_at_inv x_ne_zero).has_deriv_within_at
lemma differentiable_at_inv :
differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:=
⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at,
λ H, (has_deriv_at_inv H).differentiable_at⟩
lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x⁻¹) s x :=
(differentiable_at_inv.2 x_ne_zero).differentiable_within_at
lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} :=
λx hx, differentiable_within_at_inv hx
lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ :=
begin
rcases eq_or_ne x 0 with rfl|hne,
{ simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] },
{ exact (has_deriv_at_inv hne).deriv }
end
@[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv)
lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ :=
begin
rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact deriv_inv
end
lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
has_deriv_at_inv x_ne_zero
lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(has_fderiv_at_inv x_ne_zero).has_fderiv_within_at
lemma fderiv_inv :
fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
by rw [← deriv_fderiv, deriv_inv]
lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
begin
rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact fderiv_inv
end
variables {c : 𝕜 → 𝕜} {c' : 𝕜}
lemma has_deriv_within_at.inv
(hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) :
has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x :=
begin
convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc,
field_simp
end
lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) :
has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.inv hx
end
lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) :
differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x :=
(hc.has_deriv_within_at.inv hx).differentiable_within_at
@[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
differentiable_at 𝕜 (λx, (c x)⁻¹) x :=
(hc.has_deriv_at.inv hx).differentiable_at
lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) :
differentiable_on 𝕜 (λx, (c x)⁻¹) s :=
λx h, (hc x h).inv (hx x h)
@[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) :
differentiable 𝕜 (λx, (c x)⁻¹) :=
λx, (hc x).inv (hx x)
lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 :=
(hc.has_deriv_within_at.inv hx).deriv_within hxs
@[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 :=
(hc.has_deriv_at.inv hx).deriv
end inverse
section division
/-! ### Derivative of `x ↦ c x / d x` -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{c d : 𝕜 → 𝕜'} {c' d' : 𝕜'}
lemma has_deriv_within_at.div
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) :
has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x :=
begin
convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x)
(hx : d x ≠ 0) :
has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) :
has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.div hd hx
end
lemma differentiable_within_at.div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) :
differentiable_within_at 𝕜 (λx, c x / d x) s x :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at
@[simp] lemma differentiable_at.div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
differentiable_at 𝕜 (λx, c x / d x) x :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at
lemma differentiable_on.div
(hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) :
differentiable_on 𝕜 (λx, c x / d x) s :=
λx h, (hc x h).div (hd x h) (hx x h)
@[simp] lemma differentiable.div
(hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) :
differentiable 𝕜 (λx, c x / d x) :=
λx, (hc x).div (hd x) (hx x)
lemma deriv_within_div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d x) s x
= ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs
@[simp] lemma deriv_div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv
lemma has_deriv_at.div_const (hc : has_deriv_at c c' x) (d : 𝕜') :
has_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_deriv_within_at.div_const (hc : has_deriv_within_at c c' s x) (d : 𝕜') :
has_deriv_within_at (λ x, c x / d) (c' / d) s x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_strict_deriv_at.div_const (hc : has_strict_deriv_at c c' x) (d : 𝕜') :
has_strict_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'} :
differentiable_within_at 𝕜 (λx, c x / d) s x :=
(hc.has_deriv_within_at.div_const _).differentiable_within_at
@[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜'} :
differentiable_at 𝕜 (λ x, c x / d) x :=
(hc.has_deriv_at.div_const _).differentiable_at
lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜'} :
differentiable_on 𝕜 (λx, c x / d) s :=
λ x hx, (hc x hx).div_const
@[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜'} :
differentiable 𝕜 (λx, c x / d) :=
λ x, (hc x).div_const
lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'}
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d) s x = (deriv_within c s x) / d :=
by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs]
@[simp] lemma deriv_div_const (d : 𝕜') :
deriv (λx, c x / d) x = (deriv c x) / d :=
by simp only [div_eq_mul_inv, deriv_mul_const_field]
end division
section clm_comp_apply
/-! ### Derivative of the pointwise composition/application of continuous linear maps -/
open continuous_linear_map
variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G}
{c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F}
lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x)
(hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x :=
begin
have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x)
(hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x :=
begin
have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, (c y).comp (d y))
(c'.comp (d x) + (c x).comp d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.clm_comp hd
end
lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x)
(hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x):
deriv_within (λ y, (c y).comp (d y)) s x =
((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) :=
(hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, (c y).comp (d y)) x =
((deriv c x).comp (d x) + (c x).comp (deriv d x)) :=
(hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv
lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x)
(hu : has_strict_deriv_at u u' x) :
has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x)
(hu : has_deriv_within_at u u' s x) :
has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x :=
begin
have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) :
has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) :
deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) :=
(hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) :
deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) :=
(hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv
end clm_comp_apply
theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) :
has_strict_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x)
(hf' : f' ≠ 0) :
has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
/-- 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_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_deriv_at g f'⁻¹ a :=
(hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a
nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` 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. -/
lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) :
has_strict_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
/-- 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_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_deriv_at g f'⁻¹ a :=
(hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
nonzero 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_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) :
has_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
∀ᶠ z in 𝓝[≠] x, f z ≠ f x :=
(has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne
⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩
lemma has_deriv_at.tendsto_punctured_nhds (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
tendsto f (𝓝[≠] x) (𝓝[≠] (f x)) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
h.continuous_at.continuous_within_at (h.eventually_ne hf')
theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a)
(hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) :
¬differentiable_within_at 𝕜 g s a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha,
simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _)
end
theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) :
¬differentiable_at 𝕜 g a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm,
simpa using this.unique (has_deriv_at_id a)
end
end
namespace polynomial
/-! ### Derivative of a polynomial -/
variables {x : 𝕜} {s : set 𝕜}
variable (p : 𝕜[X])
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_strict_deriv_at (x : 𝕜) :
has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
begin
apply p.induction_on,
{ simp [has_strict_deriv_at_const] },
{ assume p q hp hq,
convert hp.add hq;
simp },
{ assume n a h,
convert h.mul (has_strict_deriv_at_id x),
{ ext y, simp [pow_add, mul_assoc] },
{ simp [pow_add], ring } }
end
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
(p.has_strict_deriv_at x).has_deriv_at
protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x :=
(p.has_deriv_at x).has_deriv_within_at
protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x :=
(p.has_deriv_at x).differentiable_at
protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x :=
p.differentiable_at.differentiable_within_at
protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) :=
λx, p.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s :=
p.differentiable.differentiable_on
@[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x :=
(p.has_deriv_at x).deriv
protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, p.eval x) s x = p.derivative.eval x :=
begin
rw differentiable_at.deriv_within p.differentiable_at hxs,
exact p.deriv
end
protected lemma has_fderiv_at (x : 𝕜) :
has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x :=
p.has_deriv_at x
protected lemma has_fderiv_within_at (x : 𝕜) :
has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x :=
(p.has_fderiv_at x).has_fderiv_within_at
@[simp] protected lemma fderiv :
fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_at x).fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_within_at x).fderiv_within hxs
end polynomial
section pow
/-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/
variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜}
variable (n : ℕ)
lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) :
has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
begin
convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x,
{ simp },
{ rw [polynomial.derivative_C_mul_X_pow], simp }
end
lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
(has_strict_deriv_at_pow n x).has_deriv_at
theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x :=
(has_deriv_at_pow n x).has_deriv_within_at
lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x :=
(has_deriv_at_pow n x).differentiable_at
lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x :=
(differentiable_at_pow n).differentiable_within_at
lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) :=
λ x, differentiable_at_pow n
lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s :=
(differentiable_pow n).differentiable_on
lemma deriv_pow : deriv (λ x, x^n) x = (n : 𝕜) * x^(n-1) :=
(has_deriv_at_pow n x).deriv
@[simp] lemma deriv_pow' : deriv (λ x, x^n) = λ x, (n : 𝕜) * x^(n-1) :=
funext $ λ x, deriv_pow n
lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) :=
(has_deriv_within_at_pow n x s).deriv_within hxs
lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) :
has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x :=
(has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc
lemma has_deriv_at.pow (hc : has_deriv_at c c' x) :
has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x :=
by { rw ← has_deriv_within_at_univ at *, exact hc.pow n }
lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) :=
(hc.has_deriv_within_at.pow n).deriv_within hxs
@[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) :
deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) :=
(hc.has_deriv_at.pow n).deriv
end pow
section zpow
/-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {x : 𝕜} {s : set 𝕜} {m : ℤ}
lemma has_strict_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
begin
have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x,
{ assume m hm,
lift m to ℕ using (le_of_lt hm),
simp only [zpow_coe_nat, int.cast_coe_nat],
convert has_strict_deriv_at_pow _ _ using 2,
rw [← int.coe_nat_one, ← int.coe_nat_sub, zpow_coe_nat],
norm_cast at hm,
exact nat.succ_le_of_lt hm },
rcases lt_trichotomy m 0 with hm|hm|hm,
{ have hx : x ≠ 0, from h.resolve_right hm.not_le,
have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm));
[skip, exact zpow_ne_zero_of_ne_zero hx _],
simp only [(∘), zpow_neg, one_div, inv_inv, smul_eq_mul] at this,
convert this using 1,
rw [sq, mul_inv, inv_inv, int.cast_neg, neg_mul, neg_mul_neg,
← zpow_add₀ hx, mul_assoc, ← zpow_add₀ hx], congr, abel },
{ simp only [hm, zpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] },
{ exact this m hm }
end
lemma has_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
(has_strict_deriv_at_zpow m x h).has_deriv_at
theorem has_deriv_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) (s : set 𝕜) :
has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x :=
(has_deriv_at_zpow m x h).has_deriv_within_at
lemma differentiable_at_zpow : differentiable_at 𝕜 (λx, x^m) x ↔ x ≠ 0 ∨ 0 ≤ m :=
⟨λ H, normed_field.continuous_at_zpow.1 H.continuous_at,
λ H, (has_deriv_at_zpow m x H).differentiable_at⟩
lemma differentiable_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λx, x^m) s x :=
(differentiable_at_zpow.mpr h).differentiable_within_at
lemma differentiable_on_zpow (m : ℤ) (s : set 𝕜) (h : (0 : 𝕜) ∉ s ∨ 0 ≤ m) :
differentiable_on 𝕜 (λx, x^m) s :=
λ x hxs, differentiable_within_at_zpow m x $ h.imp_left $ ne_of_mem_of_not_mem hxs
lemma deriv_zpow (m : ℤ) (x : 𝕜) : deriv (λ x, x ^ m) x = m * x ^ (m - 1) :=
begin
by_cases H : x ≠ 0 ∨ 0 ≤ m,
{ exact (has_deriv_at_zpow m x H).deriv },
{ rw deriv_zero_of_not_differentiable_at (mt differentiable_at_zpow.1 H),
push_neg at H, rcases H with ⟨rfl, hm⟩,
rw [zero_zpow _ ((sub_one_lt _).trans hm).ne, mul_zero] }
end
@[simp] lemma deriv_zpow' (m : ℤ) : deriv (λ x : 𝕜, x ^ m) = λ x, m * x ^ (m - 1) :=
funext $ deriv_zpow m
lemma deriv_within_zpow (hxs : unique_diff_within_at 𝕜 s x) (h : x ≠ 0 ∨ 0 ≤ m) :
deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) :=
(has_deriv_within_at_zpow m x h s).deriv_within hxs
@[simp] lemma iter_deriv_zpow' (m : ℤ) (k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ m) = λ x, (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
begin
induction k with k ihk,
{ simp only [one_mul, int.coe_nat_zero, id, sub_zero, finset.prod_range_zero,
function.iterate_zero] },
{ simp only [function.iterate_succ_apply', ihk, deriv_const_mul_field', deriv_zpow',
finset.prod_range_succ, int.coe_nat_succ, ← sub_sub, int.cast_sub, int.cast_coe_nat,
mul_assoc], }
end
lemma iter_deriv_zpow (m : ℤ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λ y, y ^ m) x = (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
congr_fun (iter_deriv_zpow' m k) x
lemma iter_deriv_pow (n : ℕ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i)) * x^(n-k) :=
begin
simp only [← zpow_coe_nat, iter_deriv_zpow, int.cast_coe_nat],
cases le_or_lt k n with hkn hnk,
{ rw int.coe_nat_sub hkn },
{ have : ∏ i in finset.range k, (n - i : 𝕜) = 0,
from finset.prod_eq_zero (finset.mem_range.2 hnk) (sub_self _),
simp only [this, zero_mul] }
end
@[simp] lemma iter_deriv_pow' (n k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ n) = λ x, (∏ i in finset.range k, (n - i)) * x ^ (n - k) :=
funext $ λ x, iter_deriv_pow n x k
lemma iter_deriv_inv (k : ℕ) (x : 𝕜) :
deriv^[k] has_inv.inv x = (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
by simpa only [zpow_neg_one, int.cast_neg, int.cast_one] using iter_deriv_zpow (-1) x k
@[simp] lemma iter_deriv_inv' (k : ℕ) :
deriv^[k] has_inv.inv = λ x : 𝕜, (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
funext (iter_deriv_inv k)
variables {f : E → 𝕜} {t : set E} {a : E}
lemma differentiable_within_at.zpow (hf : differentiable_within_at 𝕜 f t a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λ x, f x ^ m) t a :=
(differentiable_at_zpow.2 h).comp_differentiable_within_at a hf
lemma differentiable_at.zpow (hf : differentiable_at 𝕜 f a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_at 𝕜 (λ x, f x ^ m) a :=
(differentiable_at_zpow.2 h).comp a hf
lemma differentiable_on.zpow (hf : differentiable_on 𝕜 f t) (h : (∀ x ∈ t, f x ≠ 0) ∨ 0 ≤ m) :
differentiable_on 𝕜 (λ x, f x ^ m) t :=
λ x hx, (hf x hx).zpow $ h.imp_left (λ h, h x hx)
lemma differentiable.zpow (hf : differentiable 𝕜 f) (h : (∀ x, f x ≠ 0) ∨ 0 ≤ m) :
differentiable 𝕜 (λ x, f x ^ m) :=
λ x, (hf x).zpow $ h.imp_left (λ h, h x)
end zpow
/-! ### Support of derivatives -/
section support
open function
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {f : 𝕜 → F}
lemma support_deriv_subset : support (deriv f) ⊆ tsupport f :=
begin
intros x,
rw [← not_imp_not],
intro h2x,
rw [not_mem_tsupport_iff_eventually_eq] at h2x,
exact nmem_support.mpr (h2x.deriv_eq.trans (deriv_const x 0))
end
lemma has_compact_support.deriv (hf : has_compact_support f) : has_compact_support (deriv f) :=
hf.mono' support_deriv_subset
end support
/-! ### Upper estimates on liminf and limsup -/
section real
variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ}
lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) :
∀ᶠ z in 𝓝[s \ {x}] x, slope f x z < r :=
has_deriv_within_at_iff_tendsto_slope.1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x)
(hs : x ∉ s) (hr : f' < r) :
∀ᶠ z in 𝓝[s] x, slope f x z < r :=
(has_deriv_within_at_iff_tendsto_slope' hs).1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.liminf_right_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) :
∃ᶠ z in 𝓝[>] x, slope f x z < r :=
(hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently
end real
section real_space
open metric
variables {E : Type u} [normed_add_comm_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ}
{x r : ℝ}
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`. -/
lemma has_deriv_within_at.limsup_norm_slope_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
begin
have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr,
have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (is_open.mem_nhds is_open_Iio hr),
have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from mem_of_superset self_mem_nhds_within
(singleton_subset_iff.2 $ by simp [hr₀]),
have C := mem_sup.2 ⟨A, B⟩,
rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup] at C,
filter_upwards [C.1],
simp only [norm_smul, mem_Iio, norm_inv],
exact λ _, id
end
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`.
This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le`
where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/
lemma has_deriv_within_at.limsup_slope_norm_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
apply (hf.limsup_norm_slope_le hr).mono,
assume z hz,
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz,
exact inv_nonneg.2 (norm_nonneg _)
end
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le`
for a stronger version using limit superior and any set `s`. -/
lemma has_deriv_within_at.liminf_right_norm_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in 𝓝[>] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
(hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`.
See also
* `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using
limit superior and any set `s`;
* `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using
`∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/
lemma has_deriv_within_at.liminf_right_slope_norm_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in 𝓝[>] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently,
refine this.mp (eventually.mono self_mem_nhds_within _),
assume z hxz hz,
rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz
end
end real_space
|
046b96e140f625612eb341025c6cf899f6fad413 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/number_theory/lucas_lehmer.lean | d43bf93fdc37948fac2642f595a9cd88d40af957 | [
"Apache-2.0"
] | permissive | LibertasSpZ/mathlib | b9fcd46625eb940611adb5e719a4b554138dade6 | 33f7870a49d7cc06d2f3036e22543e6ec5046e68 | refs/heads/master | 1,672,066,539,347 | 1,602,429,158,000 | 1,602,429,158,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,093 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro, Scott Morrison, Ainsley Pahljina
-/
import tactic.ring_exp
import tactic.interval_cases
import data.nat.parity
import data.zmod.basic
import group_theory.order_of_element
import ring_theory.fintype
/-!
# The Lucas-Lehmer test for Mersenne primes.
We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and
prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`.
We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic
required to calculate the residue, and enables us to prove
```
example : prime (mersenne 127) :=
lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test)
```
## TODO
- Show reverse implication.
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Scott Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ := 2^p - 1
lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p :=
begin
dsimp [mersenne],
calc 0 < 2^1 - 1 : by norm_num
... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h)
end
namespace lucas_lehmer
open nat
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ
| 0 := 4
| (i+1) := (s i)^2 - 2
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/
def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1)
| 0 := 4
| (i+1) := (s_zmod i)^2 - 2
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def s_mod (p : ℕ) : ℕ → ℤ
| 0 := 4 % (2^p - 1)
| (i+1) := ((s_mod i)^2 - 2) % (2^p - 1)
lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 :=
begin
apply ne_of_gt, simp only [gt_iff_lt, sub_pos],
exact_mod_cast nat.one_lt_two_pow p w,
end
lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i :=
begin
cases i; dsimp [s_mod],
{ trivial, },
{ apply int.mod_nonneg, exact mersenne_int_ne_zero p w },
end
lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i :=
by cases i; simp [s_mod]
lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 :=
begin
rw ←s_mod_mod,
convert int.mod_lt _ _,
{ refine (abs_of_nonneg _).symm,
simp only [sub_nonneg, ge_iff_le],
exact_mod_cast nat.one_le_two_pow p, },
{ exact mersenne_int_ne_zero p w, },
end
lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):=
begin
induction i with i ih,
{ dsimp [s, s_zmod], norm_num, },
{ push_cast [s, s_zmod, ih] },
end
-- These next two don't make good `norm_cast` lemmas.
lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) :=
begin
have : 1 ≤ b^p := nat.one_le_pow p b w,
push_cast [this],
end
lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) :=
int.coe_nat_pow_pred 2 p dec_trivial
lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) :=
by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *]
/-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/
def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2)
lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) :
lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 :=
begin
dsimp [lucas_lehmer_residue],
rw s_zmod_eq_s_mod p,
split,
{ -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1`
-- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`.
intro h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h,
apply s_mod_nonneg _ (nat.lt_of_succ_lt w),
convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2),
push_cast [nat.one_le_two_pow p],
refl, },
{ intro h, rw h, simp, },
end
/--
A Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
@[derive decidable_pred]
def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩
instance fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) :=
q.2
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
@[derive [add_comm_group, decidable_eq, fintype, inhabited]]
def X (q : ℕ+) : Type := (zmod q) × (zmod q)
namespace X
variable {q : ℕ+}
@[ext]
lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y :=
begin
cases x, cases y,
congr; assumption
end
@[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl
@[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl
@[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl
@[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl
instance : has_mul (X q) :=
{ mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) }
@[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl
@[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl
instance : has_one (X q) :=
{ one := ⟨1,0⟩ }
@[simp] lemma one_fst : (1 : X q).1 = 1 := rfl
@[simp] lemma one_snd : (1 : X q).2 = 0 := rfl
@[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl
@[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl
@[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl
@[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, }
instance : monoid (X q) :=
{ mul_assoc := λ x y z, by { ext; { dsimp, ring }, },
one := ⟨1,0⟩,
one_mul := λ x, by { ext; simp, },
mul_one := λ x, by { ext; simp, },
..(infer_instance : has_mul (X q)) }
lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z :=
by { ext; { dsimp, ring }, }
lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z :=
by { ext; { dsimp, ring }, }
instance : ring (X q) :=
{ left_distrib := left_distrib,
right_distrib := right_distrib,
..(infer_instance : add_comm_group (X q)),
..(infer_instance : monoid (X q)) }
instance : comm_ring (X q) :=
{ mul_comm := λ x y, by { ext; { dsimp, ring }, },
..(infer_instance : ring (X q))}
instance [fact (1 < (q : ℕ))] : nontrivial (X q) :=
⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩
@[simp]
lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) :=
begin
induction n,
{ refl, },
{ dsimp, simp only [add_left_inj], exact n_ih, }
end
@[simp]
lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) :=
begin
induction n,
{ refl, },
{ dsimp, simp only [add_zero], exact n_ih, }
end
@[simp]
lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) :=
by { induction n; simp, }
@[simp]
lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) :=
by { induction n; simp, }
@[norm_cast]
lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) :=
by { ext; simp; ring }
@[norm_cast]
lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) :=
by { ext; simp, }
/-- The cardinality of `X` is `q^2`. -/
lemma X_card : fintype.card (X q) = q^2 :=
begin
dsimp [X],
rw [fintype.card_prod, zmod.card q],
ring,
end
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 :=
begin
haveI : fact (1 < (q : ℕ)) := w,
convert card_units_lt (X q),
rw X_card,
end
/-- We define `ω = 2 + √3`. -/
def ω : X q := (2, 1)
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ωb : X q := (2, -1)
lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
/-- A closed form for the recurrence relation. -/
lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) :=
begin
induction i with i ih,
{ dsimp [s, ω, ωb],
ext; { simp; refl, }, },
{ calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl
... = ((s i : X q)^2 - 2) : by push_cast
... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih
... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring
... = (ω^(2^i))^2 + (ωb^(2^i))^2 :
by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel]
... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] }
end
end X
open X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin
by_contradiction,
simp at a,
interval_cases q (p'+2); clear a,
{ -- If q = 1, we get a contradiction from 2^p = 2
dsimp [q] at h, injection h with h', clear h,
simp [mersenne] at h',
exact lt_irrefl 2
(calc 2 ≤ p'+2 : nat.le_add_left _ _
... < 2^(p'+2) : nat.lt_two_pow _
... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), },
{ -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1
dsimp [q] at h, injection h with h', clear h,
rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h',
exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', }
end
theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) =
k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 :=
begin
dsimp [lucas_lehmer_residue] at h,
rw s_zmod_eq_s p' at h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
cases h with k h,
use k,
replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q
dsimp at h,
rw closed_form at h,
replace h := congr_arg (λ x, ω^2^p' * x) h,
dsimp at h,
have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp,
rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h,
rw [mul_comm, coe_mul] at h,
rw [mul_comm _ (k : X (q (p'+2)))] at h,
replace h := eq_sub_of_add_eq h,
exact_mod_cast h,
end
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 :=
begin
ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos],
apply nat.min_fac_dvd,
end
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+1)) = -1 :=
begin
cases ω_pow_formula p' h with k w,
rw [mersenne_coe_X] at w,
simpa using w,
end
theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+2)) = 1 :=
calc (ω : X (q (p'+2)))^2^(p'+2)
= (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ']
... = (-1)^2 : by rw ω_pow_eq_neg_one p' h
... = 1 : by simp
/-- `ω` as an element of the group of units. -/
def ω_unit (p : ℕ) : units (X (q p)) :=
{ val := ω,
inv := ωb,
val_inv := by simp [ω_mul_ωb],
inv_val := by simp [ωb_mul_ω], }
@[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
order_of (ω_unit (p'+2)) = 2^(p'+2) :=
begin
apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p
{ norm_num, },
{ intro o,
have ω_pow := order_of_dvd_iff_pow_eq_one.1 o,
replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow,
simp at ω_pow,
have h : (1 : zmod (q (p'+2))) = -1 :=
congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)),
haveI : fact (2 < (q (p'+2) : ℕ)) := two_lt_q _,
apply zmod.neg_one_ne_one h.symm, },
{ apply order_of_dvd_iff_pow_eq_one.2,
apply units.ext,
push_cast,
exact ω_pow_eq_one p' h, }
end
lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 :=
calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm
... ≤ fintype.card (units (X _)) : order_of_le_card_univ
... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _))
end lucas_lehmer
export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue)
open lucas_lehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime :=
begin
let p' := p - 2,
have z : p = p' + 2 := (nat.sub_eq_iff_eq_add w).mp rfl,
have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl),
contrapose,
intros a t,
rw z at a,
rw z at t,
have h₁ := order_ineq p' t,
have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a,
have h := lt_of_lt_of_le h₁ h₂,
exact not_lt_of_ge (nat.sub_le _ _) h,
end
-- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better.
example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial
-- Next we use `norm_num` to calculate each `s p i`.
namespace lucas_lehmer
open tactic
meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩
meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩
lemma s_mod_succ {p a i b c}
(h1 : (2^p - 1 : ℤ) = a)
(h2 : s_mod p i = b)
(h3 : (b * b - 2) % a = c) :
s_mod p (i+1) = c :=
by { dsimp [s_mod, mersenne], rw [h1, h2, pow_two, h3] }
/--
Given a goal of the form `lucas_lehmer_test p`,
attempt to do the calculation using `norm_num` to certify each step.
-/
meta def run_test : tactic unit :=
do `(lucas_lehmer_test %%p) ← target,
`[dsimp [lucas_lehmer_test]],
`[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num],
p ← eval_expr ℕ p,
-- Calculate the candidate Mersenne prime
let M : ℤ := 2^p - 1,
t ← to_expr ``(2^%%p - 1 = %%M),
v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M),
w ← assertv `w t v,
-- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`.
-- We could make a better `has_to_pexpr ℤ` instance, or just:
`[simp only [int.coe_nat_zero, int.coe_nat_succ,
int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w],
-- base case
t ← to_expr ``(s_mod %%p 0 = 4),
v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4),
h ← assertv `h t v,
-- step case, repeated p-2 times
iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })],
-- now close the goal
h ← get_local `h,
exact h
end lucas_lehmer
/-- We verify that the tactic works to prove `127.prime`. -/
example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test).
/-!
This implementation works successfully to prove `(2^127 - 1).prime`,
and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean].
`(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!),
and unfortunately the next Mersenne prime `(2^521 - 1)`,
which was the first "computer era" prime,
is out of reach with the current implementation.
There's still low hanging fruit available to do faster computations
based on the formula
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] :=
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
begin
conv in k {rw [← nat.mod_add_div k (2^n), add_comm]},
refine nat.modeq.modeq_add _ (by refl),
conv {congr, skip, skip, rw ← one_mul (k/2^n)},
refine nat.modeq.modeq_mul _ (by refl),
symmetry,
rw [nat.modeq.modeq_iff_dvd, int.coe_nat_sub],
exact pow_pos (show 0 < 2, from dec_trivial) _
end
-- It's hard to know what the limiting factor for large Mersenne primes would be.
-- In the purely computational world, I think it's the squaring operation in `s`.
|
18d2eb4920bfee2eb4f8f84442b635c4b1fe2b44 | 7617a8700fc3eebd9200f1e620ee65b3565d2eff | /src/c0/common.lean | da87e64b62696406f936da50fa6fed42bada6e04 | [] | no_license | digama0/vc0 | 9747eee791c5c2f58eb53264ca6263ee53de0f87 | b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5 | refs/heads/master | 1,626,186,940,436 | 1,592,385,972,000 | 1,592,385,972,000 | 158,556,766 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 944 | lean |
namespace c0
def ident : Type := string
inductive comp | lt | le | gt | ge | eq | ne
inductive asize | a8 | a32 | a64
inductive err | arith | mem | abort
inductive type
| int | bool
| ref : type -> type
| arr : type → type
| struct : ident → type
structure fdef :=
(params : list type)
(ret : option type)
inductive binop
| add -- @x y : int |- x + y : int@
| sub -- @x y : int |- x - y : int@
| mul -- @x y : int |- x * y : int@
| div -- @x y : int |- x / y : int@
| mod -- @x y : int |- x % y : int@
| band -- @x y : int |- x & y : int@
| bxor -- @x y : int |- x ^ y : int@
| bor -- @x y : int |- x | y : int@
| shl -- @x y : int |- x << y : int@
| shr -- @x y : int |- x >> y : int@
| comp : comp → binop -- @x y : int |- x ?= y : bool@ (we coerce bool to int if necessary in the args)
inductive unop
| neg -- ^ @x : int |- -x : int@
| not -- ^ @x : bool |- !x : bool@
| bnot -- ^ @x : int |- ~x : int@
end c0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.