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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e6e23e66378f622fd672ebbc5865ad73562751d5 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Lean/Elab/SyntheticMVars.lean | 76d89af99ba7aa27f0f9838f3f7f35ea469c27f8 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,724 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Util.ForEachExpr
import Lean.Elab.Term
import Lean.Elab.Tactic.Basic
namespace Lean.Elab.Term
open Tactic (TacticM evalTactic getUnsolvedGoals)
open Meta
/-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/
private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr :=
-- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry`
withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do
elabTerm stx expectedType? false
/--
Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`.
It returns `true` if it succeeded, and `false` otherwise.
It is used to implement `synthesizeSyntheticMVars`. -/
private def resumePostponed (macroStack : MacroStack) (declName? : Option Name) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool :=
withRef stx <| withMVarContext mvarId do
let s ← get
try
withReader (fun ctx => { ctx with macroStack := macroStack, declName? := declName? }) do
let mvarDecl ← getMVarDecl mvarId
let expectedType ← instantiateMVars mvarDecl.type
withInfoHole mvarId do
let result ← resumeElabTerm stx expectedType (!postponeOnError)
/- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx.
That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/
let result ← withRef stx <| ensureHasType expectedType result
/- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/
if (← occursCheck mvarId result) then
assignExprMVar mvarId result
return true
else
return false
catch
| ex@(Exception.internal id _) =>
if id == postponeExceptionId then
set s
return false
else
throw ex
| ex@(Exception.error _ _) =>
if postponeOnError then
set s
return false
else
logException ex
return true
/--
Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances
are used. It also logs any error message produced. -/
private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool :=
withMVarContext instMVar do
try
synthesizeInstMVarCore instMVar
catch
| ex@(Exception.error _ _) => logException ex; return true
| _ => unreachable!
/--
Similar to `synthesizePendingInstMVar`, but generates type mismatch error message.
Remark: `eNew` is of the form `@coe ... mvar`, where `mvar` is the metavariable for the `CoeT ...` instance.
If `mvar` can be synthesized, then assign `auxMVarId := (expandCoe eNew)`.
-/
private def synthesizePendingCoeInstMVar
(auxMVarId : MVarId) (errorMsgHeader? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool :=
let instMVarId := eNew.appArg!.mvarId!
withMVarContext instMVarId do
try
if (← synthesizeCoeInstMVarCore instMVarId) then
let eNew ← expandCoe eNew
if (← occursCheck auxMVarId eNew) then
assignExprMVar auxMVarId eNew
return true
else
return false
else
return false
catch
| Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg
| _ => unreachable!
private def tryToSynthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : MetaM (Option (List SyntheticMVarDecl)) :=
commitWhenSome? do
let constInfo ← getConstInfo defaultInstance
let candidate := Lean.mkConst defaultInstance (← mkFreshLevelMVars constInfo.levelParams.length)
let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate)
let candidate := mkAppN candidate mvars
trace[Elab.resume]! "trying default instance for {mkMVar mvarId} := {candidate}"
if (← isDefEqGuarded (mkMVar mvarId) candidate) then
-- Succeeded. Collect new TC problems
let mut result := []
for i in [:bis.size] do
if bis[i] == BinderInfo.instImplicit then
result := { mvarId := mvars[i].mvarId!, stx := (← getRef), kind := SyntheticMVarKind.typeClass } :: result
trace[Elab.resume]! "worked"
return some result
else
return none
private def tryToSynthesizeUsingDefaultInstances (mvarId : MVarId) (prio : Nat) : MetaM (Option (List SyntheticMVarDecl)) :=
withMVarContext mvarId do
let mvarType := (← Meta.getMVarDecl mvarId).type
match (← isClass? mvarType) with
| none => return none
| some className =>
match (← getDefaultInstances className) with
| [] => return none
| defaultInstances =>
for (defaultInstance, instPrio) in defaultInstances do
if instPrio == prio then
match (← tryToSynthesizeUsingDefaultInstance mvarId defaultInstance) with
| some newMVarDecls => return some newMVarDecls
| none => continue
return none
/- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/
private def synthesizeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do
let rec visit (syntheticMVars : List SyntheticMVarDecl) (syntheticMVarsNew : List SyntheticMVarDecl) : TermElabM Bool := do
match syntheticMVars with
| [] => return false
| mvarDecl :: mvarDecls =>
match mvarDecl.kind with
| SyntheticMVarKind.typeClass =>
match (← withRef mvarDecl.stx <| tryToSynthesizeUsingDefaultInstances mvarDecl.mvarId prio) with
| none => visit mvarDecls (mvarDecl :: syntheticMVarsNew)
| some newMVarDecls =>
let syntheticMVarsNew := newMVarDecls ++ syntheticMVarsNew
let syntheticMVarsNew := mvarDecls.reverse ++ syntheticMVarsNew
modify fun s => { s with syntheticMVars := syntheticMVarsNew }
return true
| _ => visit mvarDecls (mvarDecl :: syntheticMVarsNew)
/- Recall that s.syntheticMVars is essentially a stack. The first metavariable was the last one created.
We want to apply the default instance in reverse creation order. Otherwise,
`toString 0` will produce a `OfNat String _` cannot be synthesized error. -/
visit (← get).syntheticMVars.reverse []
/--
Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault`
Return true if something was synthesized. -/
private def synthesizeUsingDefault : TermElabM Bool := do
let prioSet ← getDefaultInstancesPriorities
/- Recall that `prioSet` is stored in descending order -/
for prio in prioSet do
if (← synthesizeUsingDefaultPrio prio) then
return true
return false
/-- Report an error for each synthetic metavariable that could not be resolved. -/
private def reportStuckSyntheticMVars : TermElabM Unit := do
let s ← get
for mvarSyntheticDecl in s.syntheticMVars do
withRef mvarSyntheticDecl.stx do
match mvarSyntheticDecl.kind with
| SyntheticMVarKind.typeClass =>
withMVarContext mvarSyntheticDecl.mvarId do
let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId
unless (← get).messages.hasErrors do
logError <| "typeclass instance problem is stuck, it is often due to metavariables" ++ indentExpr mvarDecl.type
| SyntheticMVarKind.coe header eNew expectedType eType e f? =>
let mvarId := eNew.appArg!.mvarId!
withMVarContext mvarId do
let mvarDecl ← getMVarDecl mvarId
throwTypeMismatchError header expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type))
| _ => unreachable! -- TODO handle other cases.
private def getSomeSynthethicMVarsRef : TermElabM Syntax := do
let s ← get
match s.syntheticMVars.find? fun (mvarDecl : SyntheticMVarDecl) => !mvarDecl.stx.getPos?.isNone with
| some mvarDecl => return mvarDecl.stx
| none => return Syntax.missing
mutual
partial def liftTacticElabM {α} (mvarId : MVarId) (x : TacticM α) : TermElabM α :=
withMVarContext mvarId do
let s ← get
let savedSyntheticMVars := s.syntheticMVars
modify fun s => { s with syntheticMVars := [] }
try
let a ← x.run' { main := mvarId } { goals := [mvarId] }
synthesizeSyntheticMVars (mayPostpone := false)
pure a
finally
modify fun s => { s with syntheticMVars := savedSyntheticMVars }
partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do
/- Recall, `tacticCode` is the whole `by ...` expression.
We store the `by` because in the future we want to save the initial state information at the `by` position. -/
let code := tacticCode[1]
modifyThe Meta.State fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId }
let remainingGoals ← withInfoHole mvarId do liftTacticElabM mvarId do evalTactic code; getUnsolvedGoals
unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals
/-- Try to synthesize the given pending synthetic metavariable. -/
private partial def synthesizeSyntheticMVar (mvarSyntheticDecl : SyntheticMVarDecl) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool :=
withRef mvarSyntheticDecl.stx do
match mvarSyntheticDecl.kind with
| SyntheticMVarKind.typeClass => synthesizePendingInstMVar mvarSyntheticDecl.mvarId
| SyntheticMVarKind.coe header? eNew expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.mvarId header? eNew expectedType eType e f?
-- NOTE: actual processing at `synthesizeSyntheticMVarsAux`
| SyntheticMVarKind.postponed macroStack declName? => resumePostponed macroStack declName? mvarSyntheticDecl.stx mvarSyntheticDecl.mvarId postponeOnError
| SyntheticMVarKind.tactic declName? tacticCode =>
withReader (fun ctx => { ctx with declName? := declName? }) do
if runTactics then
runTactic mvarSyntheticDecl.mvarId tacticCode
return true
else
return false
/--
Try to synthesize the current list of pending synthetic metavariables.
Return `true` if at least one of them was synthesized. -/
private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do
let ctx ← read
traceAtCmdPos `Elab.resuming fun _ =>
m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}"
let s ← get
let syntheticMVars := s.syntheticMVars
let numSyntheticMVars := syntheticMVars.length
-- We reset `syntheticMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`.
modify fun s => { s with syntheticMVars := [] }
-- Recall that `syntheticMVars` is a list where head is the most recent pending synthetic metavariable.
-- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created.
-- It would not be incorrect to use `filterM`.
let remainingSyntheticMVars ← syntheticMVars.filterRevM fun mvarDecl => do
-- We use `traceM` because we want to make sure the metavar local context is used to trace the message
traceM `Elab.postpone (withMVarContext mvarDecl.mvarId do addMessageContext m!"resuming {mkMVar mvarDecl.mvarId}")
let succeeded ← synthesizeSyntheticMVar mvarDecl postponeOnError runTactics
trace[Elab.postpone]! if succeeded then fmt "succeeded" else fmt "not ready yet"
pure !succeeded
-- Merge new synthetic metavariables with `remainingSyntheticMVars`, i.e., metavariables that still couldn't be synthesized
modify fun s => { s with syntheticMVars := s.syntheticMVars ++ remainingSyntheticMVars }
return numSyntheticMVars != remainingSyntheticMVars.length
/--
Try to process pending synthetic metavariables. If `mayPostpone == false`,
then `syntheticMVars` is `[]` after executing this method.
It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made.
If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available)
metavariables that are still unresolved, and then tries to resolve metavariables
with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to
a "best option". If, after that, we still haven't made progress, we report "stuck" errors. -/
partial def synthesizeSyntheticMVars (mayPostpone := true) : TermElabM Unit :=
let rec loop (u : Unit) : TermElabM Unit := do
let ref ← getSomeSynthethicMVarsRef
withRef ref <| withIncRecDepth do
let s ← get
unless s.syntheticMVars.isEmpty do
if ← synthesizeSyntheticMVarsStep false false then
loop ()
else if !mayPostpone then
/- Resume pending metavariables with "elaboration postponement" disabled.
We postpone elaboration errors in this step by setting `postponeOnError := true`.
Example:
```
#check let x := ⟨1, 2⟩; Prod.fst x
```
The term `⟨1, 2⟩` can't be elaborated because the expected type is not know.
The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known.
When we execute the following step with "elaboration postponement" disabled,
the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns
that its type must be of the form `Prod ?α ?β`.
Recall that we postponed `x` at `Prod.fst x` because its type it is not known.
We the type of `x` may learn later its type and it may contain implicit and/or auto arguments.
By disabling postponement, we are essentially giving up the opportunity of learning `x`s type
and assume it does not have implict and/or auto arguments. -/
if ← withoutPostponing (synthesizeSyntheticMVarsStep true false) then
loop ()
else if ← synthesizeUsingDefault then
loop ()
else if ← withoutPostponing (synthesizeSyntheticMVarsStep false false) then
loop ()
else if ← synthesizeSyntheticMVarsStep false true then
loop ()
else
reportStuckSyntheticMVars
loop ()
end
def synthesizeSyntheticMVarsNoPostponing : TermElabM Unit :=
synthesizeSyntheticMVars (mayPostpone := false)
/- Keep invoking `synthesizeUsingDefault` until it returns false. -/
private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do
if (← synthesizeUsingDefault) then
synthesizeSyntheticMVars (mayPostpone := true)
synthesizeUsingDefaultLoop
def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do
synthesizeSyntheticMVars (mayPostpone := true)
synthesizeUsingDefaultLoop
private partial def withSynthesizeImp {α} (k : TermElabM α) (mayPostpone : Bool) : TermElabM α := do
let s ← get
let syntheticMVarsSaved := s.syntheticMVars
modify fun s => { s with syntheticMVars := [] }
try
let a ← k
synthesizeSyntheticMVars mayPostpone
if mayPostpone then
synthesizeUsingDefaultLoop
return a
finally
modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved }
/--
Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved.
If `mayPostpone == false`, then all of them must be synthesized.
Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/
@[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m α) (mayPostpone := false) : m α :=
monadMap (m := TermElabM) (withSynthesizeImp . mayPostpone) k
/-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/
def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=
withRef stx do
let v ← withSynthesize <| elabTerm stx expectedType?
instantiateMVars v
end Lean.Elab.Term
|
c5ed25fc38d7c2f951b8e64905826da5ad1205a1 | c8b4b578b2fe61d500fbca7480e506f6603ea698 | /src/caseI/statement.lean | 0b3f65506f6016584f10cbdf7795e93ceea09b6d | [] | 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 | 12,911 | lean | import caseI.aux_lemmas
open finset nat is_cyclotomic_extension ideal polynomial int basis flt_regular.caseI
open_locale big_operators number_field
namespace flt_regular
variables {p : ℕ} [hpri : fact p.prime]
local notation `P` := (⟨p, hpri.out.pos⟩ : ℕ+)
local notation `K` := cyclotomic_field P ℚ
local notation `R` := 𝓞 K
namespace caseI
/-- Statement of case I with additional assumptions. -/
def slightly_easier : Prop := ∀ ⦃a b c : ℤ⦄ {p : ℕ} [hpri : fact p.prime]
(hreg : @is_regular_prime p hpri) (hp5 : 5 ≤ p)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1)
(hab : ¬a ≡ b [ZMOD p]) (caseI : ¬ ↑p ∣ a * b * c), a ^ p + b ^ p ≠ c ^ p
/-- Statement of case I. -/
def statement : Prop := ∀ ⦃a b c : ℤ⦄ {p : ℕ} [hpri : fact p.prime]
(hreg : @is_regular_prime p hpri) (caseI : ¬ ↑p ∣ a * b * c),
a ^ p + b ^ p ≠ c ^ p
lemma may_assume : slightly_easier → statement :=
begin
intro Heasy,
intros a b c p hpri hreg hI H,
have hodd : p ≠ 2,
{ intro h,
rw [h] at H hI,
refine hI _,
refine has_dvd.dvd.mul_left _ _,
simp only [coe_nat_bit0, algebra_map.coe_one, ← even_iff_two_dvd] at ⊢ hI,
rw [← int.odd_iff_not_even] at hI,
rw [← int.even_pow' (show 2 ≠ 0, by norm_num), ← H],
exact (odd.of_mul_left (odd.of_mul_left hI)).pow.add_odd
(odd.of_mul_right (odd.of_mul_left hI)).pow },
have hprod : a * b * c ≠ 0,
{ intro h,
simpa [h] using hI },
have hp5 : 5 ≤ p,
{ by_contra' habs,
have : p ∈ finset.Ioo 2 5 := finset.mem_Icc.2 ⟨nat.lt_of_le_and_ne hpri.out.two_le hodd.symm,
by linarith⟩,
fin_cases this,
{ exact may_assume.p_ne_three hprod H rfl },
{ rw [show 4 = 2 * 2, from rfl] at hpri,
refine nat.not_prime_mul one_lt_two one_lt_two hpri.out } },
rcases may_assume.coprime H hprod with ⟨Hxyz, hunit, hprodxyx⟩,
let d := ({a, b, c} : finset ℤ).gcd id,
have hdiv : ¬↑p ∣ (a / d) * (b / d) * (c / d),
{ have hadiv : d ∣ a := gcd_dvd (by simp),
have hbdiv : d ∣ b := gcd_dvd (by simp),
have hcdiv : d ∣ c := gcd_dvd (by simp),
intro hdiv,
replace hdiv := dvd_mul_of_dvd_right hdiv ((d * d) * d),
rw [mul_assoc, ← mul_assoc d, ← mul_assoc d, int.mul_div_cancel' hadiv, mul_assoc,
mul_comm a, mul_assoc (b / d), ← mul_assoc _ (b / d), int.mul_div_cancel' hbdiv,
mul_comm, mul_assoc, mul_assoc, int.div_mul_cancel hcdiv, mul_comm, mul_assoc,
mul_comm c, ← mul_assoc] at hdiv,
exact hI hdiv },
obtain ⟨X, Y, Z, H1, H2, H3, H4, H5⟩ := a_not_cong_b hpri.out hp5 hprodxyx Hxyz hunit hdiv,
exactI Heasy hreg hp5 H2 H3 (λ hfin, H5 hfin) H1
end
end caseI
lemma ab_coprime {a b c : ℤ} (H : a ^ p + b ^ p = c ^ p) (hpzero : p ≠ 0)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1) : is_coprime a b :=
begin
rw [← gcd_eq_one_iff_coprime],
by_contra' h,
obtain ⟨q, hqpri, hq⟩ := exists_prime_and_dvd h,
replace hqpri : prime (q : ℤ) := prime_iff_nat_abs_prime.2 (by simp [hqpri]),
obtain ⟨n, hn⟩ := hq,
have haq : ↑q ∣ a,
{ obtain ⟨m, hm⟩ := int.gcd_dvd_left a b,
exact ⟨n * m, by { rw [hm, hn], simp [mul_assoc] }⟩ },
have hbq : ↑q ∣ b,
{ obtain ⟨m, hm⟩ := int.gcd_dvd_right a b,
exact ⟨n * m, by { rw [hm, hn], simp [mul_assoc] }⟩ },
have hcq : ↑q ∣ c,
{ suffices : ↑q ∣ c ^ p,
{ exact hqpri.dvd_of_dvd_pow this },
rw [← H],
exact dvd_add (dvd_pow haq hpzero) (dvd_pow hbq hpzero) },
have Hq : ↑q ∣ ({a, b, c} : finset ℤ).gcd id,
{ refine dvd_gcd (λ x hx, _),
simp only [mem_insert, mem_singleton] at hx,
rcases hx with H | H | H;
simpa [H] },
rw [hgcd] at Hq,
exact hqpri.not_unit (is_unit_of_dvd_one _ Hq)
end
theorem exists_ideal {a b c : ℤ} (h5p : 5 ≤ p) (H : a ^ p + b ^ p = c ^ p)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1) (caseI : ¬ ↑p ∣ a * b * c)
{ζ : R} (hζ : ζ ∈ nth_roots_finset p R) : ∃ I, span ({a + ζ * b} : set R) = I ^ p :=
begin
haveI : fact ((P : ℕ).prime) := ⟨hpri.out⟩,
classical,
have H₁ := congr_arg (algebra_map ℤ R) H,
simp only [eq_int_cast, int.cast_add, int.cast_pow] at H₁,
have hζ' := (zeta_spec P ℚ K).unit'_coe,
rw [pow_add_pow_eq_prod_add_zeta_runity_mul
(hpri.out.eq_two_or_odd.resolve_left $ λ h, by norm_num [h] at h5p) hζ'] at H₁,
replace H₁ := congr_arg (λ x, span ({x} : set R)) H₁,
simp only [← prod_span_singleton, ← span_singleton_pow] at H₁,
have hdom : is_domain (ideal (𝓞 (cyclotomic_field ⟨p, hpri.out.pos⟩ ℚ))) := ideal.is_domain,
let gcddom : gcd_monoid (ideal (𝓞 (cyclotomic_field ⟨p, hpri.out.pos⟩ ℚ))) :=
(ideal.normalized_gcd_monoid).to_gcd_monoid,
obtain ⟨I, hI⟩ := @finset.exists_eq_pow_of_mul_eq_pow_of_coprime _ _ _ hdom gcddom _ _ _ _ _
(λ η₁ hη₁ η₂ hη₂ hη, _) H₁ ζ hζ,
{ exact ⟨I, hI⟩ },
{ exact flt_ideals_coprime h5p H (ab_coprime H hpri.out.ne_zero hgcd) hη₁ hη₂ hη caseI }
end
theorem is_principal {a b c : ℤ} {ζ : R} (hreg : is_regular_prime p) (hp5 : 5 ≤ p)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1) (caseI : ¬ ↑p ∣ a * b * c)
(H : a ^ p + b ^ p = c ^ p) (hζ : is_primitive_root ζ p) :
∃ (u : Rˣ) (α : R), ↑u * (α ^ p) = ↑a + ζ * ↑b :=
begin
replace hζ := hζ.mem_nth_roots_finset hpri.out.pos,
obtain ⟨I, hI⟩ := exists_ideal hp5 H hgcd caseI hζ,
by_cases hIpzero : I ^ p = 0,
{ refine ⟨1, 0, _⟩,
simp [hIpzero, zero_eq_bot, span_singleton_eq_bot] at hI,
simp [hpri.out.pos, hI] },
have hIzero : I ≠ 0,
{ intro hIzero,
simp only [hIzero, zero_pow hpri.out.pos] at hIpzero,
exact hIpzero rfl },
have hIprin : I.is_principal,
{ have : class_group.mk0 ⟨_, mem_non_zero_divisors_of_ne_zero hIpzero⟩ = 1,
{ rw [class_group.mk0_eq_one_iff (mem_non_zero_divisors_of_ne_zero hIpzero)],
exact ⟨⟨↑a + ζ * ↑b, hI.symm⟩⟩ },
rw [← submonoid_class.mk_pow I (mem_non_zero_divisors_of_ne_zero hIzero), map_pow] at this,
cases (dvd_prime hpri.out).1 (order_of_dvd_of_pow_eq_one this) with h1 habs,
{ exact (class_group.mk0_eq_one_iff _).1 (order_of_eq_one_iff.1 h1) },
{ exfalso,
refine hpri.out.coprime_iff_not_dvd.1 hreg _,
simp_rw [← habs],
exact order_of_dvd_card_univ, } },
obtain ⟨α, hα⟩ := hIprin,
replace hα := congr_arg (λ J, J ^ p) hα,
simp only [←hI, submodule_span_eq, span_singleton_pow, span_singleton_eq_span_singleton] at hα,
obtain ⟨u, hu⟩ := hα,
refine ⟨u⁻¹, α, _⟩,
rw [← hu, mul_comm _ ↑u, ← mul_assoc],
simp only [units.inv_mul, one_mul]
end
theorem ex_fin_div {a b c : ℤ} {ζ : R} (hp5 : 5 ≤ p)
(hreg : is_regular_prime p) (hζ : is_primitive_root ζ p)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1) (caseI : ¬ ↑p ∣ a * b * c)
(H : a ^ p + b ^ p = c ^ p) :
∃ (k₁ k₂ : fin p), k₂ ≡ k₁ - 1 [ZMOD p] ∧ ↑p ∣ ↑a + ↑b * ζ - ↑a * ζ ^ (k₁ : ℕ) - ↑b * ζ ^ (k₂ : ℕ) :=
begin
let ζ' := (ζ : K),
have hζ' : is_primitive_root ζ' P := is_primitive_root.coe_submonoid_class_iff.2 hζ,
have : ζ = (hζ'.unit' : R) := by simp only [is_primitive_root.unit', set_like.eta, units.coe_mk],
have hP : P ≠ 2,
{ intro hP,
rw [← pnat.coe_inj, pnat.mk_coe, pnat.coe_bit0, pnat.one_coe] at hP,
norm_num [hP] at hp5 },
haveI := (⟨hpri.out⟩ : fact ((P : ℕ).prime)),
obtain ⟨u, α, hu⟩ := is_principal hreg hp5 hgcd caseI H hζ,
rw [this, mul_comm _ ↑b, ← pow_one hζ'.unit'] at hu,
obtain ⟨k, hk⟩ := flt_regular.caseI.exists_int_sum_eq_zero hζ' hP a b 1 hu.symm,
simp only [zpow_one, zpow_neg, coe_coe, pnat.mk_coe, mem_span_singleton, ← this] at hk,
have hpcoe : (p : ℤ) ≠ 0 := by simp [hpri.out.ne_zero],
refine ⟨⟨(2 * k % p).nat_abs, _⟩, ⟨((2 * k - 1) % p).nat_abs, _⟩, _, _⟩,
repeat { rw [← nat_abs_of_nat p],
refine nat_abs_lt_nat_abs_of_nonneg_of_lt (mod_nonneg _ hpcoe) _,
rw [nat_abs_of_nat],
exact mod_lt_of_pos _ (by simp [hpri.out.pos]) },
{ simp [nat_abs_of_nonneg (mod_nonneg _ hpcoe), ← zmod.int_coe_eq_int_coe_iff] },
simp only [add_sub_assoc, sub_sub] at hk ⊢,
convert hk using 3,
rw [mul_add, mul_comm ↑a, ← mul_assoc _ ↑b, mul_comm _ ↑b, mul_assoc ↑b],
congr' 2,
{ rw [← subtype.coe_inj],
simp only [fin.coe_mk, subsemiring_class.coe_pow, _root_.coe_zpow', coe_coe,
is_primitive_root.coe_unit'_coe],
refine eq_of_div_eq_one _,
rw [← zpow_coe_nat, ← zpow_sub₀ (hζ'.ne_zero hpri.out.ne_zero), hζ'.zpow_eq_one_iff_dvd],
simp [nat_abs_of_nonneg (mod_nonneg _ hpcoe), ← zmod.int_coe_zmod_eq_zero_iff_dvd] },
{ rw [← subtype.coe_inj],
simp only [fin.coe_mk, subsemiring_class.coe_pow, mul_mem_class.coe_mul, _root_.coe_zpow',
coe_coe, is_primitive_root.coe_unit'_coe, is_primitive_root.coe_inv_unit'_coe],
refine eq_of_div_eq_one _,
rw [← zpow_coe_nat, ← zpow_sub_one₀ (hζ'.ne_zero hpri.out.ne_zero),
← zpow_sub₀ (hζ'.ne_zero hpri.out.ne_zero), hζ'.zpow_eq_one_iff_dvd, pnat.mk_coe],
simp [nat_abs_of_nonneg (mod_nonneg _ hpcoe), ← zmod.int_coe_zmod_eq_zero_iff_dvd] },
end
/-- Auxiliary function -/
def f (a b : ℤ) (k₁ k₂ : ℕ) : ℕ → ℤ := λ x, if x = 0 then a else if x = 1 then b else
if x = k₁ then -a else if x = k₂ then -b else 0
lemma auxf' (hp5 : 5 ≤ p) (a b : ℤ) (k₁ k₂ : fin p) : ∃ i ∈ range p, f a b k₁ k₂ (i : ℕ) = 0 :=
begin
have h0 : 0 < p := by linarith,
have h1 : 1 < p := by linarith,
let s := ({0, 1, k₁, k₂} : finset ℕ),
have : s.card ≤ 4,
{ repeat { refine le_trans (card_insert_le _ _) (succ_le_succ _) },
exact rfl.ge },
replace this : s.card < 5 := lt_of_le_of_lt this (by norm_num),
have hs : s ⊆ range p := insert_subset.2 ⟨mem_range.2 h0, insert_subset.2 ⟨mem_range.2 h1,
insert_subset.2 ⟨mem_range.2 (fin.is_lt _), singleton_subset_iff.2 (mem_range.2 (fin.is_lt _))⟩⟩⟩,
have hcard := card_sdiff hs,
replace hcard : (range p \ s).nonempty,
{ rw [← card_pos, hcard, card_range],
exact nat.sub_pos_of_lt (lt_of_lt_of_le this hp5) },
obtain ⟨i, hi⟩ := hcard,
refine ⟨i, sdiff_subset _ _ hi, _⟩,
have hi0 : i ≠ 0 := λ h, by simpa [h] using hi,
have hi1 : i ≠ 1 := λ h, by simpa [h] using hi,
have hik₁ : i ≠ k₁ := λ h, by simpa [h] using hi,
have hik₂ : i ≠ k₂ := λ h, by simpa [h] using hi,
simp [f, hi0, hi1, hik₁, hik₂]
end
lemma auxf (hp5 : 5 ≤ p) (a b : ℤ) (k₁ k₂ : fin p) : ∃ i : fin p, f a b k₁ k₂ (i : ℕ) = 0 :=
begin
obtain ⟨i, hrange, hi⟩ := auxf' hp5 a b k₁ k₂,
exact ⟨⟨i, mem_range.1 hrange⟩, hi⟩
end
/-- Case I with additional assumptions. -/
theorem caseI_easier {a b c : ℤ} (p : ℕ) [hpri : fact p.prime]
(hreg : is_regular_prime p) (hp5 : 5 ≤ p)
(hgcd : ({a, b, c} : finset ℤ).gcd id = 1)
(hab : ¬a ≡ b [ZMOD p]) (caseI : ¬ ↑p ∣ a * b * c) : a ^ p + b ^ p ≠ c ^ p :=
begin
haveI := (⟨hpri.out⟩ : fact ((P : ℕ).prime)),
set ζ := zeta P ℤ R with hζdef,
have hζ := zeta_spec P ℤ R,
intro H,
obtain ⟨k₁, k₂, hcong, hdiv⟩ := ex_fin_div hp5 hreg hζ hgcd caseI H,
have key : ↑(p : ℤ) ∣ ∑ j in range p, (f a b k₁ k₂ j) • ζ ^ j,
{ convert hdiv using 1,
have h01 : 0 ≠ 1 := zero_ne_one,
have h0k₁ : 0 ≠ ↑k₁ := aux0k₁ hpri.out hp5 hζ caseI hcong hdiv,
have h0k₂ : 0 ≠ ↑k₂ := aux0k₂ hpri.out hp5 hζ hab hcong hdiv,
have h1k₁ : 1 ≠ ↑k₁ := aux1k₁ hpri.out hp5 hζ hab hcong hdiv,
have h1k₂ : 1 ≠ ↑k₂ := aux1k₂ hpri.out hp5 hζ caseI hcong hdiv,
have hk₁k₂ : (k₁ : ℕ) ≠ (k₂ : ℕ) := auxk₁k₂ hpri.out hcong,
simp_rw [f, ite_smul, sum_ite, filter_filter, ← ne.def, ne_and_eq_iff_right h01,
and_assoc, ne_and_eq_iff_right h1k₁, ne_and_eq_iff_right h0k₁, ne_and_eq_iff_right hk₁k₂,
ne_and_eq_iff_right h1k₂, ne_and_eq_iff_right h0k₂, finset.range_filter_eq],
simp only [hpri.out.pos, hpri.out.one_lt, if_true, zsmul_eq_mul, sum_singleton, pow_zero,
mul_one, pow_one, fin.is_lt, neg_smul, sum_neg_distrib, ne.def, filter_congr_decidable, zero_smul, sum_const_zero, add_zero],
ring },
rw [sum_range] at key,
refine caseI (has_dvd.dvd.mul_right (has_dvd.dvd.mul_right _ _) _),
simpa [f] using dvd_coeff_cycl_integer hζ (by exact auxf hp5 a b k₁ k₂) key ⟨0, hpri.out.pos⟩
end
/-- CaseI. -/
theorem caseI {a b c : ℤ} {p : ℕ} [fact p.prime] (hreg : is_regular_prime p)
(caseI : ¬ ↑p ∣ a * b * c) : a ^ p + b ^ p ≠ c ^ p :=
flt_regular.caseI.may_assume (λ x y z p₁ Hpri Hreg Hp5 Hunit Hxy HI H,
by exactI caseI_easier p₁ Hreg Hp5 Hunit Hxy HI H) hreg caseI
end flt_regular
|
bc0820e75fb0f96bcb5484d1783087af12e70538 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/calculus/inverse.lean | 5006b15c09371ebc12e58aa2e25481f69b32c03c | [
"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 | 37,409 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth, Sébastien Gouëzel
-/
import analysis.calculus.cont_diff
import tactic.ring_exp
import analysis.normed_space.banach
import topology.local_homeomorph
/-!
# Inverse function theorem
In this file we prove the inverse function theorem. It says that if a map `f : E → F`
has an invertible strict derivative `f'` at `a`, then it is locally invertible,
and the inverse function has derivative `f' ⁻¹`.
We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f`
with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`.
The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems
about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`.
Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`,
and prove two versions of the inverse function theorem:
* `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the
strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the
strict sense;
* `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in
the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative
`f'.symm` at `f a` in the strict sense.
In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and
`f'⁻¹`.
We also reformulate the theorems in terms of `cont_diff`, to give that `C^k` (respectively,
smooth) inputs give `C^k` (smooth) inverses. These versions require that continuous
differentiability implies strict differentiability; this is false over a general field, true over
`ℝ` or `ℂ` and implemented here assuming `is_R_or_C 𝕂`.
Some related theorems, providing the derivative and higher regularity assuming that we already know
the inverse function, are formulated in `fderiv.lean`, `deriv.lean`, and `cont_diff.lean`.
## Notations
In the section about `approximates_linear_on` we introduce some `local notation` to make formulas
shorter:
* by `N` we denote `∥f'⁻¹∥`;
* by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that
`{x | f x = y}` is nonempty.
## Tags
derivative, strictly differentiable, continuously differentiable, smooth, inverse function
-/
open function set filter metric
open_locale topological_space classical nnreal
noncomputable theory
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G]
variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G']
variables {ε : ℝ}
open asymptotics filter metric set
open continuous_linear_map (id)
/-!
### Non-linear maps close to affine maps
In this section we study a map `f` such that `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` on an open set
`s`, where `f' : E →L[𝕜] F` is a continuous linear map and `c` is suitably small. Maps of this type
behave like `f a + f' (x - a)` near each `a ∈ s`.
When `f'` is onto, we show that `f` is locally onto.
When `f'` is a continuous linear equiv, we show that `f` is a homeomorphism
between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to
be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`.
Maps of this type naturally appear in the proof of the inverse function theorem (see next section),
and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function
exists.
We define this auxiliary notion to split the proof of the inverse function theorem into small
lemmas. This approach makes it possible
- to prove a lower estimate on the size of the domain of the inverse function;
- to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a
function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`.
-/
/-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`,
if `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` whenever `x, y ∈ s`.
This predicate is defined to facilitate the splitting of the inverse function theorem into small
lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined
on a specific set. -/
def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop :=
∀ (x ∈ s) (y ∈ s), ∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥
@[simp] lemma approximates_linear_on_empty (f : E → F) (f' : E →L[𝕜] F) (c : ℝ≥0) :
approximates_linear_on f f' ∅ c :=
by simp [approximates_linear_on]
namespace approximates_linear_on
variables [cs : complete_space E] {f : E → F}
/-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily
invertible) continuous linear map. -/
section
variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0}
theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) :
approximates_linear_on f f' s c' :=
λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _)
theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) :
approximates_linear_on f f' s c :=
λ x hx y hy, hf x (hst hx) y (hst hy)
lemma approximates_linear_on_iff_lipschitz_on_with
{f : E → F} {f' : E →L[𝕜] F} {s : set E} {c : ℝ≥0} :
approximates_linear_on f f' s c ↔ lipschitz_on_with c (f - f') s :=
begin
have : ∀ x y, f x - f y - f' (x - y) = (f - f') x - (f - f') y,
{ assume x y, simp only [map_sub, pi.sub_apply], abel },
simp only [this, lipschitz_on_with_iff_norm_sub_le, approximates_linear_on],
end
alias approximates_linear_on_iff_lipschitz_on_with ↔
lipschitz_on_with _root_.lipschitz_on_with.approximates_linear_on
lemma lipschitz_sub (hf : approximates_linear_on f f' s c) :
lipschitz_with c (λ x : s, f x - f' x) :=
begin
refine lipschitz_with.of_dist_le_mul (λ x y, _),
rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm],
convert hf x x.2 y y.2 using 2,
rw [f'.map_sub], abel
end
protected lemma lipschitz (hf : approximates_linear_on f f' s c) :
lipschitz_with (∥f'∥₊ + c) (s.restrict f) :=
by simpa only [restrict_apply, add_sub_cancel'_right]
using (f'.lipschitz.restrict s).add hf.lipschitz_sub
protected lemma continuous (hf : approximates_linear_on f f' s c) :
continuous (s.restrict f) :=
hf.lipschitz.continuous
protected lemma continuous_on (hf : approximates_linear_on f f' s c) :
continuous_on f s :=
continuous_on_iff_continuous_restrict.2 hf.continuous
end
section locally_onto
/-!
We prove that a function which is linearly approximated by a continuous linear map with a nonlinear
right inverse is locally onto. This will apply to the case where the approximating map is a linear
equivalence, for the local inverse theorem, but also whenever the approximating map is onto,
by Banach's open mapping theorem. -/
include cs
variables {s : set E} {c : ℝ≥0} {f' : E →L[𝕜] F}
/-- If a function is linearly approximated by a continuous linear map with a (possibly nonlinear)
right inverse, then it is locally onto: a ball of an explicit radius is included in the image
of the map. -/
theorem surj_on_closed_ball_of_nonlinear_right_inverse
(hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse)
{ε : ℝ} {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) :
surj_on f (closed_ball b ε) (closed_ball (f b) (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε)) :=
begin
assume y hy,
cases le_or_lt (f'symm.nnnorm : ℝ) ⁻¹ c with hc hc,
{ refine ⟨b, by simp [ε0], _⟩,
have : dist y (f b) ≤ 0 :=
(mem_closed_ball.1 hy).trans (mul_nonpos_of_nonpos_of_nonneg (by linarith) ε0),
simp only [dist_le_zero] at this,
rw this },
have If' : (0 : ℝ) < f'symm.nnnorm,
by { rw [← inv_pos], exact (nnreal.coe_nonneg _).trans_lt hc },
have Icf' : (c : ℝ) * f'symm.nnnorm < 1, by rwa [inv_eq_one_div, lt_div_iff If'] at hc,
have Jf' : (f'symm.nnnorm : ℝ) ≠ 0 := ne_of_gt If',
have Jcf' : (1 : ℝ) - c * f'symm.nnnorm ≠ 0, by { apply ne_of_gt, linarith },
/- We have to show that `y` can be written as `f x` for some `x ∈ closed_ball b ε`.
The idea of the proof is to apply the Banach contraction principle to the map
`g : x ↦ x + f'symm (y - f x)`, as a fixed point of this map satisfies `f x = y`.
When `f'symm` is a genuine linear inverse, `g` is a contracting map. In our case, since `f'symm`
is nonlinear, this map is not contracting (it is not even continuous), but still the proof of
the contraction theorem holds: `uₙ = gⁿ b` is a Cauchy sequence, converging exponentially fast
to the desired point `x`. Instead of appealing to general results, we check this by hand.
The main point is that `f (u n)` becomes exponentially close to `y`, and therefore
`dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive
bound on `dist (u n) b`, from which one checks that `u n` stays in the ball on which one has a
control. Therefore, the bound can be checked at the next step, and so on inductively.
-/
set g := λ x, x + f'symm (y - f x) with hg,
set u := λ (n : ℕ), g ^[n] b with hu,
have usucc : ∀ n, u (n + 1) = g (u n), by simp [hu, ← iterate_succ_apply' g _ b],
-- First bound: if `f z` is close to `y`, then `g z` is close to `z` (i.e., almost a fixed point).
have A : ∀ z, dist (g z) z ≤ f'symm.nnnorm * dist (f z) y,
{ assume z,
rw [dist_eq_norm, hg, add_sub_cancel', dist_eq_norm'],
exact f'symm.bound _ },
-- Second bound: if `z` and `g z` are in the set with good control, then `f (g z)` becomes closer
-- to `y` than `f z` was (this uses the linear approximation property, and is the reason for the
-- choice of the formula for `g`).
have B : ∀ z ∈ closed_ball b ε, g z ∈ closed_ball b ε →
dist (f (g z)) y ≤ c * f'symm.nnnorm * dist (f z) y,
{ assume z hz hgz,
set v := f'symm (y - f z) with hv,
calc dist (f (g z)) y = ∥f (z + v) - y∥ : by rw [dist_eq_norm]
... = ∥f (z + v) - f z - f' v + f' v - (y - f z)∥ : by { congr' 1, abel }
... = ∥f (z + v) - f z - f' ((z + v) - z)∥ :
by simp only [continuous_linear_map.nonlinear_right_inverse.right_inv,
add_sub_cancel', sub_add_cancel]
... ≤ c * ∥(z + v) - z∥ : hf _ (hε hgz) _ (hε hz)
... ≤ c * (f'symm.nnnorm * dist (f z) y) : begin
apply mul_le_mul_of_nonneg_left _ (nnreal.coe_nonneg c),
simpa [hv, dist_eq_norm'] using f'symm.bound (y - f z),
end
... = c * f'symm.nnnorm * dist (f z) y : by ring },
-- Third bound: a complicated bound on `dist w b` (that will show up in the induction) is enough
-- to check that `w` is in the ball on which one has controls. Will be used to check that `u n`
-- belongs to this ball for all `n`.
have C : ∀ (n : ℕ) (w : E),
dist w b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y
→ w ∈ closed_ball b ε,
{ assume n w hw,
apply hw.trans,
rw [div_mul_eq_mul_div, div_le_iff], swap, { linarith },
calc (f'symm.nnnorm : ℝ) * (1 - (c * f'symm.nnnorm) ^ n) * dist (f b) y
= f'symm.nnnorm * dist (f b) y * (1 - (c * f'symm.nnnorm) ^ n) : by ring
... ≤ f'symm.nnnorm * dist (f b) y * 1 :
begin
apply mul_le_mul_of_nonneg_left _ (mul_nonneg (nnreal.coe_nonneg _) dist_nonneg),
rw [sub_le_self_iff],
exact pow_nonneg (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) _,
end
... ≤ f'symm.nnnorm * (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε) :
by { rw [mul_one],
exact mul_le_mul_of_nonneg_left (mem_closed_ball'.1 hy) (nnreal.coe_nonneg _) }
... = ε * (1 - c * f'symm.nnnorm) : by { field_simp, ring } },
/- Main inductive control: `f (u n)` becomes exponentially close to `y`, and therefore
`dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive
bound on `dist (u n) b`, from which one checks that `u n` remains in the ball on which we
have estimates. -/
have D : ∀ (n : ℕ), dist (f (u n)) y ≤ (c * f'symm.nnnorm)^n * dist (f b) y
∧ dist (u n) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm)
* dist (f b) y,
{ assume n,
induction n with n IH, { simp [hu, le_refl] },
rw usucc,
have Ign : dist (g (u n)) b ≤
f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y :=
calc
dist (g (u n)) b ≤ dist (g (u n)) (u n) + dist (u n) b : dist_triangle _ _ _
... ≤ f'symm.nnnorm * dist (f (u n)) y + dist (u n) b : add_le_add (A _) le_rfl
... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) +
f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y :
add_le_add (mul_le_mul_of_nonneg_left IH.1 (nnreal.coe_nonneg _)) IH.2
... = f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm)
* dist (f b) y : by { field_simp [Jcf'], ring_exp },
refine ⟨_, Ign⟩,
calc dist (f (g (u n))) y ≤ c * f'symm.nnnorm * dist (f (u n)) y :
B _ (C n _ IH.2) (C n.succ _ Ign)
... ≤ (c * f'symm.nnnorm) * ((c * f'symm.nnnorm)^n * dist (f b) y) :
mul_le_mul_of_nonneg_left IH.1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _))
... = (c * f'symm.nnnorm) ^ n.succ * dist (f b) y : by ring_exp },
-- Deduce from the inductive bound that `uₙ` is a Cauchy sequence, therefore converging.
have : cauchy_seq u,
{ have : ∀ (n : ℕ), dist (u n) (u (n+1)) ≤ f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n,
{ assume n,
calc dist (u n) (u (n+1)) = dist (g (u n)) (u n) : by rw [usucc, dist_comm]
... ≤ f'symm.nnnorm * dist (f (u n)) y : A _
... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) :
mul_le_mul_of_nonneg_left (D n).1 (nnreal.coe_nonneg _)
... = f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n : by ring },
exact cauchy_seq_of_le_geometric _ _ Icf' this },
obtain ⟨x, hx⟩ : ∃ x, tendsto u at_top (𝓝 x) := cauchy_seq_tendsto_of_complete this,
-- As all the `uₙ` belong to the ball `closed_ball b ε`, so does their limit `x`.
have xmem : x ∈ closed_ball b ε :=
is_closed_ball.mem_of_tendsto hx (eventually_of_forall (λ n, C n _ (D n).2)),
refine ⟨x, xmem, _⟩,
-- It remains to check that `f x = y`. This follows from continuity of `f` on `closed_ball b ε`
-- and from the fact that `f uₙ` is converging to `y` by construction.
have hx' : tendsto u at_top (𝓝[closed_ball b ε] x),
{ simp only [nhds_within, tendsto_inf, hx, true_and, ge_iff_le, tendsto_principal],
exact eventually_of_forall (λ n, C n _ (D n).2) },
have T1 : tendsto (λ n, f (u n)) at_top (𝓝 (f x)) :=
(hf.continuous_on.mono hε x xmem).tendsto.comp hx',
have T2 : tendsto (λ n, f (u n)) at_top (𝓝 y),
{ rw tendsto_iff_dist_tendsto_zero,
refine squeeze_zero (λ n, dist_nonneg) (λ n, (D n).1) _,
simpa using (tendsto_pow_at_top_nhds_0_of_lt_1
(mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) Icf').mul tendsto_const_nhds },
exact tendsto_nhds_unique T1 T2,
end
lemma open_image (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse)
(hs : is_open s) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : is_open (f '' s) :=
begin
cases hc with hE hc, { resetI, apply is_open_discrete },
simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢,
intros x hx,
rcases hs x hx with ⟨ε, ε0, hε⟩,
refine ⟨(f'symm.nnnorm⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩,
exact (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'symm (le_of_lt ε0) hε).mono
hε (subset.refl _)
end
lemma image_mem_nhds (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse)
{x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) :
f '' s ∈ 𝓝 (f x) :=
begin
obtain ⟨t, hts, ht, xt⟩ : ∃ t ⊆ s, is_open t ∧ x ∈ t := _root_.mem_nhds_iff.1 hs,
have := is_open.mem_nhds ((hf.mono_set hts).open_image f'symm ht hc) (mem_image_of_mem _ xt),
exact mem_of_superset this (image_subset _ hts),
end
lemma map_nhds_eq (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse)
{x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) :
map f (𝓝 x) = 𝓝 (f x) :=
begin
refine le_antisymm ((hf.continuous_on x (mem_of_mem_nhds hs)).continuous_at hs)
(le_map (λ t ht, _)),
have : f '' (s ∩ t) ∈ 𝓝 (f x) := (hf.mono_set (inter_subset_left s t)).image_mem_nhds
f'symm (inter_mem hs ht) hc,
exact mem_of_superset this (image_subset _ (inter_subset_right _ _)),
end
end locally_onto
/-!
From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`.
We also assume that either `E = {0}`, or `c < ∥f'⁻¹∥⁻¹`. We use `N` as an abbreviation for `∥f'⁻¹∥`.
-/
variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0}
local notation `N` := ∥(f'.symm : F →L[𝕜] E)∥₊
protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) :=
begin
cases hc with hE hc,
{ haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩,
exact antilipschitz_with.of_subsingleton },
convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc,
simp [restrict]
end
protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
injective (s.restrict f) :=
(hf.antilipschitz hc).injective
protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
inj_on f s :=
inj_on_iff_injective.2 $ hf.injective hc
protected lemma surjective [complete_space E]
(hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c) (hc : subsingleton E ∨ c < N⁻¹) :
surjective f :=
begin
cases hc with hE hc,
{ haveI : subsingleton F := (equiv.subsingleton_congr f'.to_linear_equiv.to_equiv).1 hE,
exact surjective_to_subsingleton _ },
{ apply forall_of_forall_mem_closed_ball (λ (y : F), ∃ a, f a = y) (f 0) _,
have hc' : (0 : ℝ) < N⁻¹ - c, by { rw sub_pos, exact hc },
let p : ℝ → Prop := λ R, closed_ball (f 0) R ⊆ set.range f,
have hp : ∀ᶠ (r:ℝ) in at_top, p ((N⁻¹ - c) * r),
{ have hr : ∀ᶠ (r:ℝ) in at_top, 0 ≤ r := eventually_ge_at_top 0,
refine hr.mono (λ r hr, subset.trans _ (image_subset_range f (closed_ball 0 r))),
refine hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse hr _,
exact subset_univ _ },
refine ((tendsto_id.const_mul_at_top hc').frequently hp.frequently).mono _,
exact λ R h y hy, h hy },
end
/-- A map approximating a linear equivalence on a set defines a local equivalence on this set.
Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below.
This is a first step towards the inverse function. -/
def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F :=
(hf.inj_on hc).to_local_equiv _ _
/-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/
lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
continuous_on (hf.to_local_equiv hc).symm (f '' s) :=
begin
apply continuous_on_iff_continuous_restrict.2,
refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous,
exact (λ x hx, (hf.to_local_equiv hc).map_target hx)
end
/-- The inverse function is approximated linearly on `f '' s` by `f'.symm`. -/
lemma to_inv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
approximates_linear_on (hf.to_local_equiv hc).symm (f'.symm : F →L[𝕜] E) (f '' s)
(N * (N⁻¹ - c)⁻¹ * c) :=
begin
assume x hx y hy,
set A := hf.to_local_equiv hc with hA,
have Af : ∀ z, A z = f z := λ z, rfl,
rcases (mem_image _ _ _).1 hx with ⟨x', x's, rfl⟩,
rcases (mem_image _ _ _).1 hy with ⟨y', y's, rfl⟩,
rw [← Af x', ← Af y', A.left_inv x's, A.left_inv y's],
calc ∥x' - y' - (f'.symm) (A x' - A y')∥
≤ N * ∥f' (x' - y' - (f'.symm) (A x' - A y'))∥ :
(f' : E →L[𝕜] F).bound_of_antilipschitz f'.antilipschitz _
... = N * ∥A y' - A x' - f' (y' - x')∥ :
begin
congr' 2,
simp only [continuous_linear_equiv.apply_symm_apply, continuous_linear_equiv.map_sub],
abel,
end
... ≤ N * (c * ∥y' - x'∥) :
mul_le_mul_of_nonneg_left (hf _ y's _ x's) (nnreal.coe_nonneg _)
... ≤ N * (c * (((N⁻¹ - c)⁻¹ : ℝ≥0) * ∥A y' - A x'∥)) :
begin
apply_rules [mul_le_mul_of_nonneg_left, nnreal.coe_nonneg],
rw [← dist_eq_norm, ← dist_eq_norm],
exact (hf.antilipschitz hc).le_mul_dist ⟨y', y's⟩ ⟨x', x's⟩,
end
... = (N * (N⁻¹ - c)⁻¹ * c : ℝ≥0) * ∥A x' - A y'∥ :
by { simp only [norm_sub_rev, nonneg.coe_mul], ring }
end
include cs
section
variables (f s)
/-- Given a function `f` that approximates a linear equivalence on an open set `s`,
returns a local homeomorph with `to_fun = f` and `source = s`. -/
def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F :=
{ to_local_equiv := hf.to_local_equiv hc,
open_source := hs,
open_target := hf.open_image f'.to_nonlinear_right_inverse hs
(by rwa f'.to_linear_equiv.to_equiv.subsingleton_congr at hc),
continuous_to_fun := hf.continuous_on,
continuous_inv_fun := hf.inverse_continuous_on hc }
/-- A function `f` that approximates a linear equivalence on the whole space is a homeomorphism. -/
def to_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c)
(hc : subsingleton E ∨ c < N⁻¹) :
E ≃ₜ F :=
begin
refine (hf.to_local_homeomorph _ _ hc is_open_univ).to_homeomorph_of_source_eq_univ_target_eq_univ
rfl _,
change f '' univ = univ,
rw [image_univ, range_iff_surjective],
exact hf.surjective hc,
end
omit cs
/-- In a real vector space, a function `f` that approximates a linear equivalence on a subset `s`
can be extended to a homeomorphism of the whole space. -/
lemma exists_homeomorph_extension {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
{F : Type*} [normed_add_comm_group F] [normed_space ℝ F] [finite_dimensional ℝ F]
{s : set E} {f : E → F} {f' : E ≃L[ℝ] F} {c : ℝ≥0}
(hf : approximates_linear_on f (f' : E →L[ℝ] F) s c)
(hc : subsingleton E ∨ lipschitz_extension_constant F * c < (∥(f'.symm : F →L[ℝ] E)∥₊)⁻¹) :
∃ g : E ≃ₜ F, eq_on f g s :=
begin
-- the difference `f - f'` is Lipschitz on `s`. It can be extended to a Lipschitz function `u`
-- on the whole space, with a slightly worse Lipschitz constant. Then `f' + u` will be the
-- desired homeomorphism.
obtain ⟨u, hu, uf⟩ : ∃ (u : E → F), lipschitz_with (lipschitz_extension_constant F * c) u
∧ eq_on (f - f') u s := hf.lipschitz_on_with.extend_finite_dimension,
let g : E → F := λ x, f' x + u x,
have fg : eq_on f g s := λ x hx, by simp_rw [g, ← uf hx, pi.sub_apply, add_sub_cancel'_right],
have hg : approximates_linear_on g (f' : E →L[ℝ] F) univ (lipschitz_extension_constant F * c),
{ apply lipschitz_on_with.approximates_linear_on,
rw lipschitz_on_univ,
convert hu,
ext x,
simp only [add_sub_cancel', continuous_linear_equiv.coe_coe, pi.sub_apply] },
haveI : finite_dimensional ℝ E := f'.symm.to_linear_equiv.finite_dimensional,
exact ⟨hg.to_homeomorph g hc, fg⟩,
end
end
@[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs : E → F) = f := rfl
@[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs).source = s := rfl
@[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs).target = f '' s := rfl
lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) :
closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target :=
(hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse
ε0 hε).mono hε (subset.refl _)
end approximates_linear_on
/-!
### Inverse function theorem
Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector
space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict
sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood
of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse
function. -/
namespace has_strict_fderiv_at
/-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'`
with constant `c` on some neighborhood of `a`. -/
lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E}
(hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) :
∃ s ∈ 𝓝 a, approximates_linear_on f f' s c :=
begin
cases hc with hE hc,
{ refine ⟨univ, is_open.mem_nhds is_open_univ trivial, λ x hx y hy, _⟩,
simp [@subsingleton.elim E hE x y] },
have := hf.def hc,
rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this,
rcases this with ⟨s, has, hs⟩,
exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩
end
lemma map_nhds_eq_of_surj [complete_space E] [complete_space F]
{f : E → F} {f' : E →L[𝕜] F} {a : E}
(hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) (h : f'.range = ⊤) :
map f (𝓝 a) = 𝓝 (f a) :=
begin
let f'symm := f'.nonlinear_right_inverse_of_surjective h,
set c : ℝ≥0 := f'symm.nnnorm⁻¹ / 2 with hc,
have f'symm_pos : 0 < f'symm.nnnorm := f'.nonlinear_right_inverse_of_surjective_nnnorm_pos h,
have cpos : 0 < c, by simp [hc, nnreal.half_pos, nnreal.inv_pos, f'symm_pos],
obtain ⟨s, s_nhds, hs⟩ : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c :=
hf.approximates_deriv_on_nhds (or.inr cpos),
apply hs.map_nhds_eq f'symm s_nhds (or.inr (nnreal.half_lt_self _)),
simp [ne_of_gt f'symm_pos],
end
variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E}
lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∃ (s : set E) (hs : a ∈ s ∧ is_open s),
approximates_linear_on f (f' : E →L[𝕜] F) s (∥(f'.symm : F →L[𝕜] E)∥₊⁻¹ / 2) :=
begin
refine ((nhds_basis_opens a).exists_iff _).1 _,
exact (λ s t, approximates_linear_on.mono_set),
exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $
λ hf', nnreal.half_pos $ nnreal.inv_pos.2 $ hf')
end
include cs
variable (f)
/-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph`
with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem.
The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function
of this `local_homeomorph` has derivative `f'.symm`. -/
def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F :=
approximates_linear_on.to_local_homeomorph f
(classical.some hf.approximates_deriv_on_open_nhds)
(classical.some_spec hf.approximates_deriv_on_open_nhds).snd
(f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $
nnreal.inv_pos.2 $ hf')
(classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2
variable {f}
@[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
(hf.to_local_homeomorph f : E → F) = f := rfl
lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
a ∈ (hf.to_local_homeomorph f).source :=
(classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1
lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
f a ∈ (hf.to_local_homeomorph f).target :=
(hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source
lemma map_nhds_eq_of_equiv (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
map f (𝓝 a) = 𝓝 (f a) :=
(hf.to_local_homeomorph f).map_nhds_eq hf.mem_to_local_homeomorph_source
variables (f f' a)
/-- Given a function `f` with an invertible derivative, returns a function that is locally inverse
to `f`. -/
def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E :=
(hf.to_local_homeomorph f).symm
variables {f f' a}
lemma local_inverse_def (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
hf.local_inverse f _ _ = (hf.to_local_homeomorph f).symm :=
rfl
lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x :=
(hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source
@[simp] lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
hf.local_inverse f f' a (f a) = a :=
hf.eventually_left_inverse.self_of_nhds
lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y :=
(hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source
lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
continuous_at (hf.local_inverse f f' a) (f a) :=
(hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target
lemma local_inverse_tendsto (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
tendsto (hf.local_inverse f f' a) (𝓝 $ f a) (𝓝 a) :=
(hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source
lemma local_inverse_unique (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E}
(hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
∀ᶠ y in 𝓝 (f a), g y = local_inverse f f' a hf y :=
eventually_eq_of_left_inv_of_right_inv hg hf.eventually_right_inverse $
(hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source
/-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`,
then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/
theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) :=
(hf.to_local_homeomorph f).has_strict_fderiv_at_symm hf.image_mem_to_local_homeomorph_target $
by simpa [← local_inverse_def] using hf
/-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability
and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`.
For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]`
see `of_local_left_inverse`. -/
theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E}
(hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) :=
hf.to_local_inverse.congr_of_eventually_eq $ (hf.local_inverse_unique hg).mono $ λ _, eq.symm
end has_strict_fderiv_at
/-- If a function has an invertible strict derivative at all points, then it is an open map. -/
lemma open_map_of_strict_fderiv_equiv [complete_space E] {f : E → F} {f' : E → E ≃L[𝕜] F}
(hf : ∀ x, has_strict_fderiv_at f (f' x : E →L[𝕜] F) x) :
is_open_map f :=
is_open_map_iff_nhds_le.2 $ λ x, (hf x).map_nhds_eq_of_equiv.ge
/-!
### Inverse function theorem, 1D case
In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`.
We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and
`f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`.
-/
namespace has_strict_deriv_at
variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a)
(hf' : f' ≠ 0)
include cs
variables (f f' a)
/-- A function that is inverse to `f` near `a`. -/
@[reducible] def local_inverse : 𝕜 → 𝕜 :=
(hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _
variables {f f' a}
lemma map_nhds_eq : map f (𝓝 a) = 𝓝 (f a) :=
(hf.has_strict_fderiv_at_equiv hf').map_nhds_eq_of_equiv
theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) :=
(hf.has_strict_fderiv_at_equiv hf').to_local_inverse
theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
has_strict_deriv_at g f'⁻¹ (f a) :=
(hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg
end has_strict_deriv_at
/-- If a function has a non-zero strict derivative at all points, then it is an open map. -/
lemma open_map_of_strict_deriv [complete_space 𝕜] {f f' : 𝕜 → 𝕜}
(hf : ∀ x, has_strict_deriv_at f (f' x) x) (h0 : ∀ x, f' x ≠ 0) :
is_open_map f :=
is_open_map_iff_nhds_le.2 $ λ x, ((hf x).map_nhds_eq (h0 x)).ge
/-!
### Inverse function theorem, smooth case
-/
namespace cont_diff_at
variables {𝕂 : Type*} [is_R_or_C 𝕂]
variables {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕂 E']
variables {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕂 F']
variables [complete_space E'] (f : E' → F') {f' : E' ≃L[𝕂] F'} {a : E'}
/-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible
derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. -/
def to_local_homeomorph
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
local_homeomorph E' F' :=
(hf.has_strict_fderiv_at' hf' hn).to_local_homeomorph f
variable {f}
@[simp] lemma to_local_homeomorph_coe
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
(hf.to_local_homeomorph f hf' hn : E' → F') = f := rfl
lemma mem_to_local_homeomorph_source
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
a ∈ (hf.to_local_homeomorph f hf' hn).source :=
(hf.has_strict_fderiv_at' hf' hn).mem_to_local_homeomorph_source
lemma image_mem_to_local_homeomorph_target
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
f a ∈ (hf.to_local_homeomorph f hf' hn).target :=
(hf.has_strict_fderiv_at' hf' hn).image_mem_to_local_homeomorph_target
/-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative
at `a`, returns a function that is locally inverse to `f`. -/
def local_inverse
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
F' → E' :=
(hf.has_strict_fderiv_at' hf' hn).local_inverse f f' a
lemma local_inverse_apply_image
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
hf.local_inverse hf' hn (f a) = a :=
(hf.has_strict_fderiv_at' hf' hn).local_inverse_apply_image
/-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative
at `a`, the inverse function (produced by `cont_diff.to_local_homeomorph`) is
also `cont_diff`. -/
lemma to_local_inverse
{n : with_top ℕ} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a)
(hn : 1 ≤ n) :
cont_diff_at 𝕂 n (hf.local_inverse hf' hn) (f a) :=
begin
have := hf.local_inverse_apply_image hf' hn,
apply (hf.to_local_homeomorph f hf' hn).cont_diff_at_symm
(image_mem_to_local_homeomorph_target hf hf' hn),
{ convert hf' },
{ convert hf }
end
end cont_diff_at
|
b814e29b240639b6fd52b46e7d50191006112f92 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/meta/expr.lean | 98e29ab44f9cbdf738eebc6faf1eb05e9160055a | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 4,140 | lean | /-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis
Additional non-tactic operations on expr and related types
-/
namespace name
meta def deinternalize_field : name → name
| (name.mk_string s name.anonymous) :=
let i := s.mk_iterator in
if i.curr = '_' then i.next.next_to_string else s
| n := n
meta def get_nth_prefix : name → ℕ → name
| nm 0 := nm
| nm (n + 1) := get_nth_prefix nm.get_prefix n
private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ
| anonymous n := (anonymous, 1)
| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in
if height ≤ n then (anonymous, height + 1)
else (nm.update_prefix pfx, height + 1)
-- Pops the top `n` prefixes from the given name.
meta def pop_nth_prefix (nm : name) (n : ℕ) : name :=
prod.fst $ pop_nth_prefix_aux nm n
meta def pop_prefix (n : name) : name :=
pop_nth_prefix n 1
-- `name`s can contain numeral pieces, which are not legal names
-- when typed/passed directly to the parser. We turn an arbitrary
-- name into a legal identifier name.
meta def sanitize_name : name → name
| name.anonymous := name.anonymous
| (name.mk_string s p) := name.mk_string s $ sanitize_name p
| (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p
def append_suffix : name → string → name
| (mk_string s n) s' := mk_string (s ++ s') n
| n _ := n
end name
namespace expr
open tactic
protected meta def to_pos_nat : expr → option ℕ
| `(has_one.one _) := some 1
| `(bit0 %%e) := bit0 <$> e.to_pos_nat
| `(bit1 %%e) := bit1 <$> e.to_pos_nat
| _ := none
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero _) := some 0
| e := e.to_pos_nat
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := coe <$> e.to_nat
meta def is_meta_var : expr → bool
| (mvar _ _ _) := tt
| e := ff
meta def is_sort : expr → bool
| (sort _) := tt
| e := ff
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es)
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
match e' with
| expr.const n _ := if n.get_prefix = pre then l.insert n else l
| _ := l
end
meta def is_mvar : expr → bool
| (mvar _ _ _) := tt
| _ := ff
/--
is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
meta def is_num_eq : expr → expr → bool
| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt
| `(@has_one.one _ _) `(@has_one.one _ _) := tt
| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b
| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b
| `(-%%a) `(-%%b) := a.is_num_eq b
| `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b
| _ _ := ff
end expr
namespace environment
meta def in_current_file' (env : environment) (n : name) : bool :=
env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind])
meta def is_structure_like (env : environment) (n : name) : option (nat × name) :=
do guardb (env.is_inductive n),
d ← (env.get n).to_option,
[intro] ← pure (env.constructors_of n) | none,
guard (env.inductive_num_indices n = 0),
some (env.inductive_num_params n, intro)
meta def is_structure (env : environment) (n : name) : bool :=
option.is_some $ do
(nparams, intro) ← env.is_structure_like n,
di ← (env.get intro).to_option,
expr.pi x _ _ _ ← nparams.iterate
(λ e : option expr, do expr.pi _ _ _ body ← e | none, some body)
(some di.type) | none,
env.is_projection (n ++ x.deinternalize_field)
end environment
|
a25bc708db8193a66312a8f046b0ba5b814bd631 | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /AIME_2021_I_14.lean | bae56c6da852792b9a1d57ba3694c07cda7ad1a1 | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 386 | lean | import algebra.big_operators.basic
import data.int.gcd
import data.real.basic
import data.finset.basic
import number_theory.divisors
#check int.lcm 42 47
open_locale big_operators
theorem AIME_2021_I_14 (n1:ℕ)(sigma:ℕ → ℕ )(hs:∀(n:pnat), sigma n = ∑ i in nat.divisors n, i)
(h:∀ (a:pnat),2021∈ nat.divisors (sigma (a^n1) -1) ):
n1≥ 2*3*7*23*43*47:=
begin
sorry
end |
13e34d73dee553bf4974fcb26ec80a061ff4c3ba | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebra/group/hom.lean | 5849915e0d0e50e4d19ac67a370d495c91c4c8f8 | [
"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 | 14,103 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes,
Johannes Hölzl, Yury Kudryashov
-/
import algebra.group.commute
/-!
# monoid and group homomorphisms
This file defines the bundled structures for monoid and group homomorphisms. Namely, we define
`monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp.,
additive) monoids or groups.
We also define coercion to a function, and usual operations: composition, identity homomorphism,
pointwise multiplication and pointwise inversion.
## Notations
* `→*` for bundled monoid homs (also use for group homs)
* `→+` for bundled add_monoid homs (also use for add_group homs)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the
instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they
can be inferred from the type it is faster to use this method than to use type class inference.
Historically this file also included definitions of unbundled homomorphism classes; they were
deprecated and moved to `deprecated/group`.
## Tags
monoid_hom, add_monoid_hom
-/
variables {M : Type*} {N : Type*} {P : Type*} -- monoids
{G : Type*} {H : Type*} -- groups
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] :=
(to_fun : M → N)
(map_zero' : to_fun 0 = 0)
(map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y)
infixr ` →+ `:25 := add_monoid_hom
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
@[to_additive]
structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] :=
(to_fun : M → N)
(map_one' : to_fun 1 = 1)
(map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y)
infixr ` →* `:25 := monoid_hom
@[to_additive]
instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) :=
⟨_, monoid_hom.to_fun⟩
namespace monoid_hom
variables {mM : monoid M} {mN : monoid N} {mP : monoid P}
variables [group G] [comm_group H]
include mM mN
@[simp, to_additive]
lemma to_fun_eq_coe (f : M →* N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma coe_mk (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl
@[to_additive]
theorem congr_fun {f g : M →* N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : M →* N, h x) h
@[to_additive]
theorem congr_arg (f : M →* N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext, to_additive]
lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g :=
coe_inj (funext h)
attribute [ext] _root_.add_monoid_hom.ext
@[to_additive]
lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
/-- If `f` is a monoid homomorphism then `f 1 = 1`. -/
@[simp, to_additive]
lemma map_one (f : M →* N) : f 1 = 1 := f.map_one'
/-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/
add_decl_doc add_monoid_hom.map_zero
/-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/
@[simp, to_additive]
lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/
add_decl_doc add_monoid_hom.map_add
@[to_additive]
lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 :=
by rw [← f.map_mul, h, f.map_one]
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse,
then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a right inverse, then `f x` has a right inverse too."]
lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) :
∃ y, f x * y = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse,
then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see
`is_add_unit.map`."]
lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) :
∃ y, y * f x = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
omit mN mM
/-- The identity map from a monoid to itself. -/
@[to_additive]
def id (M : Type*) [monoid M] : M →* M :=
{ to_fun := id,
map_one' := rfl,
map_mul' := λ _ _, rfl }
/-- The identity map from an additive monoid to itself. -/
add_decl_doc add_monoid_hom.id
@[simp, to_additive] lemma id_apply {M : Type*} [monoid M] (x : M) :
id M x = x := rfl
include mM mN mP
/-- Composition of monoid morphisms as a monoid morphism. -/
@[to_additive]
def comp (hnp : N →* P) (hmn : M →* N) : M →* P :=
{ to_fun := hnp ∘ hmn,
map_one' := by simp,
map_mul' := by simp }
/-- Composition of additive monoid morphisms as an additive monoid morphism. -/
add_decl_doc add_monoid_hom.comp
@[simp, to_additive] lemma comp_apply (g : N →* P) (f : M →* N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of monoid homomorphisms is associative. -/
@[to_additive] lemma comp_assoc {Q : Type*} [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive]
lemma cancel_right {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma cancel_left {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩
omit mP
@[simp, to_additive] lemma comp_id (f : M →* N) : f.comp (id M) = f := ext $ λ x, rfl
@[simp, to_additive] lemma id_comp (f : M →* N) : (id N).comp f = f := ext $ λ x, rfl
end monoid_hom
section End
namespace monoid
variables (M) [monoid M]
/-- The monoid of endomorphisms. -/
protected def End := M →* M
namespace End
instance : monoid (monoid.End M) :=
{ mul := monoid_hom.comp,
one := monoid_hom.id M,
mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _,
mul_one := monoid_hom.comp_id,
one_mul := monoid_hom.id_comp }
instance : inhabited (monoid.End M) := ⟨1⟩
instance : has_coe_to_fun (monoid.End M) := ⟨_, monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl
end monoid
namespace add_monoid
variables (A : Type*) [add_monoid A]
/-- The monoid of endomorphisms. -/
protected def End := A →+ A
namespace End
instance : monoid (add_monoid.End A) :=
{ mul := add_monoid_hom.comp,
one := add_monoid_hom.id A,
mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _,
mul_one := add_monoid_hom.comp_id,
one_mul := add_monoid_hom.id_comp }
instance : inhabited (add_monoid.End A) := ⟨1⟩
instance : has_coe_to_fun (add_monoid.End A) := ⟨_, add_monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl
end add_monoid
end End
namespace monoid_hom
variables [mM : monoid M] [mN : monoid N] [mP : monoid P]
variables [group G] [comm_group H]
include mM mN
/-- `1` is the monoid homomorphism sending all elements to `1`. -/
@[to_additive]
instance : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩
/-- `0` is the additive monoid homomorphism sending all elements to `0`. -/
add_decl_doc add_monoid_hom.has_zero
@[simp, to_additive] lemma one_apply (x : M) : (1 : M →* N) x = 1 := rfl
@[to_additive]
instance : inhabited (M →* N) := ⟨1⟩
omit mM mN
/-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism
sending `x` to `f x * g x`. -/
@[to_additive]
instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) :=
⟨λ f g,
{ to_fun := λ m, f m * g m,
map_one' := show f 1 * g 1 = 1, by simp,
map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y),
rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩
/-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the
additive monoid morphism sending `x` to `f x + g x`. -/
add_decl_doc add_monoid_hom.has_add
@[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N}
(f g : M →* N) (x : M) :
(f * g) x = f x * g x := rfl
/-- (M →* N) is a comm_monoid if N is commutative. -/
@[to_additive]
instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) :=
{ mul := (*),
mul_assoc := by intros; ext; apply mul_assoc,
one := 1,
one_mul := by intros; ext; apply one_mul,
mul_one := by intros; ext; apply mul_one,
mul_comm := by intros; ext; apply mul_comm }
/-- `flip` arguments of `f : M →* N →* P` -/
@[to_additive "`flip` arguments of `f : M →+ N →+ P`"]
def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) :
N →* M →* P :=
{ to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩,
map_one' := ext $ λ x, (f x).map_one,
map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ }
@[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P}
(f : M →* N →* P) (x : M) (y : N) :
f.flip y x = f x y :=
rfl
/-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/
@[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`,
then they are equal at `-x`." ]
lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) :
f x⁻¹ = g x⁻¹ :=
left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $
h.symm ▸ g.map_mul_eq_one $ mul_inv_self x
/-- Group homomorphisms preserve inverse. -/
@[simp, to_additive]
theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ :=
eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g
/-- Group homomorphisms preserve division. -/
@[simp, to_additive]
theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) :
f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv]
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff {G H} [group G] [monoid H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h x hfx, h $ hfx.trans f.map_one.symm,
λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩
include mM
/-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/
@[to_additive]
def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G :=
{ to_fun := f,
map_mul' := map_mul,
map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] }
/-- Makes an additive group homomomorphism from a proof that the map preserves multiplication. -/
add_decl_doc add_monoid_hom.mk'
@[simp, to_additive]
lemma coe_mk' {f : M → G} (map_mul : ∀ a b : M, f (a * b) = f a * f b) :
⇑(mk' f map_mul) = f := rfl
omit mM
/-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending
`x` to `(f x)⁻¹`. -/
@[to_additive]
instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) :=
⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩
/-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the
homomorphism sending `x` to `-(f x)`. -/
add_decl_doc add_monoid_hom.has_neg
@[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G}
(f : M →* G) (x : M) :
f⁻¹ x = (f x)⁻¹ := rfl
/-- If `G` is a commutative group, then `M →* G` a commutative group too. -/
@[to_additive]
instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) :=
{ inv := has_inv.inv,
mul_left_inv := by intros; ext; apply mul_left_inv,
..monoid_hom.comm_monoid }
/-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/
add_decl_doc add_monoid_hom.add_comm_group
end monoid_hom
namespace add_monoid_hom
/-- Additive group homomorphisms preserve subtraction. -/
@[simp] theorem map_sub {G H} [add_group G] [add_group H] (f : G →+ H) (g h : G) :
f (g - h) = (f g) - (f h) := f.map_add_neg g h
end add_monoid_hom
section commute
variables [monoid M] [monoid N] {a x y : M}
@[simp, to_additive]
protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) :
semiconj_by (f a) (f x) (f y) :=
by simpa only [semiconj_by, f.map_mul] using congr_arg f h
@[simp, to_additive]
protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f
end commute
|
f213e2c31775e27980928289b40b4afb821c157b | 94e33a31faa76775069b071adea97e86e218a8ee | /src/linear_algebra/dual.lean | 96ef0d5e4fdbd125ffc3c10425c110c5aaaf1bc0 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 30,562 | 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 : linear_map_class (dual R M) R M R :=
linear_map.semilinear_map_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_semiring R] [add_comm_monoid 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_semiring R] [add_comm_monoid 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_semiring R] [add_comm_monoid 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⟩ :=
by convert 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
open module
section dual_map
variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*}
variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂]
/-- 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
end dual_map
namespace linear_map
variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*}
variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂]
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
namespace tensor_product
variables (R : Type*) (M : Type*) (N : Type*)
variables {ι κ : Type*}
variables [decidable_eq ι] [decidable_eq κ]
variables [fintype ι] [fintype κ]
open_locale big_operators
open_locale tensor_product
local attribute [ext] tensor_product.ext
open tensor_product
open linear_map
section
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N]
variables [module R M] [module R N]
/--
The canonical linear map from `dual M ⊗ dual N` to `dual (M ⊗ N)`,
sending `f ⊗ g` to the composition of `tensor_product.map f g` with
the natural isomorphism `R ⊗ R ≃ R`.
-/
def dual_distrib : (dual R M) ⊗[R] (dual R N) →ₗ[R] dual R (M ⊗[R] N) :=
(comp_right ↑(tensor_product.lid R R)) ∘ₗ hom_tensor_hom_map R M N R R
variables {R M N}
@[simp]
lemma dual_distrib_apply (f : dual R M) (g : dual R N) (m : M) (n : N) :
dual_distrib R M N (f ⊗ₜ g) (m ⊗ₜ n) = f m * g n :=
by simp only [dual_distrib, coe_comp, function.comp_app, hom_tensor_hom_map_apply,
comp_right_apply, linear_equiv.coe_coe, map_tmul, lid_tmul, algebra.id.smul_eq_mul]
end
variables {R M N}
variables [comm_ring R] [add_comm_group M] [add_comm_group N]
variables [module R M] [module R N]
/--
An inverse to `dual_tensor_dual_map` given bases.
-/
noncomputable
def dual_distrib_inv_of_basis (b : basis ι R M) (c : basis κ R N) :
dual R (M ⊗[R] N) →ₗ[R] (dual R M) ⊗[R] (dual R N) :=
∑ i j, (ring_lmap_equiv_self R ℕ _).symm (b.dual_basis i ⊗ₜ c.dual_basis j)
∘ₗ applyₗ (c j) ∘ₗ applyₗ (b i) ∘ₗ (lcurry R M N R)
@[simp]
lemma dual_distrib_inv_of_basis_apply (b : basis ι R M) (c : basis κ R N)
(f : dual R (M ⊗[R] N)) : dual_distrib_inv_of_basis b c f =
∑ i j, (f (b i ⊗ₜ c j)) • (b.dual_basis i ⊗ₜ c.dual_basis j) :=
by simp [dual_distrib_inv_of_basis]
/--
A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` given bases for `M` and `N`.
It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural
isomorphism `R ⊗ R ≃ R`.
-/
@[simps]
noncomputable def dual_distrib_equiv_of_basis (b : basis ι R M) (c : basis κ R N) :
(dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) :=
begin
refine linear_equiv.of_linear
(dual_distrib R M N) (dual_distrib_inv_of_basis b c) _ _,
{ ext f m n,
have h : ∀ (r s : R), r • s = s • r := is_commutative.comm,
simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply,
linear_map.map_sum, map_smul, sum_apply, smul_apply, dual_distrib_apply, h (f _) _,
← f.map_smul, ←f.map_sum, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis,
basis.coord_apply, basis.sum_repr] },
{ ext f g,
simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply,
dual_distrib_apply, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis,
basis.sum_dual_apply_smul_coord] }
end
variables (R M N)
variables [module.finite R M] [module.finite R N] [module.free R M] [module.free R N]
variables [nontrivial R]
open_locale classical
/--
A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` when `M` and `N` are finite free
modules. It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural
isomorphism `R ⊗ R ≃ R`.
-/
@[simp]
noncomputable
def dual_distrib_equiv : (dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) :=
dual_distrib_equiv_of_basis (module.free.choose_basis R M) (module.free.choose_basis R N)
end tensor_product
|
8cce968bac24c171a282b9cfeaf136f1b658af14 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/list/tfae.lean | c687b3eb64e276c3865e85e718ef6e07e162f983 | [
"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,129 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Simon Hudon
-/
import data.list.basic
/-!
# The Following Are Equivalent
This file allows to state that all propositions in a list are equivalent. It is used by
`tactic.tfae`.
`tfae l` means `∀ x ∈ l, ∀ y ∈ l, x ↔ y`. This is equivalent to `pairwise (↔) l`.
-/
namespace list
/--
tfae: The Following (propositions) Are Equivalent.
The `tfae_have` and `tfae_finish` tactics can be useful in proofs with `tfae` goals.
-/
def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y
theorem tfae_nil : tfae [] := forall_mem_nil _
theorem tfae_singleton (p) : tfae [p] := by simp [tfae, -eq_iff_iff]
theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) :
tfae (a::l) ↔ (a ↔ b) ∧ tfae l :=
⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩,
begin
rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq),
{ refl },
{ exact ab.trans (H _ h _ hq) },
{ exact (ab.trans (H _ h _ hp)).symm },
{ exact H _ hp _ hq }
end⟩
theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) :=
tfae_cons_of_mem (or.inl rfl)
theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l :=
λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm
theorem tfae_of_cycle {a b} {l : list Prop} :
list.chain (→) a (b::l) → (ilast' b l → a) → tfae (a::b::l) :=
begin
induction l with c l IH generalizing a b;
simp only [tfae_cons_cons, tfae_singleton, and_true, chain_cons, chain.nil] at *,
{ intros a b, exact iff.intro a b },
rintros ⟨ab,⟨bc,ch⟩⟩ la,
have := IH ⟨bc,ch⟩ (ab ∘ la),
exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (ilast'_mem _ _)).1 ∘ bc⟩, this⟩
end
theorem tfae.out {l} (h : tfae l) (n₁ n₂) {a b}
(h₁ : list.nth l n₁ = some a . tactic.interactive.refl)
(h₂ : list.nth l n₂ = some b . tactic.interactive.refl) :
a ↔ b :=
h _ (list.nth_mem h₁) _ (list.nth_mem h₂)
end list
|
4e040f4b5b6a8a778914519fc793be491a92fe1a | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/zsqrtd/gaussian_int.lean | 8be057e9c246fdef4632d070e250a715facb761a | [
"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 | 12,684 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
-/
import data.zsqrtd.basic
import data.complex.basic
import ring_theory.principal_ideal_domain
import number_theory.quadratic_reciprocity
/-!
# Gaussian integers
The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both
integers.
## Main definitions
The Euclidean domain structure on `ℤ[i]` is defined in this file.
The homomorphism `to_complex` into the complex numbers is also defined in this file.
## Main statements
`prime_iff_mod_four_eq_three_of_nat_prime`
A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4`
## Notations
This file uses the local notation `ℤ[i]` for `gaussian_int`
## Implementation notes
Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers
adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties
and definitions about `zsqrtd` can easily be used.
-/
open zsqrtd complex
@[reducible] def gaussian_int : Type := zsqrtd (-1)
local notation `ℤ[i]` := gaussian_int
namespace gaussian_int
instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩
instance : comm_ring ℤ[i] := zsqrtd.comm_ring
section
local attribute [-instance] complex.field -- Avoid making things noncomputable unnecessarily.
/-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/
def to_complex : ℤ[i] →+* ℂ :=
begin
refine_struct { to_fun := λ x : ℤ[i], (x.re + x.im * I : ℂ), .. };
intros; apply complex.ext; dsimp; norm_cast; simp; abel
end
end
instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩
lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl
lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def]
lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ :=
by apply complex.ext; simp [to_complex_def]
@[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def]
@[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def]
@[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def]
@[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def]
@[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := to_complex.map_add _ _
@[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := to_complex.map_mul _ _
@[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := to_complex.map_one
@[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := to_complex.map_zero
@[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := to_complex.map_neg _
@[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := to_complex.map_sub _ _
@[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y :=
by cases x; cases y; simp [to_complex_def₂]
@[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 :=
by rw [← to_complex_zero, to_complex_inj]
@[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq :=
by rw [norm, norm_sq]; simp
@[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq :=
by cases x; rw [norm, norm_sq]; simp
lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _
@[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 :=
by rw [← @int.cast_inj ℝ _ _ _]; simp
lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 :=
by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg]
@[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm :=
int.nat_abs_of_nonneg (norm_nonneg _)
@[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α]
(x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm :=
by rw [← int.cast_coe_nat, coe_nat_abs_norm]
lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs =
x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs :=
int.coe_nat_inj $ begin simp, simp [norm] end
protected def div (x y : ℤ[i]) : ℤ[i] :=
let n := (rat.of_int (norm y))⁻¹ in let c := y.conj in
⟨round (rat.of_int (x * c).re * n : ℚ),
round (rat.of_int (x * c).im * n : ℚ)⟩
instance : has_div ℤ[i] := ⟨gaussian_int.div⟩
lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ),
round ((x * conj y).im / norm y : ℚ)⟩ :=
show zsqrtd.mk _ _ = _, by simp [rat.of_int_eq_mk, rat.mk_eq_div, div_eq_mul_inv]
lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) :=
by rw [div_def, ← @rat.cast_round ℝ _ _];
simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul]
lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) :=
by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _];
simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul]
local notation `abs'` := _root_.abs
lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re)
(him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq :=
by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul,
← _root_.abs_mul_self y.re, _root_.abs_mul y.re,
← _root_.abs_mul_self x.im, _root_.abs_mul x.im,
← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact
(add_le_add (mul_self_le_mul_self (abs_nonneg _) hre)
(mul_self_le_mul_self (abs_nonneg _) him))
lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) :
((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 :=
calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq =
((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re +
((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq :
congr_arg _ $ by apply complex.ext; simp
... ≤ (1 / 2 + 1 / 2 * I).norm_sq :
have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num,
norm_sq_le_norm_sq_of_re_le_of_im_le
(by rw [to_complex_div_re]; simp [norm_sq, this];
simpa using abs_sub_round (x / y : ℂ).re)
(by rw [to_complex_div_im]; simp [norm_sq, this];
simpa using abs_sub_round (x / y : ℂ).im)
... < 1 : by simp [norm_sq]; norm_num
protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y)
instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩
lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl
lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm :=
have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj],
(@int.cast_lt ℝ _ _ _).1 $
calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def]
... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq :
by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this]
... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _)
(norm_sq_pos.2 this)
... = norm y : by simp
lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) :
(x % y).norm.nat_abs < y.norm.nat_abs :=
int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy])
lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) :
(norm x).nat_abs ≤ (norm (x * y)).nat_abs :=
by rw [norm_mul, int.nat_abs_mul];
exact le_mul_of_one_le_right (nat.zero_le _)
(int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact norm_pos.2 hy))
instance : nontrivial ℤ[i] :=
⟨⟨0, 1, dec_trivial⟩⟩
instance : euclidean_domain ℤ[i] :=
{ quotient := (/),
remainder := (%),
quotient_zero := λ _, by simp [div_def]; refl,
quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def],
r := _,
r_well_founded := measure_wf (int.nat_abs ∘ norm),
remainder_lt := nat_abs_norm_mod_lt,
mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0,
.. gaussian_int.comm_ring,
.. gaussian_int.nontrivial }
open principal_ideal_ring
lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) :
p % 4 = 3 :=
hp.eq_two_or_odd.elim
(λ hp2, absurd hpi (mt irreducible_iff_prime.2 $
λ ⟨hu, h⟩, begin
have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl),
rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this,
exact absurd this dec_trivial
end))
(λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3,
have hp41 : p % 4 = 1,
begin
rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1,
have := nat.mod_lt p (show 0 < 4, from dec_trivial),
revert this hp3 hp1,
generalize : p % 4 = m, dec_trivial!,
end,
let ⟨k, hk⟩ := (zmod.exists_pow_two_eq_neg_one_iff_mod_four_ne_three p).2 $
by rw hp41; exact dec_trivial in
begin
obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k,
{ refine ⟨k.val, k.val_lt, zmod.cast_val k⟩ },
have hpk : p ∣ k ^ 2 + 1,
by rw [← char_p.cast_eq_zero_iff (zmod p) p]; simp *,
have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ :=
by simp [pow_two, zsqrtd.ext],
have hpne1 : p ≠ 1, from (ne_of_lt (hp.one_lt)).symm,
have hkltp : 1 + k * k < p * p,
from calc 1 + k * k ≤ k + k * k :
add_le_add_right (nat.pos_of_ne_zero
(λ hk0, by clear_aux_decl; simp [*, pow_succ'] at *)) _
... = k * (k + 1) : by simp [add_comm, mul_add]
... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _),
have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, -1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, 1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2
(by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff];
exact λ h, (ne_of_lt hp.one_lt).symm h.1),
obtain ⟨y, hy⟩ := hpk,
have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩,
clear_aux_decl, tauto
end)
lemma sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact p.prime]
(hpi : ¬irreducible (p : ℤ[i])) : ∃ a b, a^2 + b^2 = p :=
have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $
by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff];
exact λ h, (ne_of_lt hp.one_lt).symm h.1,
have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b,
by simpa [irreducible, hpu, not_forall, not_or_distrib] using hpi,
let ⟨a, b, hpab, hau, hbu⟩ := hab in
have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff
(mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $
by rw [← int.coe_nat_inj', int.coe_nat_pow, pow_two,
← @norm_nat_cast (-1), hpab];
simp).1,
⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, pow_two] using hnap⟩
lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) :
prime (p : ℤ[i]) :=
irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi,
let ⟨a, b, hab⟩ := sum_two_squares_of_nat_prime_of_not_irreducible p hpi in
have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.cast_mod_nat 4 p, hp3]; exact dec_trivial,
this a b (hab ▸ by simp)
/-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/
lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] :
prime (p : ℤ[i]) ↔ p % 4 = 3 :=
⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩
end gaussian_int
|
152cade4e7dbd299e7310932e442786393f377a4 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/normed_space/banach_steinhaus.lean | a471d27e9fbc4dfed3ff7964d94770cc84aec6d5 | [
"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,361 | lean | /-
Copyright (c) 2021 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import analysis.normed_space.operator_norm
import topology.metric_space.baire
import topology.algebra.module.basic
/-!
# The Banach-Steinhaus theorem: Uniform Boundedness Principle
Herein we prove the Banach-Steinhaus theorem: any collection of bounded linear maps
from a Banach space into a normed space which is pointwise bounded is uniformly bounded.
## TODO
For now, we only prove the standard version by appeal to the Baire category theorem.
Much more general versions exist (in particular, for maps from barrelled spaces to locally
convex spaces), but these are not yet in `mathlib`.
-/
open set
variables
{E F 𝕜 𝕜₂ : Type*}
[semi_normed_group E] [semi_normed_group F]
[nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂]
[normed_space 𝕜 E] [normed_space 𝕜₂ F]
{σ₁₂ : 𝕜 →+* 𝕜₂} [ring_hom_isometric σ₁₂]
/-- This is the standard Banach-Steinhaus theorem, or Uniform Boundedness Principle.
If a family of continuous linear maps from a Banach space into a normed space is pointwise
bounded, then the norms of these linear maps are uniformly bounded. -/
theorem banach_steinhaus {ι : Type*} [complete_space E] {g : ι → E →SL[σ₁₂] F}
(h : ∀ x, ∃ C, ∀ i, ∥g i x∥ ≤ C) :
∃ C', ∀ i, ∥g i∥ ≤ C' :=
begin
/- sequence of subsets consisting of those `x : E` with norms `∥g i x∥` bounded by `n` -/
let e : ℕ → set E := λ n, (⋂ i : ι, { x : E | ∥g i x∥ ≤ n }),
/- each of these sets is closed -/
have hc : ∀ n : ℕ, is_closed (e n), from λ i, is_closed_Inter (λ i,
is_closed_le (continuous.norm (g i).cont) continuous_const),
/- the union is the entire space; this is where we use `h` -/
have hU : (⋃ n : ℕ, e n) = univ,
{ refine eq_univ_of_forall (λ x, _),
cases h x with C hC,
obtain ⟨m, hm⟩ := exists_nat_ge C,
exact ⟨e m, mem_range_self m, mem_Inter.mpr (λ i, le_trans (hC i) hm)⟩ },
/- apply the Baire category theorem to conclude that for some `m : ℕ`, `e m` contains some `x` -/
rcases nonempty_interior_of_Union_of_closed hc hU with ⟨m, x, hx⟩,
rcases metric.is_open_iff.mp is_open_interior x hx with ⟨ε, ε_pos, hε⟩,
obtain ⟨k, hk⟩ := normed_field.exists_one_lt_norm 𝕜,
/- show all elements in the ball have norm bounded by `m` after applying any `g i` -/
have real_norm_le : ∀ z : E, z ∈ metric.ball x ε → ∀ i : ι, ∥g i z∥ ≤ m,
{ intros z hz i,
replace hz := mem_Inter.mp (interior_Inter_subset _ (hε hz)) i,
apply interior_subset hz },
have εk_pos : 0 < ε / ∥k∥ := div_pos ε_pos (zero_lt_one.trans hk),
refine ⟨(m + m : ℕ) / (ε / ∥k∥), λ i, continuous_linear_map.op_norm_le_of_shell ε_pos _ hk _⟩,
{ exact div_nonneg (nat.cast_nonneg _) εk_pos.le },
intros y le_y y_lt,
calc ∥g i y∥
= ∥g i (y + x) - g i x∥ : by rw [continuous_linear_map.map_add, add_sub_cancel]
... ≤ ∥g i (y + x)∥ + ∥g i x∥ : norm_sub_le _ _
... ≤ m + m : add_le_add (real_norm_le (y + x) (by rwa [add_comm, add_mem_ball_iff_norm]) i)
(real_norm_le x (metric.mem_ball_self ε_pos) i)
... = (m + m : ℕ) : (m.cast_add m).symm
... ≤ (m + m : ℕ) * (∥y∥ / (ε / ∥k∥))
: le_mul_of_one_le_right (nat.cast_nonneg _)
((one_le_div $ div_pos ε_pos (zero_lt_one.trans hk)).2 le_y)
... = (m + m : ℕ) / (ε / ∥k∥) * ∥y∥ : (mul_comm_div _ _ _).symm,
end
open_locale ennreal
open ennreal
/-- This version of Banach-Steinhaus is stated in terms of suprema of `↑∥⬝∥₊ : ℝ≥0∞`
for convenience. -/
theorem banach_steinhaus_supr_nnnorm {ι : Type*} [complete_space E] {g : ι → E →SL[σ₁₂] F}
(h : ∀ x, (⨆ i, ↑∥g i x∥₊) < ∞) :
(⨆ i, ↑∥g i∥₊) < ∞ :=
begin
have h' : ∀ x : E, ∃ C : ℝ, ∀ i : ι, ∥g i x∥ ≤ C,
{ intro x,
rcases lt_iff_exists_coe.mp (h x) with ⟨p, hp₁, _⟩,
refine ⟨p, (λ i, _)⟩,
exact_mod_cast
calc (∥g i x∥₊ : ℝ≥0∞) ≤ ⨆ j, ∥g j x∥₊ : le_supr _ i
... = p : hp₁ },
cases banach_steinhaus h' with C' hC',
refine (supr_le $ λ i, _).trans_lt (@coe_lt_top C'.to_nnreal),
rw ←norm_to_nnreal,
exact coe_mono (real.to_nnreal_le_to_nnreal $ hC' i),
end
open_locale topological_space
open filter
/-- Given a *sequence* of continuous linear maps which converges pointwise and for which the
domain is complete, the Banach-Steinhaus theorem is used to guarantee that the limit map
is a *continuous* linear map as well. -/
def continuous_linear_map_of_tendsto [complete_space E] [t2_space F]
(g : ℕ → E →SL[σ₁₂] F) {f : E → F} (h : tendsto (λ n x, g n x) at_top (𝓝 f)) :
E →SL[σ₁₂] F :=
{ to_fun := f,
map_add' := (linear_map_of_tendsto _ _ h).map_add',
map_smul' := (linear_map_of_tendsto _ _ h).map_smul',
cont :=
begin
/- show that the maps are pointwise bounded and apply `banach_steinhaus`-/
have h_point_bdd : ∀ x : E, ∃ C : ℝ, ∀ n : ℕ, ∥g n x∥ ≤ C,
{ intro x,
rcases cauchy_seq_bdd (tendsto_pi_nhds.mp h x).cauchy_seq with ⟨C, C_pos, hC⟩,
refine ⟨C + ∥g 0 x∥, (λ n, _)⟩,
simp_rw dist_eq_norm at hC,
calc ∥g n x∥ ≤ ∥g 0 x∥ + ∥g n x - g 0 x∥ : norm_le_insert' _ _
... ≤ C + ∥g 0 x∥ : by linarith [hC n 0] },
cases banach_steinhaus h_point_bdd with C' hC',
/- show the uniform bound from `banach_steinhaus` is a norm bound of the limit map
by allowing "an `ε` of room." -/
refine linear_map.continuous_of_bound (linear_map_of_tendsto _ _ h) C'
(λ x, le_of_forall_pos_lt_add (λ ε ε_pos, _)),
cases metric.tendsto_at_top.mp (tendsto_pi_nhds.mp h x) ε ε_pos with n hn,
have lt_ε : ∥g n x - f x∥ < ε, by {rw ←dist_eq_norm, exact hn n (le_refl n)},
calc ∥f x∥ ≤ ∥g n x∥ + ∥g n x - f x∥ : norm_le_insert _ _
... < ∥g n∥ * ∥x∥ + ε : by linarith [lt_ε, (g n).le_op_norm x]
... ≤ C' * ∥x∥ + ε : by nlinarith [hC' n, norm_nonneg x],
end }
|
80a3ccf8b7a7752cb55de0311d352fb711e0cd62 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/compiler/foreign/Main/S.lean | 6e5e6c0555f459e76b425f511f43a5c579151e20 | [
"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 | 610 | lean | constant SPointed : PointedType
def S : Type := SPointed.type
instance : Inhabited S := ⟨SPointed.val⟩
@[extern "lean_mk_S"] constant mkS (x y : UInt32) (s : @& String) : S
@[extern "lean_S_add_x_y"] constant S.addXY (s : @& S) : UInt32
@[extern "lean_S_string"] constant S.string (s : @& S) : String
-- The following 3 externs have side effects. Thus, we put them in IO.
@[extern "lean_S_global_append"] constant appendToGlobalS (str : @& String) : IO Unit
@[extern "lean_S_global_string"] constant getGlobalString : IO String
@[extern "lean_S_update_global"] constant updateGlobalS (s : @& S) : IO Unit
|
06700f5b4dfbfca68f25d16d30428693bee70d3f | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/analysis/normed_space/linear_isometry.lean | cf3fe8321c66c14ce3ddf067b0ff3c0f416a848f | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,963 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.normed_space.basic
/-!
# Linear isometries
In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric
embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear
isometric equivalence between `E` and `F`.
We also prove some trivial lemmas and provide convenience constructors.
Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the
theory for `semi_normed_space` and we specialize to `normed_space` when needed.
-/
open function set
variables {R E F G G' E₁ : Type*} [semiring R]
[semi_normed_group E] [semi_normed_group F] [semi_normed_group G] [semi_normed_group G']
[module R E] [module R F] [module R G] [module R G']
[normed_group E₁] [module R E₁]
/-- An `R`-linear isometric embedding of one normed `R`-module into another. -/
structure linear_isometry (R E F : Type*) [semiring R] [semi_normed_group E]
[semi_normed_group F] [module R E] [module R F] extends E →ₗ[R] F :=
(norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥)
notation E ` →ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry R E F
namespace linear_isometry
/-- We use `f₁` when we need the domain to be a `normed_space`. -/
variables (f : E →ₗᵢ[R] F) (f₁ : E₁ →ₗᵢ[R] F)
instance : has_coe_to_fun (E →ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl
lemma to_linear_map_injective : injective (to_linear_map : (E →ₗᵢ[R] F) → (E →ₗ[R] F))
| ⟨f, _⟩ ⟨g, _⟩ rfl := rfl
lemma coe_fn_injective : injective (λ (f : E →ₗᵢ[R] F) (x : E), f x) :=
linear_map.coe_injective.comp to_linear_map_injective
@[ext] lemma ext {f g : E →ₗᵢ[R] F} (h : ∀ x, f x = g x) : f = g :=
coe_fn_injective $ funext h
@[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero
@[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y
@[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y
@[simp] lemma map_smul (c : R) (x : E) : f (c • x) = c • f x := f.to_linear_map.map_smul c x
@[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x
@[simp] lemma nnnorm_map (x : E) : nnnorm (f x) = nnnorm x := nnreal.eq $ f.norm_map x
protected lemma isometry : isometry f :=
f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map
@[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y
@[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y
protected lemma injective : injective f₁ := f₁.isometry.injective
@[simp] lemma map_eq_iff {x y : E₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff
lemma map_ne {x y : E₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h
protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz
@[continuity] protected lemma continuous : continuous f := f.isometry.continuous
lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s :=
f.isometry.ediam_image s
lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) :=
f.isometry.ediam_range
lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s :=
f.isometry.diam_image s
lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) :=
f.isometry.diam_range
/-- Interpret a linear isometry as a continuous linear map. -/
def to_continuous_linear_map : E →L[R] F := ⟨f.to_linear_map, f.continuous⟩
@[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} :
continuous (f ∘ g) ↔ continuous g :=
f.isometry.comp_continuous_iff
/-- The identity linear isometry. -/
def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩
@[simp] lemma coe_id : ⇑(id : E →ₗᵢ[R] E) = _root_.id := rfl
@[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl
@[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl
instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩
/-- Composition of linear isometries. -/
def comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : E →ₗᵢ[R] G :=
⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩
@[simp] lemma coe_comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) :
⇑(g.comp f) = g ∘ f :=
rfl
@[simp] lemma id_comp : (id : F →ₗᵢ[R] F).comp f = f := ext $ λ x, rfl
@[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl
lemma comp_assoc (f : G →ₗᵢ[R] G') (g : F →ₗᵢ[R] G) (h : E →ₗᵢ[R] F) :
(f.comp g).comp h = f.comp (g.comp h) :=
rfl
instance : monoid (E →ₗᵢ[R] E) :=
{ one := id,
mul := comp,
mul_assoc := comp_assoc,
one_mul := id_comp,
mul_one := comp_id }
@[simp] lemma coe_one : ⇑(1 : E →ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl
end linear_isometry
namespace submodule
variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E)
/-- `submodule.subtype` as a `linear_isometry`. -/
def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩
@[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl
@[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl
/-- `submodule.subtype` as a `continuous_linear_map`. -/
def subtypeL : p →L[R'] E := p.subtypeₗᵢ.to_continuous_linear_map
@[simp] lemma coe_subtypeL : (p.subtypeL : p →ₗ[R'] E) = p.subtype := rfl
@[simp] lemma coe_subtypeL' : ⇑p.subtypeL = p.subtype := rfl
@[simp] lemma range_subtypeL : p.subtypeL.range = p :=
range_subtype _
@[simp] lemma ker_subtypeL : p.subtypeL.ker = ⊥ :=
ker_subtype _
end submodule
/-- A linear isometric equivalence between two normed vector spaces. -/
structure linear_isometry_equiv (R E F : Type*) [semiring R] [semi_normed_group E]
[semi_normed_group F] [module R E] [module R F] extends E ≃ₗ[R] F :=
(norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥)
notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry_equiv R E F
namespace linear_isometry_equiv
variables (e : E ≃ₗᵢ[R] F)
instance : has_coe_to_fun (E ≃ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_mk (e : E ≃ₗ[R] F) (he : ∀ x, ∥e x∥ = ∥x∥) :
⇑(mk e he) = e :=
rfl
@[simp] lemma coe_to_linear_equiv (e : E ≃ₗᵢ[R] F) : ⇑e.to_linear_equiv = e := rfl
lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₗᵢ[R] F) → (E ≃ₗ[R] F))
| ⟨e, _⟩ ⟨_, _⟩ rfl := rfl
@[ext] lemma ext {e e' : E ≃ₗᵢ[R] F} (h : ∀ x, e x = e' x) : e = e' :=
to_linear_equiv_injective $ linear_equiv.ext h
/-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities:
`∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/
def of_bounds (e : E ≃ₗ[R] F) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) : E ≃ₗᵢ[R] F :=
⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩
@[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x
/-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/
def to_linear_isometry : E →ₗᵢ[R] F := ⟨e.1, e.2⟩
@[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl
protected lemma isometry : isometry e := e.to_linear_isometry.isometry
/-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/
def to_isometric : E ≃ᵢ F := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩
@[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl
lemma range_eq_univ (e : E ≃ₗᵢ[R] F) : set.range e = set.univ :=
by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, }
/-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/
def to_homeomorph : E ≃ₜ F := e.to_isometric.to_homeomorph
@[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl
protected lemma continuous : continuous e := e.isometry.continuous
protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at
protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on
protected lemma continuous_within_at {s x} : continuous_within_at e s x :=
e.continuous.continuous_within_at
/-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/
def to_continuous_linear_equiv : E ≃L[R] F :=
{ .. e.to_linear_isometry.to_continuous_linear_map,
.. e.to_homeomorph }
@[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl
variables (R E)
/-- Identity map as a `linear_isometry_equiv`. -/
def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩
variables {R E}
instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩
@[simp] lemma coe_refl : ⇑(refl R E) = id := rfl
/-- The inverse `linear_isometry_equiv`. -/
def symm : F ≃ₗᵢ[R] E :=
⟨e.to_linear_equiv.symm,
λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩
@[simp] lemma apply_symm_apply (x : F) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x
@[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff
@[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl
@[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl
@[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl
/-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/
def trans (e' : F ≃ₗᵢ[R] G) : E ≃ₗᵢ[R] G :=
⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩
@[simp] lemma coe_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
@[simp] lemma trans_refl : e.trans (refl R F) = e := ext $ λ x, rfl
@[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl
@[simp] lemma trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply
@[simp] lemma symm_trans : e.symm.trans e = refl R F := ext e.apply_symm_apply
@[simp] lemma coe_symm_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) :
⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm :=
rfl
lemma trans_assoc (eEF : E ≃ₗᵢ[R] F) (eFG : F ≃ₗᵢ[R] G) (eGG' : G ≃ₗᵢ[R] G') :
eEF.trans (eFG.trans eGG') = (eEF.trans eFG).trans eGG' :=
rfl
instance : group (E ≃ₗᵢ[R] E) :=
{ mul := λ e₁ e₂, e₂.trans e₁,
one := refl _ _,
inv := symm,
one_mul := trans_refl,
mul_one := refl_trans,
mul_assoc := λ _ _ _, trans_assoc _ _ _,
mul_left_inv := trans_symm }
@[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl
@[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl
/-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/
instance : has_coe_t (E ≃ₗᵢ[R] F) (E ≃L[R] F) :=
⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩
instance : has_coe_t (E ≃ₗᵢ[R] F) (E →L[R] F) := ⟨λ e, ↑(e : E ≃L[R] F)⟩
@[simp] lemma coe_coe : ⇑(e : E ≃L[R] F) = e := rfl
@[simp] lemma coe_coe' : ((e : E ≃L[R] F) : E →L[R] F) = e := rfl
@[simp] lemma coe_coe'' : ⇑(e : E →L[R] F) = e := rfl
@[simp] lemma map_zero : e 0 = 0 := e.1.map_zero
@[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y
@[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y
@[simp] lemma map_smul (c : R) (x : E) : e (c • x) = c • e x := e.1.map_smul c x
@[simp] lemma nnnorm_map (x : E) : nnnorm (e x) = nnnorm x := e.to_linear_isometry.nnnorm_map x
@[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y :=
e.to_linear_isometry.dist_map x y
@[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y :=
e.to_linear_isometry.edist_map x y
protected lemma bijective : bijective e := e.1.bijective
protected lemma injective : injective e := e.1.injective
protected lemma surjective : surjective e := e.1.surjective
@[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff
lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h
protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz
@[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s :=
e.isometry.ediam_image s
@[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s :=
e.isometry.diam_image s
variables {α : Type*} [topological_space α]
@[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.isometry.comp_continuous_on_iff
@[simp] lemma comp_continuous_iff {f : α → E} :
continuous (e ∘ f) ↔ continuous f :=
e.isometry.comp_continuous_iff
variables (R)
/-- The negation operation on a normed space `E`, considered as a linear isometry equivalence. -/
def neg : E ≃ₗᵢ[R] E :=
{ norm_map' := norm_neg,
.. linear_equiv.neg R }
variables {R}
@[simp] lemma coe_neg : (neg R : E → E) = λ x, -x := rfl
@[simp] lemma symm_neg : (neg R : E ≃ₗᵢ[R] E).symm = neg R := rfl
end linear_isometry_equiv
|
a5d9168145564dead2f32355da5a56ac3e6a0447 | 46125763b4dbf50619e8846a1371029346f4c3db | /src/topology/metric_space/contracting.lean | 447365c5fda6a27b954167a0e4dff06bcdc9e582 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 5,165 | lean | /-
Copyright (c) 2019 Rohan Mitta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov
-/
import topology.metric_space.lipschitz analysis.specific_limits
/-!
# Contracting maps
A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*.
In this file we prove the Banach fixed point theorem, some explicit estimates on the rate
of convergence, and some properties of the map sending a contracting map to its fixed point.
-/
universes u v
open_locale nnreal topological_space
open filter
variables {α : Type u} {ι : Sort v}
/-- If the iterates `f^[n] x₀` converge to `x` and `f` is continuous at `x`,
then `x` is a fixed point for `f`. -/
lemma fixed_point_of_tendsto_iterate [topological_space α] [t2_space α] {f : α → α} {x : α}
(hf : continuous_at f x) (hx : ∃ x₀ : α, tendsto (λ n, f^[n] x₀) at_top (𝓝 x)) :
f x = x :=
begin
rcases hx with ⟨x₀, hx⟩,
refine tendsto_nhds_unique at_top_ne_bot _ hx,
rw [← tendsto_add_at_top_iff_nat 1, funext (assume n, nat.iterate_succ' f n x₀)],
exact tendsto.comp hf hx
end
/-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/
def contracting_with [emetric_space α] (K : ℝ≥0) (f : α → α) :=
(K < 1) ∧ lipschitz_with K f
namespace contracting_with
variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f)
include hf
lemma to_lipschitz_with : lipschitz_with K f := hf.2
lemma dist_le_mul (x y : α) : dist (f x) (f y) ≤ K * dist x y :=
hf.to_lipschitz_with.dist_le_mul x y
lemma one_sub_K_pos : (0:ℝ) < 1 - K := sub_pos_of_lt hf.1
lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) :=
suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y,
by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add],
calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _
... ≤ dist x (f x) + dist y (f y) + K * dist x y :
add_le_add_left (hf.dist_le_mul _ _) _
lemma dist_le_of_fixed_point (x) {y} (hy : f y = y) :
dist x y ≤ (dist x (f x)) / (1 - K) :=
by simpa only [hy, dist_self, add_zero] using hf.dist_inequality x y
theorem fixed_point_unique' {x y} (hx : f x = x) (hy : f y = y) : x = y :=
dist_le_zero.1 $ by simpa only [hx, dist_self, add_zero, zero_div]
using hf.dist_le_of_fixed_point x hy
/-- Banach fixed-point theorem, contraction mapping theorem -/
theorem exists_fixed_point [hα : nonempty α] [complete_space α] : ∃x, f x = x :=
let ⟨x₀⟩ := hα in
have cauchy_seq (λ n, f^[n] x₀),
from cauchy_seq_of_le_geometric K (dist x₀ (f x₀)) hf.1 $
hf.to_lipschitz_with.dist_iterate_succ_le_geometric x₀,
let ⟨x, hx⟩ := cauchy_seq_tendsto_of_complete this in
⟨x, fixed_point_of_tendsto_iterate (hf.to_lipschitz_with.continuous.tendsto x) ⟨x₀, hx⟩⟩
/-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly
`C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/
lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α)
{x y} (hx : f x = x) (hy : g y = y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist x y ≤ C / (1 - K) :=
calc dist x y = dist y x : dist_comm x y
... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx
... = (dist (f y) (g y)) / (1 - K) : by rw [hy, dist_comm]
... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y)
noncomputable theory
variables [inhabited α] [complete_space α]
/-- The unique fixed point of a contracting map. -/
protected def fixed_point : α := classical.some hf.exists_fixed_point
/-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/
lemma fixed_point_is_fixed : f hf.fixed_point = hf.fixed_point :=
classical.some_spec hf.exists_fixed_point
lemma fixed_point_unique {x} (hx : f x = x) : x = hf.fixed_point :=
hf.fixed_point_unique' hx hf.fixed_point_is_fixed
lemma dist_fixed_point_le (x) : dist x hf.fixed_point ≤ (dist x (f x)) / (1 - K) :=
hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed
/-- Aposteriori estimates on the convergence of iterates to the fixed point. -/
lemma aposteriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) hf.fixed_point ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) :=
by { rw [nat.iterate_succ'], apply hf.dist_fixed_point_le }
lemma apriori_dist_iterate_fixed_point_le (x n) :
dist (f^[n] x) hf.fixed_point ≤ (dist x (f x)) * K^n / (1 - K) :=
le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $
(div_le_div_right hf.one_sub_K_pos).2 $
hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n
lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g)
{C} (hfg : ∀ z, dist (f z) (g z) ≤ C) :
dist hf.fixed_point hg.fixed_point ≤ C / (1 - K) :=
hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed hg.fixed_point_is_fixed hfg
end contracting_with
|
7c5e3539971974e51a2ad65530808904c776da5e | 952248371e69ccae722eb20bfe6815d8641554a8 | /test/trace.lean | 8978561372deb94f48b9c86c8447b28ff2d71fd2 | [] | no_license | robertylewis/lean_polya | 5fd079031bf7114449d58d68ccd8c3bed9bcbc97 | 1da14d60a55ad6cd8af8017b1b64990fccb66ab7 | refs/heads/master | 1,647,212,226,179 | 1,558,108,354,000 | 1,558,108,354,000 | 89,933,264 | 1 | 2 | null | 1,560,964,118,000 | 1,493,650,551,000 | Lean | UTF-8 | Lean | false | false | 1,055 | lean | import control proof_trace
open polya tactic expr
variables u v w x y z : ℚ
meta def polya_on_hyps' (hys : list name) (rct : bool := tt) : tactic unit :=
do exps ← hys.mmap get_local,
bb ← add_proof_to_blackboard blackboard.mk_empty `(rat_one_gt_zero),
bb ← add_proofs_to_blackboard bb exps,
let pb := polya_bundle.default.set_blackboard bb,
let (n, pb) := pb.cycle 0,
trace ("number of cycles:", n),
trace ("contr found", pb.contr_found),
if bnot pb.contr_found then /-bb.trace >>-/ fail "polya failed, no contradiction found" else do
pb.bb.contr.sketch >>= proof_sketch.trace,
if rct then pb.bb.contr.reconstruct >>= apply >> skip
else skip
example (h1 : x > 0) (h2 : x < 1*1) (h3 : rat.pow (1*1 + (-1)*x) (-1) ≤ 1*(rat.pow (1*1 + (-1)*rat.pow x 2) (-1))) : false :=
by
polya_on_hyps' [`h1, `h2, `h3]
example (h1 : u > 0) (h2 : u < 1*v) (h3 : z > 0) (h4 : 1*z + 1*1 < 1*w) (h5 : rat.pow (1*u + 1*v + 1*z) 3 ≥ 1* rat.pow (1*u + 1*v + 1*w + 1*1) 5) : false :=
by polya_on_hyps' [`h1, `h2, `h3, `h4, `h5]
|
c09d16778080ed1dcafa9b823eac3c5a2406d2a0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/combinatorics/composition.lean | b39773ebcc5cb09321bd29ce007dfc00cfb0a73e | [
"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 | 36,392 | 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 data.finset.sort
import algebra.big_operators.order
import algebra.big_operators.fin
/-!
# Compositions
A composition of a natural number `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum
of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into
non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks.
This notion is closely related to that of a partition of `n`, but in a composition of `n` the
order of the `iⱼ`s matters.
We implement two different structures covering these two viewpoints on compositions. The first
one, made of a list of positive integers summing to `n`, is the main one and is called
`composition n`. The second one is useful for combinatorial arguments (for instance to show that
the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}`
containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost
points of each block. The main API is built on `composition n`, and we provide an equivalence
between the two types.
## Main functions
* `c : composition n` is a structure, made of a list of integers which are all positive and
add up to `n`.
* `composition_card` states that the cardinality of `composition n` is exactly
`2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which
is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is
nat subtraction).
Let `c : composition n` be a composition of `n`. Then
* `c.blocks` is the list of blocks in `c`.
* `c.length` is the number of blocks in the composition.
* `c.blocks_fun : fin c.length → ℕ` is the realization of `c.blocks` as a function on
`fin c.length`. This is the main object when using compositions to understand the composition of
analytic functions.
* `c.size_up_to : ℕ → ℕ` is the sum of the size of the blocks up to `i`.;
* `c.embedding i : fin (c.blocks_fun i) → fin n` is the increasing embedding of the `i`-th block in
`fin n`;
* `c.index j`, for `j : fin n`, is the index of the block containing `j`.
* `composition.ones n` is the composition of `n` made of ones, i.e., `[1, ..., 1]`.
* `composition.single n (hn : 0 < n)` is the composition of `n` made of a single block of size `n`.
Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition
of `n`.
* `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the
blocks of `c`.
* `join_split_wrt_composition` states that splitting a list and then joining it gives back the
original list.
* `split_wrt_composition_join` states that joining a list of lists, and then splitting it back
according to the right composition, gives back the original list of lists.
We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`.
`c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries`
and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not
make sense in the edge case `n = 0`, while the previous description works in all cases).
The elements of this set (other than `n`) correspond to leftmost points of blocks.
Thus, there is an equiv between `composition n` and `composition_as_set n`. We
only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able
to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv
between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n`
from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that
`composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)`
(see `composition_as_set_card` and `composition_card`).
## Implementation details
The main motivation for this structure and its API is in the construction of the composition of
formal multilinear series, and the proof that the composition of analytic functions is analytic.
The representation of a composition as a list is very handy as lists are very flexible and already
have a well-developed API.
## Tags
Composition, partition
## References
<https://en.wikipedia.org/wiki/Composition_(combinatorics)>
-/
open list
open_locale big_operators
variable {n : ℕ}
/-- A composition of `n` is a list of positive integers summing to `n`. -/
@[ext] structure composition (n : ℕ) :=
(blocks : list ℕ)
(blocks_pos : ∀ {i}, i ∈ blocks → 0 < i)
(blocks_sum : blocks.sum = n)
/-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of
consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding
a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and
get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure
`composition_as_set n`. -/
@[ext] structure composition_as_set (n : ℕ) :=
(boundaries : finset (fin n.succ))
(zero_mem : (0 : fin n.succ) ∈ boundaries)
(last_mem : fin.last n ∈ boundaries)
instance {n : ℕ} : inhabited (composition_as_set n) :=
⟨⟨finset.univ, finset.mem_univ _, finset.mem_univ _⟩⟩
/-!
### Compositions
A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of
positive integers.
-/
namespace composition
variables (c : composition n)
instance (n : ℕ) : has_to_string (composition n) :=
⟨λ c, to_string c.blocks⟩
/-- The length of a composition, i.e., the number of blocks in the composition. -/
@[reducible] def length : ℕ := c.blocks.length
lemma blocks_length : c.blocks.length = c.length := rfl
/-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic
functions using compositions, this is the main player. -/
def blocks_fun : fin c.length → ℕ := λ i, nth_le c.blocks i i.2
lemma of_fn_blocks_fun : of_fn c.blocks_fun = c.blocks :=
of_fn_nth_le _
lemma sum_blocks_fun : ∑ i, c.blocks_fun i = n :=
by conv_rhs { rw [← c.blocks_sum, ← of_fn_blocks_fun, sum_of_fn] }
lemma blocks_fun_mem_blocks (i : fin c.length) : c.blocks_fun i ∈ c.blocks :=
nth_le_mem _ _ _
@[simp] lemma one_le_blocks {i : ℕ} (h : i ∈ c.blocks) : 1 ≤ i :=
c.blocks_pos h
@[simp] lemma one_le_blocks' {i : ℕ} (h : i < c.length) : 1 ≤ nth_le c.blocks i h:=
c.one_le_blocks (nth_le_mem (blocks c) i h)
@[simp] lemma blocks_pos' (i : ℕ) (h : i < c.length) : 0 < nth_le c.blocks i h:=
c.one_le_blocks' h
lemma one_le_blocks_fun (i : fin c.length) : 1 ≤ c.blocks_fun i :=
c.one_le_blocks (c.blocks_fun_mem_blocks i)
lemma length_le : c.length ≤ n :=
begin
conv_rhs { rw ← c.blocks_sum },
exact length_le_sum_of_one_le _ (λ i hi, c.one_le_blocks hi)
end
lemma length_pos_of_pos (h : 0 < n) : 0 < c.length :=
begin
apply length_pos_of_sum_pos,
convert h,
exact c.blocks_sum
end
/-- The sum of the sizes of the blocks in a composition up to `i`. -/
def size_up_to (i : ℕ) : ℕ := (c.blocks.take i).sum
@[simp] lemma size_up_to_zero : c.size_up_to 0 = 0 := by simp [size_up_to]
lemma size_up_to_of_length_le (i : ℕ) (h : c.length ≤ i) : c.size_up_to i = n :=
begin
dsimp [size_up_to],
convert c.blocks_sum,
exact take_all_of_le h
end
@[simp] lemma size_up_to_length : c.size_up_to c.length = n :=
c.size_up_to_of_length_le c.length le_rfl
lemma size_up_to_le (i : ℕ) : c.size_up_to i ≤ n :=
begin
conv_rhs { rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] },
exact nat.le_add_right _ _
end
lemma size_up_to_succ {i : ℕ} (h : i < c.length) :
c.size_up_to (i+1) = c.size_up_to i + c.blocks.nth_le i h :=
by { simp only [size_up_to], rw sum_take_succ _ _ h }
lemma size_up_to_succ' (i : fin c.length) :
c.size_up_to ((i : ℕ) + 1) = c.size_up_to i + c.blocks_fun i :=
c.size_up_to_succ i.2
lemma size_up_to_strict_mono {i : ℕ} (h : i < c.length) : c.size_up_to i < c.size_up_to (i+1) :=
by { rw c.size_up_to_succ h, simp }
lemma monotone_size_up_to : monotone c.size_up_to :=
monotone_sum_take _
/-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include
a virtual point at the right of the last block, to make for a nice equiv with
`composition_as_set n`. -/
def boundary : fin (c.length + 1) ↪o fin (n+1) :=
order_embedding.of_strict_mono (λ i, ⟨c.size_up_to i, nat.lt_succ_of_le (c.size_up_to_le i)⟩) $
fin.strict_mono_iff_lt_succ.2 $ λ ⟨i, hi⟩, c.size_up_to_strict_mono hi
@[simp] lemma boundary_zero : c.boundary 0 = 0 :=
by simp [boundary, fin.ext_iff]
@[simp] lemma boundary_last : c.boundary (fin.last c.length) = fin.last n :=
by simp [boundary, fin.ext_iff]
/-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include
a virtual point at the right of the last block, to make for a nice equiv with
`composition_as_set n`. -/
def boundaries : finset (fin (n+1)) :=
finset.univ.map c.boundary.to_embedding
lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 :=
by simp [boundaries]
/-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost
point of each block, and adding a virtual point at the right of the last block. -/
def to_composition_as_set : composition_as_set n :=
{ boundaries := c.boundaries,
zero_mem := begin
simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map],
exact ⟨0, rfl⟩,
end,
last_mem := begin
simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map],
exact ⟨fin.last c.length, c.boundary_last⟩,
end }
/-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is
exactly `c.boundary`. -/
lemma order_emb_of_fin_boundaries :
c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length = c.boundary :=
begin
refine (finset.order_emb_of_fin_unique' _ _).symm,
exact λ i, (finset.mem_map' _).2 (finset.mem_univ _)
end
/-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into
`fin n` at the relevant position. -/
def embedding (i : fin c.length) : fin (c.blocks_fun i) ↪o fin n :=
(fin.nat_add $ c.size_up_to i).trans $ fin.cast_le $
calc c.size_up_to i + c.blocks_fun i = c.size_up_to (i + 1) : (c.size_up_to_succ _).symm
... ≤ c.size_up_to c.length : monotone_sum_take _ i.2
... = n : c.size_up_to_length
@[simp] lemma coe_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) :
(c.embedding i j : ℕ) = c.size_up_to i + j := rfl
/--
`index_exists` asserts there is some `i` with `j < c.size_up_to (i+1)`.
In the next definition `index` we use `nat.find` to produce the minimal such index.
-/
lemma index_exists {j : ℕ} (h : j < n) :
∃ i : ℕ, j < c.size_up_to i.succ ∧ i < c.length :=
begin
have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h,
have : 0 < c.blocks.sum, by rwa [← c.blocks_sum] at n_pos,
have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this,
refine ⟨c.length.pred, _, nat.pred_lt (ne_of_gt length_pos)⟩,
have : c.length.pred.succ = c.length := nat.succ_pred_eq_of_pos length_pos,
simp [this, h]
end
/-- `c.index j` is the index of the block in the composition `c` containing `j`. -/
def index (j : fin n) : fin c.length :=
⟨nat.find (c.index_exists j.2), (nat.find_spec (c.index_exists j.2)).2⟩
lemma lt_size_up_to_index_succ (j : fin n) : (j : ℕ) < c.size_up_to (c.index j).succ :=
(nat.find_spec (c.index_exists j.2)).1
lemma size_up_to_index_le (j : fin n) : c.size_up_to (c.index j) ≤ j :=
begin
by_contradiction H,
set i := c.index j with hi,
push_neg at H,
have i_pos : (0 : ℕ) < i,
{ by_contra' i_pos,
revert H, simp [nonpos_iff_eq_zero.1 i_pos, c.size_up_to_zero] },
let i₁ := (i : ℕ).pred,
have i₁_lt_i : i₁ < i := nat.pred_lt (ne_of_gt i_pos),
have i₁_succ : i₁.succ = i := nat.succ_pred_eq_of_pos i_pos,
have := nat.find_min (c.index_exists j.2) i₁_lt_i,
simp [lt_trans i₁_lt_i (c.index j).2, i₁_succ] at this,
exact nat.lt_le_antisymm H this
end
/-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with
`fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/
def inv_embedding (j : fin n) : fin (c.blocks_fun (c.index j)) :=
⟨j - c.size_up_to (c.index j),
begin
rw [tsub_lt_iff_right, add_comm, ← size_up_to_succ'],
{ exact lt_size_up_to_index_succ _ _ },
{ exact size_up_to_index_le _ _ }
end⟩
@[simp] lemma coe_inv_embedding (j : fin n) :
(c.inv_embedding j : ℕ) = j - c.size_up_to (c.index j) := rfl
lemma embedding_comp_inv (j : fin n) :
c.embedding (c.index j) (c.inv_embedding j) = j :=
begin
rw fin.ext_iff,
apply add_tsub_cancel_of_le (c.size_up_to_index_le j),
end
lemma mem_range_embedding_iff {j : fin n} {i : fin c.length} :
j ∈ set.range (c.embedding i) ↔
c.size_up_to i ≤ j ∧ (j : ℕ) < c.size_up_to (i : ℕ).succ :=
begin
split,
{ assume h,
rcases set.mem_range.2 h with ⟨k, hk⟩,
rw fin.ext_iff at hk,
change c.size_up_to i + k = (j : ℕ) at hk,
rw ← hk,
simp [size_up_to_succ', k.is_lt] },
{ assume h,
apply set.mem_range.2,
refine ⟨⟨j - c.size_up_to i, _⟩, _⟩,
{ rw [tsub_lt_iff_left, ← size_up_to_succ'],
{ exact h.2 },
{ exact h.1 } },
{ rw fin.ext_iff,
exact add_tsub_cancel_of_le h.1 } }
end
/-- The embeddings of different blocks of a composition are disjoint. -/
lemma disjoint_range {i₁ i₂ : fin c.length} (h : i₁ ≠ i₂) :
disjoint (set.range (c.embedding i₁)) (set.range (c.embedding i₂)) :=
begin
classical,
wlog h' : i₁ ≤ i₂ using i₁ i₂,
swap, exact (this h.symm).symm,
by_contradiction d,
obtain ⟨x, hx₁, hx₂⟩ :
∃ x : fin n, (x ∈ set.range (c.embedding i₁) ∧ x ∈ set.range (c.embedding i₂)) :=
set.not_disjoint_iff.1 d,
have : i₁ < i₂ := lt_of_le_of_ne h' h,
have A : (i₁ : ℕ).succ ≤ i₂ := nat.succ_le_of_lt this,
apply lt_irrefl (x : ℕ),
calc (x : ℕ) < c.size_up_to (i₁ : ℕ).succ : (c.mem_range_embedding_iff.1 hx₁).2
... ≤ c.size_up_to (i₂ : ℕ) : monotone_sum_take _ A
... ≤ x : (c.mem_range_embedding_iff.1 hx₂).1
end
lemma mem_range_embedding (j : fin n) :
j ∈ set.range (c.embedding (c.index j)) :=
begin
have : c.embedding (c.index j) (c.inv_embedding j)
∈ set.range (c.embedding (c.index j)) := set.mem_range_self _,
rwa c.embedding_comp_inv j at this
end
lemma mem_range_embedding_iff' {j : fin n} {i : fin c.length} :
j ∈ set.range (c.embedding i) ↔ i = c.index j :=
begin
split,
{ rw ← not_imp_not,
assume h,
exact set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) },
{ assume h,
rw h,
exact c.mem_range_embedding j }
end
lemma index_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) :
c.index (c.embedding i j) = i :=
begin
symmetry,
rw ← mem_range_embedding_iff',
apply set.mem_range_self
end
lemma inv_embedding_comp (i : fin c.length) (j : fin (c.blocks_fun i)) :
(c.inv_embedding (c.embedding i j) : ℕ) = j :=
by simp_rw [coe_inv_embedding, index_embedding, coe_embedding, add_tsub_cancel_left]
/-- Equivalence between the disjoint union of the blocks (each of them seen as
`fin (c.blocks_fun i)`) with `fin n`. -/
def blocks_fin_equiv : (Σ i : fin c.length, fin (c.blocks_fun i)) ≃ fin n :=
{ to_fun := λ x, c.embedding x.1 x.2,
inv_fun := λ j, ⟨c.index j, c.inv_embedding j⟩,
left_inv := λ x, begin
rcases x with ⟨i, y⟩,
dsimp,
congr, { exact c.index_embedding _ _ },
rw fin.heq_ext_iff,
{ exact c.inv_embedding_comp _ _ },
{ rw c.index_embedding }
end,
right_inv := λ j, c.embedding_comp_inv j }
lemma blocks_fun_congr {n₁ n₂ : ℕ} (c₁ : composition n₁) (c₂ : composition n₂)
(i₁ : fin c₁.length) (i₂ : fin c₂.length) (hn : n₁ = n₂)
(hc : c₁.blocks = c₂.blocks) (hi : (i₁ : ℕ) = i₂) :
c₁.blocks_fun i₁ = c₂.blocks_fun i₂ :=
by { cases hn, rw ← composition.ext_iff at hc, cases hc, congr, rwa fin.ext_iff }
/-- Two compositions (possibly of different integers) coincide if and only if they have the
same sequence of blocks. -/
lemma sigma_eq_iff_blocks_eq {c : Σ n, composition n} {c' : Σ n, composition n} :
c = c' ↔ c.2.blocks = c'.2.blocks :=
begin
refine ⟨λ H, by rw H, λ H, _⟩,
rcases c with ⟨n, c⟩,
rcases c' with ⟨n', c'⟩,
have : n = n', by { rw [← c.blocks_sum, ← c'.blocks_sum, H] },
induction this,
simp only [true_and, eq_self_iff_true, heq_iff_eq],
ext1,
exact H
end
/-! ### The composition `composition.ones` -/
/-- The composition made of blocks all of size `1`. -/
def ones (n : ℕ) : composition n :=
⟨repeat (1 : ℕ) n, λ i hi, by simp [list.eq_of_mem_repeat hi], by simp⟩
instance {n : ℕ} : inhabited (composition n) :=
⟨composition.ones n⟩
@[simp] lemma ones_length (n : ℕ) : (ones n).length = n :=
list.length_repeat 1 n
@[simp] lemma ones_blocks (n : ℕ) : (ones n).blocks = repeat (1 : ℕ) n := rfl
@[simp] lemma ones_blocks_fun (n : ℕ) (i : fin (ones n).length) :
(ones n).blocks_fun i = 1 :=
by simp [blocks_fun, ones, blocks, i.2]
@[simp] lemma ones_size_up_to (n : ℕ) (i : ℕ) : (ones n).size_up_to i = min i n :=
by simp [size_up_to, ones_blocks, take_repeat]
@[simp] lemma ones_embedding (i : fin (ones n).length) (h : 0 < (ones n).blocks_fun i) :
(ones n).embedding i ⟨0, h⟩ = ⟨i, lt_of_lt_of_le i.2 (ones n).length_le⟩ :=
by { ext, simpa using i.2.le }
lemma eq_ones_iff {c : composition n} :
c = ones n ↔ ∀ i ∈ c.blocks, i = 1 :=
begin
split,
{ rintro rfl,
exact λ i, eq_of_mem_repeat },
{ assume H,
ext1,
have A : c.blocks = repeat 1 c.blocks.length := eq_repeat_of_mem H,
have : c.blocks.length = n, by { conv_rhs { rw [← c.blocks_sum, A] }, simp },
rw [A, this, ones_blocks] },
end
lemma ne_ones_iff {c : composition n} :
c ≠ ones n ↔ ∃ i ∈ c.blocks, 1 < i :=
begin
refine (not_congr eq_ones_iff).trans _,
have : ∀ j ∈ c.blocks, j = 1 ↔ j ≤ 1 := λ j hj, by simp [le_antisymm_iff, c.one_le_blocks hj],
simp [this] {contextual := tt}
end
lemma eq_ones_iff_length {c : composition n} :
c = ones n ↔ c.length = n :=
begin
split,
{ rintro rfl,
exact ones_length n },
{ contrapose,
assume H length_n,
apply lt_irrefl n,
calc
n = ∑ (i : fin c.length), 1 : by simp [length_n]
... < ∑ (i : fin c.length), c.blocks_fun i :
begin
obtain ⟨i, hi, i_blocks⟩ : ∃ i ∈ c.blocks, 1 < i := ne_ones_iff.1 H,
rw [← of_fn_blocks_fun, mem_of_fn c.blocks_fun, set.mem_range] at hi,
obtain ⟨j : fin c.length, hj : c.blocks_fun j = i⟩ := hi,
rw ← hj at i_blocks,
exact finset.sum_lt_sum (λ i hi, by simp [blocks_fun]) ⟨j, finset.mem_univ _, i_blocks⟩,
end
... = n : c.sum_blocks_fun }
end
lemma eq_ones_iff_le_length {c : composition n} :
c = ones n ↔ n ≤ c.length :=
by simp [eq_ones_iff_length, le_antisymm_iff, c.length_le]
/-! ### The composition `composition.single` -/
/-- The composition made of a single block of size `n`. -/
def single (n : ℕ) (h : 0 < n) : composition n :=
⟨[n], by simp [h], by simp⟩
@[simp] lemma single_length {n : ℕ} (h : 0 < n) : (single n h).length = 1 := rfl
@[simp] lemma single_blocks {n : ℕ} (h : 0 < n) : (single n h).blocks = [n] := rfl
@[simp] lemma single_blocks_fun {n : ℕ} (h : 0 < n) (i : fin (single n h).length) :
(single n h).blocks_fun i = n :=
by simp [blocks_fun, single, blocks, i.2]
@[simp] lemma single_embedding {n : ℕ} (h : 0 < n) (i : fin n) :
(single n h).embedding ⟨0, single_length h ▸ zero_lt_one⟩ i = i :=
by { ext, simp }
lemma eq_single_iff_length {n : ℕ} (h : 0 < n) {c : composition n} :
c = single n h ↔ c.length = 1 :=
begin
split,
{ assume H,
rw H,
exact single_length h },
{ assume H,
ext1,
have A : c.blocks.length = 1 := H ▸ c.blocks_length,
have B : c.blocks.sum = n := c.blocks_sum,
rw eq_cons_of_length_one A at B ⊢,
simpa [single_blocks] using B }
end
lemma ne_single_iff {n : ℕ} (hn : 0 < n) {c : composition n} :
c ≠ single n hn ↔ ∀ i, c.blocks_fun i < n :=
begin
rw ← not_iff_not,
push_neg,
split,
{ rintros rfl,
exact ⟨⟨0, by simp⟩, by simp⟩ },
{ rintros ⟨i, hi⟩,
rw eq_single_iff_length,
have : ∀ j : fin c.length, j = i,
{ intros j,
by_contradiction ji,
apply lt_irrefl ∑ k, c.blocks_fun k,
calc ∑ k, c.blocks_fun k ≤ c.blocks_fun i : by simp only [c.sum_blocks_fun, hi]
... < ∑ k, c.blocks_fun k :
finset.single_lt_sum ji (finset.mem_univ _) (finset.mem_univ _) (c.one_le_blocks_fun j)
(λ _ _ _, zero_le _) },
simpa using fintype.card_eq_one_of_forall_eq this }
end
end composition
/-!
### Splitting a list
Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists
of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the
join operation.
-/
namespace list
variable {α : Type*}
/-- Auxiliary for `list.split_wrt_composition`. -/
def split_wrt_composition_aux : list α → list ℕ → list (list α)
| l [] := []
| l (n :: ns) :=
let (l₁, l₂) := l.split_at n in
l₁ :: split_wrt_composition_aux l₂ ns
/-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of
`k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`.
This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/
def split_wrt_composition (l : list α) (c : composition n) : list (list α) :=
split_wrt_composition_aux l c.blocks
local attribute [simp] split_wrt_composition_aux.equations._eqn_1
local attribute [simp]
lemma split_wrt_composition_aux_cons (l : list α) (n ns) :
l.split_wrt_composition_aux (n :: ns) = take n l :: (drop n l).split_wrt_composition_aux ns :=
by simp [split_wrt_composition_aux]
lemma length_split_wrt_composition_aux (l : list α) (ns) :
length (l.split_wrt_composition_aux ns) = ns.length :=
by induction ns generalizing l; simp *
/-- When one splits a list along a composition `c`, the number of sublists thus created is
`c.length`. -/
@[simp] lemma length_split_wrt_composition (l : list α) (c : composition n) :
length (l.split_wrt_composition c) = c.length :=
length_split_wrt_composition_aux _ _
lemma map_length_split_wrt_composition_aux {ns : list ℕ} :
∀ {l : list α}, ns.sum ≤ l.length → map length (l.split_wrt_composition_aux ns) = ns :=
begin
induction ns with n ns IH; intros l h; simp at h ⊢,
have := le_trans (nat.le_add_right _ _) h,
rw IH, {simp [this]},
rwa [length_drop, le_tsub_iff_left this]
end
/-- When one splits a list along a composition `c`, the lengths of the sublists thus created are
given by the block sizes in `c`. -/
lemma map_length_split_wrt_composition (l : list α) (c : composition l.length) :
map length (l.split_wrt_composition c) = c.blocks :=
map_length_split_wrt_composition_aux (le_of_eq c.blocks_sum)
lemma length_pos_of_mem_split_wrt_composition {l l' : list α} {c : composition l.length}
(h : l' ∈ l.split_wrt_composition c) : 0 < length l' :=
begin
have : l'.length ∈ (l.split_wrt_composition c).map list.length :=
list.mem_map_of_mem list.length h,
rw map_length_split_wrt_composition at this,
exact c.blocks_pos this
end
lemma sum_take_map_length_split_wrt_composition
(l : list α) (c : composition l.length) (i : ℕ) :
(((l.split_wrt_composition c).map length).take i).sum = c.size_up_to i :=
by { congr, exact map_length_split_wrt_composition l c }
lemma nth_le_split_wrt_composition_aux (l : list α) (ns : list ℕ) {i : ℕ} (hi) :
nth_le (l.split_wrt_composition_aux ns) i hi =
(l.take (ns.take (i+1)).sum).drop (ns.take i).sum :=
begin
induction ns with n ns IH generalizing l i, {cases hi},
cases i; simp [IH],
rw [add_comm n, drop_add, drop_take],
end
/-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l`
between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th
block of the composition. -/
lemma nth_le_split_wrt_composition (l : list α) (c : composition n)
{i : ℕ} (hi : i < (l.split_wrt_composition c).length) :
nth_le (l.split_wrt_composition c) i hi = (l.take (c.size_up_to (i+1))).drop (c.size_up_to i) :=
nth_le_split_wrt_composition_aux _ _ _
theorem join_split_wrt_composition_aux {ns : list ℕ} :
∀ {l : list α}, ns.sum = l.length → (l.split_wrt_composition_aux ns).join = l :=
begin
induction ns with n ns IH; intros l h; simp at h ⊢,
{ exact (length_eq_zero.1 h.symm).symm },
rw IH, {simp},
rwa [length_drop, ← h, add_tsub_cancel_left]
end
/-- If one splits a list along a composition, and then joins the sublists, one gets back the
original list. -/
@[simp] theorem join_split_wrt_composition (l : list α) (c : composition l.length) :
(l.split_wrt_composition c).join = l :=
join_split_wrt_composition_aux c.blocks_sum
/-- If one joins a list of lists and then splits the join along the right composition, one gets
back the original list of lists. -/
@[simp] theorem split_wrt_composition_join (L : list (list α)) (c : composition L.join.length)
(h : map length L = c.blocks) : split_wrt_composition (join L) c = L :=
by simp only [eq_self_iff_true, and_self, eq_iff_join_eq, join_split_wrt_composition,
map_length_split_wrt_composition, h]
end list
/-!
### Compositions as sets
Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and
`n`, where the points of the set (other than `n`) correspond to the leftmost points of each block.
-/
/-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by
considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/
def composition_as_set_equiv (n : ℕ) : composition_as_set n ≃ finset (fin (n - 1)) :=
{ to_fun := λ c, {i : fin (n-1) |
(⟨1 + (i : ℕ), begin
apply (add_lt_add_left i.is_lt 1).trans_le,
rw [nat.succ_eq_add_one, add_comm],
exact add_le_add (nat.sub_le n 1) (le_refl 1)
end ⟩ : fin n.succ) ∈ c.boundaries}.to_finset,
inv_fun := λ s,
{ boundaries := {i : fin n.succ | (i = 0) ∨ (i = fin.last n)
∨ (∃ (j : fin (n-1)) (hj : j ∈ s), (i : ℕ) = j + 1)}.to_finset,
zero_mem := by simp,
last_mem := by simp },
left_inv := begin
assume c,
ext i,
simp only [exists_prop, add_comm, set.mem_to_finset, true_or, or_true, set.mem_set_of_eq],
split,
{ rintro (rfl | rfl | ⟨j, hj1, hj2⟩),
{ exact c.zero_mem },
{ exact c.last_mem },
{ convert hj1, rwa fin.ext_iff } },
{ simp only [or_iff_not_imp_left],
assume i_mem i_ne_zero i_ne_last,
simp [fin.ext_iff] at i_ne_zero i_ne_last,
have A : (1 + (i-1) : ℕ) = (i : ℕ),
by { rw add_comm, exact nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr i_ne_zero) },
refine ⟨⟨i - 1, _⟩, _, _⟩,
{ have : (i : ℕ) < n + 1 := i.2,
simp [nat.lt_succ_iff_lt_or_eq, i_ne_last] at this,
exact nat.pred_lt_pred i_ne_zero this },
{ convert i_mem,
rw fin.ext_iff,
simp only [fin.coe_mk, A] },
{ simp [A] } },
end,
right_inv := begin
assume s,
ext i,
have : 1 + (i : ℕ) ≠ n,
{ apply ne_of_lt,
convert add_lt_add_left i.is_lt 1,
rw add_comm,
apply (nat.succ_pred_eq_of_pos _).symm,
exact (zero_le i.val).trans_lt (i.2.trans_le (nat.sub_le n 1)) },
simp only [fin.ext_iff, exists_prop, fin.coe_zero, add_comm,
set.mem_to_finset, set.mem_set_of_eq, fin.coe_last],
erw [set.mem_set_of_eq],
simp only [this, false_or, add_right_inj, add_eq_zero_iff, one_ne_zero, false_and, fin.coe_mk],
split,
{ rintros ⟨j, js, hj⟩, convert js, exact fin.ext_iff.2 hj },
{ assume h, exact ⟨i, h, rfl⟩ }
end }
instance composition_as_set_fintype (n : ℕ) : fintype (composition_as_set n) :=
fintype.of_equiv _ (composition_as_set_equiv n).symm
lemma composition_as_set_card (n : ℕ) : fintype.card (composition_as_set n) = 2 ^ (n - 1) :=
begin
have : fintype.card (finset (fin (n-1))) = 2 ^ (n - 1), by simp,
rw ← this,
exact fintype.card_congr (composition_as_set_equiv n)
end
namespace composition_as_set
variables (c : composition_as_set n)
lemma boundaries_nonempty : c.boundaries.nonempty :=
⟨0, c.zero_mem⟩
lemma card_boundaries_pos : 0 < finset.card c.boundaries :=
finset.card_pos.mpr c.boundaries_nonempty
/-- Number of blocks in a `composition_as_set`. -/
def length : ℕ := finset.card c.boundaries - 1
lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 :=
(tsub_eq_iff_eq_add_of_le (nat.succ_le_of_lt c.card_boundaries_pos)).mp rfl
lemma length_lt_card_boundaries : c.length < c.boundaries.card :=
by { rw c.card_boundaries_eq_succ_length, exact lt_add_one _ }
lemma lt_length (i : fin c.length) : (i : ℕ) + 1 < c.boundaries.card :=
lt_tsub_iff_right.mp i.2
lemma lt_length' (i : fin c.length) : (i : ℕ) < c.boundaries.card :=
lt_of_le_of_lt (nat.le_succ i) (c.lt_length i)
/-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/
def boundary : fin c.boundaries.card ↪o fin (n + 1) := c.boundaries.order_emb_of_fin rfl
@[simp] lemma boundary_zero : (c.boundary ⟨0, c.card_boundaries_pos⟩ : fin (n + 1)) = 0 :=
begin
rw [boundary, finset.order_emb_of_fin_zero rfl c.card_boundaries_pos],
exact le_antisymm (finset.min'_le _ _ c.zero_mem) (fin.zero_le _),
end
@[simp] lemma boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = fin.last n :=
begin
convert finset.order_emb_of_fin_last rfl c.card_boundaries_pos,
exact le_antisymm (finset.le_max' _ _ c.last_mem) (fin.le_last _)
end
/-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/
def blocks_fun (i : fin c.length) : ℕ :=
(c.boundary ⟨(i : ℕ) + 1, c.lt_length i⟩) - (c.boundary ⟨i, c.lt_length' i⟩)
lemma blocks_fun_pos (i : fin c.length) : 0 < c.blocks_fun i :=
begin
have : (⟨i, c.lt_length' i⟩ : fin c.boundaries.card) < ⟨i + 1, c.lt_length i⟩ :=
nat.lt_succ_self _,
exact lt_tsub_iff_left.mpr ((c.boundaries.order_emb_of_fin rfl).strict_mono this)
end
/-- List of the sizes of the blocks in a `composition_as_set`. -/
def blocks (c : composition_as_set n) : list ℕ :=
of_fn c.blocks_fun
@[simp] lemma blocks_length : c.blocks.length = c.length :=
length_of_fn _
lemma blocks_partial_sum {i : ℕ} (h : i < c.boundaries.card) :
(c.blocks.take i).sum = c.boundary ⟨i, h⟩ :=
begin
induction i with i IH, { simp },
have A : i < c.blocks.length,
{ rw c.card_boundaries_eq_succ_length at h,
simp [blocks, nat.lt_of_succ_lt_succ h] },
have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length, nat.sub_le]),
rw [sum_take_succ _ _ A, IH B],
simp only [blocks, blocks_fun, nth_le_of_fn'],
apply add_tsub_cancel_of_le,
simp
end
lemma mem_boundaries_iff_exists_blocks_sum_take_eq {j : fin (n+1)} :
j ∈ c.boundaries ↔ ∃ i < c.boundaries.card, (c.blocks.take i).sum = j :=
begin
split,
{ assume hj,
rcases (c.boundaries.order_iso_of_fin rfl).surjective ⟨j, hj⟩ with ⟨i, hi⟩,
rw [subtype.ext_iff, subtype.coe_mk] at hi,
refine ⟨i.1, i.2, _⟩,
rw [← hi, c.blocks_partial_sum i.2],
refl },
{ rintros ⟨i, hi, H⟩,
convert (c.boundaries.order_iso_of_fin rfl ⟨i, hi⟩).2,
have : c.boundary ⟨i, hi⟩ = j, by rwa [fin.ext_iff, ← c.blocks_partial_sum hi],
exact this.symm }
end
lemma blocks_sum : c.blocks.sum = n :=
begin
have : c.blocks.take c.length = c.blocks := take_all_of_le (by simp [blocks]),
rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length],
refl
end
/-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the
blocks as a list of positive integers. -/
def to_composition : composition n :=
{ blocks := c.blocks,
blocks_pos := by simp only [blocks, forall_mem_of_fn_iff, blocks_fun_pos c, forall_true_iff],
blocks_sum := c.blocks_sum }
end composition_as_set
/-!
### Equivalence between compositions and compositions as sets
In this section, we explain how to go back and forth between a `composition` and a
`composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to
each other, and construct an equivalence between them called `composition_equiv`.
-/
@[simp] lemma composition.to_composition_as_set_length (c : composition n) :
c.to_composition_as_set.length = c.length :=
by simp [composition.to_composition_as_set, composition_as_set.length,
c.card_boundaries_eq_succ_length]
@[simp] lemma composition_as_set.to_composition_length (c : composition_as_set n) :
c.to_composition.length = c.length :=
by simp [composition_as_set.to_composition, composition.length, composition.blocks]
@[simp] lemma composition.to_composition_as_set_blocks (c : composition n) :
c.to_composition_as_set.blocks = c.blocks :=
begin
let d := c.to_composition_as_set,
change d.blocks = c.blocks,
have length_eq : d.blocks.length = c.blocks.length,
{ convert c.to_composition_as_set_length,
simp [composition_as_set.blocks] },
suffices H : ∀ (i ≤ d.blocks.length), (d.blocks.take i).sum = (c.blocks.take i).sum,
from eq_of_sum_take_eq length_eq H,
assume i hi,
have i_lt : i < d.boundaries.card,
{ convert nat.lt_succ_iff.2 hi,
convert d.card_boundaries_eq_succ_length,
exact length_of_fn _ },
have i_lt' : i < c.boundaries.card := i_lt,
have i_lt'' : i < c.length + 1, by rwa c.card_boundaries_eq_succ_length at i_lt',
have A : d.boundaries.order_emb_of_fin rfl ⟨i, i_lt⟩
= c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length ⟨i, i_lt''⟩ := rfl,
have B : c.size_up_to i = c.boundary ⟨i, i_lt''⟩ := rfl,
rw [d.blocks_partial_sum i_lt, composition_as_set.boundary, ← composition.size_up_to, B,
A, c.order_emb_of_fin_boundaries]
end
@[simp] lemma composition_as_set.to_composition_blocks (c : composition_as_set n) :
c.to_composition.blocks = c.blocks := rfl
@[simp] lemma composition_as_set.to_composition_boundaries (c : composition_as_set n) :
c.to_composition.boundaries = c.boundaries :=
begin
ext j,
simp only [c.mem_boundaries_iff_exists_blocks_sum_take_eq, composition.boundaries,
finset.mem_map],
split,
{ rintros ⟨i, _, hi⟩,
refine ⟨i.1, _, _⟩,
simpa [c.card_boundaries_eq_succ_length] using i.2,
simp [composition.boundary, composition.size_up_to, ← hi] },
{ rintros ⟨i, i_lt, hi⟩,
refine ⟨i, by simp, _⟩,
rw [c.card_boundaries_eq_succ_length] at i_lt,
simp [composition.boundary, nat.mod_eq_of_lt i_lt, composition.size_up_to, hi] }
end
@[simp] lemma composition.to_composition_as_set_boundaries (c : composition n) :
c.to_composition_as_set.boundaries = c.boundaries := rfl
/-- Equivalence between `composition n` and `composition_as_set n`. -/
def composition_equiv (n : ℕ) : composition n ≃ composition_as_set n :=
{ to_fun := λ c, c.to_composition_as_set,
inv_fun := λ c, c.to_composition,
left_inv := λ c, by { ext1, exact c.to_composition_as_set_blocks },
right_inv := λ c, by { ext1, exact c.to_composition_boundaries } }
instance composition_fintype (n : ℕ) : fintype (composition n) :=
fintype.of_equiv _ (composition_equiv n).symm
lemma composition_card (n : ℕ) : fintype.card (composition n) = 2 ^ (n - 1) :=
begin
rw ← composition_as_set_card n,
exact fintype.card_congr (composition_equiv n)
end
|
e48f8a9e1e7b26c38d20a55f31b6fdd92c7ba01c | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /set_deMorgan.lean | 5c8f08700780c3a58ad7d715e90c08a1cef19875 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,267 | lean | import data.set.basic
import topology.topological_space
open topological_space
open set
universe u
variable elem_type : Type u
variable a : elem_type
variable A : set elem_type
variable B : set elem_type
def notPoQ {p : Prop} {q : Prop} (H : ¬ (p ∨ q)) : (¬p ∧ ¬q) :=
have Hnp : ¬p, from λ Hp : p, H (or.intro_left q Hp),
have Hnq : ¬q, from λ Hq : q, H (or.intro_right p Hq),
show ¬p ∧ ¬q, from and.intro Hnp Hnq
def prop_deMorgan {p : Prop} {q : Prop} (H : p ∧ q) : ¬ (¬p ∨ ¬q) :=
have Pp : p, from and.elim_left H,
have Pq : q, from and.elim_right H,
assume (H1 : (¬p ∨ ¬q)),
or.elim H1 (λ Hnp : ¬p, Hnp Pp) (λ Hnq: ¬q, Hnq Pq)
open classical
def dne {p : Prop} : ¬¬p → p :=
assume H0 : ¬¬p,
or.elim (em p)
(assume H : p, H)
(assume H : ¬p, false.elim (H0 H))
def set_deMorgan : a ∈ A ∩ B → a ∈ set.compl ((set.compl A) ∪ (set.compl B)) :=
λ H : a ∈ A ∧ a ∈ B,
show ¬ (¬ a ∈ A ∨ ¬ a ∈ B), from prop_deMorgan H
def set_deMorgan_incl : A ∩ B ⊆ set.compl ((set.compl A) ∪ (set.compl B)) :=
have H : ∀ b : elem_type, b ∈ A ∩ B → b ∈ set.compl ((set.compl A) ∪ (set.compl B)),
from λ (b : elem_type), @set_deMorgan elem_type b A B,
H
def prop_deMorgan_conv {p : Prop} {q : Prop} (H : ¬ (¬p ∨ ¬q)) : p ∧ q :=
have Pnnpnnq : ¬¬p ∧ ¬¬q, from notPoQ H,
have Pnnp : ¬¬p, from and.elim_left Pnnpnnq,
have Pnnq : ¬¬q, from and.elim_right Pnnpnnq,
show p ∧ q, from and.intro (dne Pnnp) (dne Pnnq)
def set_deMorgan_conv (H : a ∈ set.compl ((set.compl A) ∪ (set.compl B))) : a ∈ A ∩ B :=
prop_deMorgan_conv H
def set_deMorgan_incl_conv : set.compl ((set.compl A) ∪ (set.compl B)) ⊆ A ∩ B :=
λ b, set_deMorgan_conv _ b _ _
def set_deMorgan_eq_ext : A ∩ B = set.compl ((set.compl A) ∪ (set.compl B)) :=
subset.antisymm (set_deMorgan_incl _ _ _) (set_deMorgan_incl_conv _ _ _)
variable natSet : set nat
variable natUni : univ nat
def univSet : set nat :=
univ
def allUniv : ∀ (n : nat), n ∈ univSet :=
λ n,
true.intro
def eP : 4 ∈ univSet := true.intro
def smallSet0 : set nat := {a | a = 0}
def smallSet1 : set nat := {a | a = 1}
def bigSet : set nat := {a | a = 0 ∨ a = 1}
def simpleTopo : set (set nat) := {A | A = smallSet0 ∨ A = smallSet1 ∨ A = bigSet ∨ A = univ}
def univInSimpleTopo : univ ∈ simpleTopo :=
have H1 : @univ nat = univ, from rfl,
have H3 : (univ = bigSet ∨ @univ nat = univ),
from or.intro_right (univ = bigSet) H1,
have H4 : (univ = smallSet1 ∨ (univ = bigSet ∨ @univ nat = univ)),
from or.intro_right (univ = smallSet1) H3,
have H2 : (univ = smallSet0 ∨ (univ = smallSet1 ∨ (univ = bigSet ∨ @univ nat = univ))),
from or.intro_right (univ = smallSet0) H4,
H2
def inter_indemp : A ∩ A = A :=
have P1 : ∀ a, a ∈ A ∩ A → a ∈ A, from λ a H,
and.elim_left H,
have P2 : ∀ a, a ∈ A → a ∈ A ∩ A, from λ a H,
and.intro H H,
set.ext (λ a, iff.intro (P1 a) (P2 a))
#check (set nat : Sort 1)
/-,-/
def open_inter (s t : set nat) : s ∈ simpleTopo → t ∈ simpleTopo → (s ∩ t) ∈ simpleTopo :=
λ sInTopo tInTopo,
have H1 : s = smallSet0 ∨ s = smallSet1 ∨ s = bigSet ∨ s = univ, from sInTopo,
have H2 : t = smallSet0 ∨ t = smallSet1 ∨ t = bigSet ∨ t = univ, from tInTopo,
show (s ∩ t = smallSet0 ∨ s ∩ t = smallSet1 ∨ s ∩ t = bigSet ∨ s ∩ t = univ), from
or.elim H1
(λ A1 : s = smallSet0,
have A1Rev : smallSet0 = s, from sorry,
or.elim H2
(λ B1 : t = smallSet0,
have H : smallSet0 ∩ smallSet0 = smallSet0,
from inter_indemp _ smallSet0,
have H2 : s ∩ smallSet0 = smallSet0,
from @eq.subst _ (λ a, a ∩ smallSet0 = smallSet0) smallSet0 s A1Rev H,
have H1 : s ∩ t = smallSet0, from @eq.subst _ (λ a, s ∩ a = smallSet0) smallSet0 t (eq.symm B1) H2,
or.intro_left (s ∩ t = smallSet1 ∨ s ∩ t = bigSet ∨ s ∩ t = univ) H1)
(λ B2 : t = smallSet1 ∨ t = bigSet ∨ t = univ, sorry)
)
(λ A2 : s = smallSet1 ∨ s = bigSet ∨ s = univ,
or.elim A2
(λ A3 : s = smallSet1, sorry)
(λ A4 : s = bigSet ∨ s = univ,
or.elim A4
(λ A5 : s = bigSet, sorry)
(λ A5 : s = univ, sorry)
)
)
def open_sUnion : ∀s : (set (set nat)), (∀t∈ s, t ∈ simpleTopo) → (⋃₀ s) ∈ simpleTopo :=
sorry
def aTopology : topological_space (nat) :=
topological_space.mk
simpleTopo
univInSimpleTopo
open_inter
open_sUnion
def setInclusion : set.subset smallSet0 bigSet :=
λ a : nat,
λ H : a ∈ smallSet0,
have H1 : a = 0, from H,
have H2 : a = 0 ∨ a = 1, from or.intro_left (a = 1) H1,
have H3 : a ∈ bigSet, from H2,
H3
#check λ a : set nat, sorry
--#check a : true
example : true := true.intro
--#check eP |
11fecb3e80604364b28f5a60f7c376a8b606b954 | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/stone_cech.lean | b71acb835ab521c45c53ac9c02da3cff6df9baf5 | [
"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 | 11,244 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import topology.bases
import topology.dense_embedding
/-! # Stone-Čech compactification
Construction of the Stone-Čech compactification using ultrafilters.
Parts of the formalization are based on "Ultrafilters and Topology"
by Marius Stekelenburg, particularly section 5.
-/
noncomputable theory
open filter set
open_locale topological_space
universes u v
section ultrafilter
/- The set of ultrafilters on α carries a natural topology which makes
it the Stone-Čech compactification of α (viewed as a discrete space). -/
/-- Basis for the topology on `ultrafilter α`. -/
def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) :=
range $ λ s : set α, {u | s ∈ u}
variables {α : Type u}
instance : topological_space (ultrafilter α) :=
topological_space.generate_from (ultrafilter_basis α)
lemma ultrafilter_basis_is_basis :
topological_space.is_topological_basis (ultrafilter_basis α) :=
⟨begin
rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩,
refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem_sets ua ub, assume v hv, ⟨_, _⟩⟩;
apply mem_sets_of_superset hv; simp [inter_subset_right a b]
end,
eq_univ_of_univ_subset $ subset_sUnion_of_mem $
⟨univ, eq_univ_of_forall (λ u, univ_mem_sets)⟩,
rfl⟩
/-- The basic open sets for the topology on ultrafilters are open. -/
lemma ultrafilter_is_open_basic (s : set α) :
is_open {u : ultrafilter α | s ∈ u} :=
topological_space.is_open_of_is_topological_basis ultrafilter_basis_is_basis ⟨s, rfl⟩
/-- The basic open sets for the topology on ultrafilters are also closed. -/
lemma ultrafilter_is_closed_basic (s : set α) :
is_closed {u : ultrafilter α | s ∈ u} :=
begin
rw ← is_open_compl_iff,
convert ultrafilter_is_open_basic sᶜ,
ext u,
exact ultrafilter.compl_mem_iff_not_mem.symm
end
/-- Every ultrafilter `u` on `ultrafilter α` converges to a unique
point of `ultrafilter α`, namely `mjoin u`. -/
lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} :
↑u ≤ 𝓝 x ↔ x = mjoin u :=
begin
rw [eq_comm, ← ultrafilter.coe_le_coe],
change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, {v : ultrafilter α | s ∈ v} ∈ u,
simp only [topological_space.nhds_generate_from, le_infi_iff, ultrafilter_basis,
le_principal_iff, mem_set_of_eq],
split,
{ intros h a ha, exact h _ ⟨ha, a, rfl⟩ },
{ rintros h a ⟨xi, a, rfl⟩, exact h _ xi }
end
instance ultrafilter_compact : compact_space (ultrafilter α) :=
⟨compact_iff_ultrafilter_le_nhds.mpr $ assume f _,
⟨mjoin f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩
instance ultrafilter.t2_space : t2_space (ultrafilter α) :=
t2_iff_ultrafilter.mpr $ assume x y f fx fy,
have hx : x = mjoin f, from ultrafilter_converges_iff.mp fx,
have hy : y = mjoin f, from ultrafilter_converges_iff.mp fy,
hx.trans hy.symm
lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b :=
begin
rw topological_space.nhds_generate_from,
simp only [comap_infi, comap_principal],
intros s hs,
rw ←le_principal_iff,
refine infi_le_of_le {u | s ∈ u} _,
refine infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _,
exact principal_mono.2 (λ a, id)
end
section embedding
lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) :=
begin
intros x y h,
have : {x} ∈ (pure x : ultrafilter α) := singleton_mem_pure_sets,
rw h at this,
exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm
end
open topological_space
/-- The range of `pure : α → ultrafilter α` is dense in `ultrafilter α`. -/
lemma dense_range_pure : dense_range (pure : α → ultrafilter α) :=
λ x, mem_closure_iff_ultrafilter.mpr
⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩
/-- The map `pure : α → ultra_filter α` induces on `α` the discrete topology. -/
lemma induced_topology_pure :
topological_space.induced (pure : α → ultrafilter α) ultrafilter.topological_space = ⊥ :=
begin
apply eq_bot_of_singletons_open,
intros x,
use [{u : ultrafilter α | {x} ∈ u}, ultrafilter_is_open_basic _],
simp,
end
/-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/
lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) :=
by letI : topological_space α := ⊥; exact ⟨⟨induced_topology_pure.symm⟩, dense_range_pure⟩
-- The following refined version will never be used
/-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/
lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) :=
by letI : topological_space α := ⊥ ;
exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure }
end embedding
section extension
/- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a
unique extension to a continuous function `ultrafilter α → γ`. We
already know it must be unique because `α → ultrafilter α` is a
dense embedding and `γ` is Hausdorff. For existence, we will invoke
`dense_embedding.continuous_extend`. -/
variables {γ : Type*} [topological_space γ]
/-- The extension of a function `α → γ` to a function `ultrafilter α → γ`.
When `γ` is a compact Hausdorff space it will be continuous. -/
def ultrafilter.extend (f : α → γ) : ultrafilter α → γ :=
by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f
variables [t2_space γ]
lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f :=
begin
letI : topological_space α := ⊥,
haveI : discrete_topology α := ⟨rfl⟩,
exact funext (dense_inducing_pure.extend_eq continuous_of_discrete_topology)
end
variables [compact_space γ]
lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) :=
have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap pure (𝓝 b)) (𝓝 c) := assume b,
-- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ.
let ⟨c, _, h⟩ := compact_univ.ultrafilter_le_nhds (b.map f)
(by rw [le_principal_iff]; exact univ_mem_sets) in
⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩,
begin
letI : topological_space α := ⊥,
haveI : normal_space γ := normal_of_compact_t2,
exact dense_inducing_pure.continuous_extend this
end
/-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the
unique limit of the ultrafilter `b.map f` in `γ`. -/
lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} :
ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c :=
⟨assume h, begin
-- Write b as an ultrafilter limit of pure ultrafilters, and use
-- the facts that ultrafilter.extend is a continuous extension of f.
let b' : ultrafilter (ultrafilter α) := b.map pure,
have t : ↑b' ≤ 𝓝 b,
from ultrafilter_converges_iff.mpr (bind_pure _).symm,
rw ←h,
have := (continuous_ultrafilter_extend f).tendsto b,
refine le_trans _ (le_trans (map_mono t) this),
change _ ≤ map (ultrafilter.extend f ∘ pure) ↑b,
rw ultrafilter_extend_extends,
exact le_refl _
end,
assume h, by letI : topological_space α := ⊥; exact
dense_inducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩
end extension
end ultrafilter
section stone_cech
/- Now, we start with a (not necessarily discrete) topological space α
and we want to construct its Stone-Čech compactification. We can
build it as a quotient of `ultrafilter α` by the relation which
identifies two points if the extension of every continuous function
α → γ to a compact Hausdorff space sends the two points to the same
point of γ. -/
variables (α : Type u) [topological_space α]
instance stone_cech_setoid : setoid (ultrafilter α) :=
{ r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI
∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f),
ultrafilter.extend f x = ultrafilter.extend f y,
iseqv :=
⟨assume x γ tγ h₁ h₂ f hf, rfl,
assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm,
assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ }
/-- The Stone-Čech compactification of a topological space. -/
def stone_cech : Type u := quotient (stone_cech_setoid α)
variables {α}
instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance
instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance
/-- The natural map from α to its Stone-Čech compactification. -/
def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧
/-- The image of stone_cech_unit is dense. (But stone_cech_unit need
not be an embedding, for example if α is not Hausdorff.) -/
lemma dense_range_stone_cech_unit : dense_range (stone_cech_unit : α → stone_cech α) :=
dense_range_pure.quotient
section extension
variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ]
variables {f : α → γ} (hf : continuous f)
local attribute [elab_with_expected_type] quotient.lift
/-- The extension of a continuous function from α to a compact
Hausdorff space γ to the Stone-Čech compactification of α. -/
def stone_cech_extend : stone_cech α → γ :=
quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf)
lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f :=
ultrafilter_extend_extends f
lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) :=
continuous_quot_lift _ (continuous_ultrafilter_extend f)
end extension
lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : ↑u ≤ 𝓝 x) : u ≈ pure x :=
assume γ tγ h₁ h₂ f hf, begin
resetI,
transitivity f x, swap, symmetry,
all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) },
{ apply pure_le_nhds }, { exact ux }
end
lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) :=
continuous_iff_ultrafilter.mpr $ λ x g gx,
have ↑(g.map pure) ≤ 𝓝 g,
by rw ultrafilter_converges_iff; exact (bind_pure _).symm,
have (g.map stone_cech_unit : filter (stone_cech α)) ≤ 𝓝 ⟦g⟧, from
continuous_at_iff_ultrafilter.mp (continuous_quotient_mk.tendsto g) _ this,
by rwa (show ⟦g⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this
instance stone_cech.t2_space : t2_space (stone_cech α) :=
begin
rw t2_iff_ultrafilter,
rintros ⟨x⟩ ⟨y⟩ g gx gy,
apply quotient.sound,
intros γ tγ h₁ h₂ f hf,
resetI,
let ff := stone_cech_extend hf,
change ff ⟦x⟧ = ff ⟦y⟧,
have lim := λ (z : ultrafilter α) (gz : (g : filter (stone_cech α)) ≤ 𝓝 ⟦z⟧),
((continuous_stone_cech_extend hf).tendsto _).mono_left gz,
exact tendsto_nhds_unique (lim x gx) (lim y gy)
end
instance stone_cech.compact_space : compact_space (stone_cech α) :=
quotient.compact_space
end stone_cech
|
3856e59da76a56f1392ffd9803e83f188f373050 | 03bd658c402412f41d3026d1040ee8ca8c0fc579 | /src/misc_lemmas.lean | c5b6d1868a3d5a7eb9a0ad94a1f0c5fa9538a10a | [] | no_license | ImperialCollegeLondon/dots_and_boxes | c205f6dbad8af9625f56715e4d1bed96b0ac1022 | f7bd0b1603674a657170c5395adb717c4f670220 | refs/heads/master | 1,663,752,058,476 | 1,591,438,614,000 | 1,591,438,614,000 | 139,707,103 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,743 | lean | import data.int.basic tactic.linarith
/- abs -/
/-- any integer greater than or equal to some absolute value is non-negative-/
lemma abs_le_nonneg {a b : ℤ } : abs(a) ≤ b → 0 ≤ b:=
begin
have h : 0 ≤ abs(a),
{show abs(a) ≥ 0, -- ≥ is defined via ≤
exact abs_nonneg a}, -- absolute values are non-negative
intro x,
exact le_trans h x, -- using transitivity of ≤
end
/--the absolute value of a difference of values is greater than or equal
to the the absolute value of the difference of their absolute values-/
theorem abs_abs_sub_abs_le (a b : ℤ) : abs (abs a - abs b) ≤ abs (a - b) :=
-- proof in term mode
abs_le.2 ⟨by rw [neg_le,neg_sub, abs_sub]; apply sub_abs_le_abs_sub, sub_abs_le_abs_sub a b⟩
/-- For any a, b, x, y, d in ℤ,
if abs (a - b) ≤ d and abs (x - y) ≤ d, then abs (min a x - min b y) ≤ d-/
lemma abs_min_sub_min {a b x y d : ℤ} (hab : abs (a - b) ≤ d)
(hxy : abs (x - y) ≤ d) : abs (min a x - min b y) ≤ d :=
begin
rw abs_le at *, -- abs (m - n) ≤ d ↔ d ≤ m - n ∧ m - n ≤ d, for any m,n in ℤ
cases hab,
cases hxy,
unfold min, -- min a x = if (a ≤ x), then a, else x
-- min b y = if (b ≤ y), then b, else y
split_ifs; split; linarith, -- all cases Lean can solve by itself using linarith
end
/- lt -/
/--if there exists an element strictly between a and the sucessor of c in ℕ, then a is smaller than c -/
lemma lt_trans_of_succ {a b c : ℕ}: a < b → b < nat.succ c → a < c :=
begin
intros h1 h2,
rw nat.lt_succ_iff at h2, -- b < nat.succ c ↔ b ≤ c
exact lt_of_lt_of_le h1 h2, /- lt_of_lt_of_le says : for all x, y, z of some adequate type,
x < y → y ≤ z → a < z-/
end |
c7b94a0c3f9f15ede4375b89a62c358bc6494e1a | 9cba98daa30c0804090f963f9024147a50292fa0 | /old/src/classical_velocity_test.lean | 5790087a29c9af16300d2cd737baca4ac471571d | [] | no_license | kevinsullivan/phys | dcb192f7b3033797541b980f0b4a7e75d84cea1a | ebc2df3779d3605ff7a9b47eeda25c2a551e011f | refs/heads/master | 1,637,490,575,500 | 1,629,899,064,000 | 1,629,899,064,000 | 168,012,884 | 0 | 3 | null | 1,629,644,436,000 | 1,548,699,832,000 | Lean | UTF-8 | Lean | false | false | 26 | lean | import .classical_velocity |
30fe82cac2d52880d03c691dd9ae8d9d00de12e9 | 856e2e1615a12f95b551ed48fa5b03b245abba44 | /src/group_theory/group_action.lean | 5d4de5701dde0588913cfef76514a9e4ab58b3aa | [
"Apache-2.0"
] | permissive | pimsp/mathlib | 8b77e1ccfab21703ba8fbe65988c7de7765aa0e5 | 913318ca9d6979686996e8d9b5ebf7e74aae1c63 | refs/heads/master | 1,669,812,465,182 | 1,597,133,610,000 | 1,597,133,610,000 | 281,890,685 | 1 | 0 | null | 1,595,491,577,000 | 1,595,491,576,000 | null | UTF-8 | Lean | false | false | 12,771 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import group_theory.coset
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open_locale big_operators
open function
/-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ)
infixr ` • `:73 := has_scalar.smul
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/
@[protect_proj] class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β :=
(one_smul : ∀ b : β, (1 : α) • b = b)
(mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b)
end prio
section
variables [monoid α] [mul_action α β]
theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _
lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm
lemma smul_comm {α : Type u} {β : Type v} [comm_monoid α] [mul_action α β] (a₁ a₂ : α) (b : β) :
a₁ • a₂ • b = a₂ • a₁ • b := by rw [←mul_smul, ←mul_smul, mul_comm]
variable (α)
@[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _
variables {α}
@[simp] lemma units.inv_smul_smul (u : units α) (x : β) :
(↑u⁻¹:α) • (u:α) • x = x :=
by rw [smul_smul, u.inv_mul, one_smul]
@[simp] lemma units.smul_inv_smul (u : units α) (x : β) :
(u:α) • (↑u⁻¹:α) • x = x :=
by rw [smul_smul, u.mul_inv, one_smul]
/-- Pullback a multiplicative action along an injective map respecting `•`. -/
protected def function.injective.mul_action [has_scalar α γ] (f : γ → β)
(hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) :
mul_action α γ :=
{ smul := (•),
one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x),
mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] }
/-- Pushforward a multiplicative action along a surjective map respecting `•`. -/
protected def function.surjective.mul_action [has_scalar α γ] (f : β → γ) (hf : surjective f)
(smul : ∀ (c : α) x, f (c • x) = c • f x) :
mul_action α γ :=
{ smul := (•),
one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] },
mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } }
section gwz
variables {G : Type*} [group_with_zero G] [mul_action G β]
lemma inv_smul_smul' {c : G} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x :=
(units.mk0 c hc).inv_smul_smul x
lemma smul_inv_smul' {c : G} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x :=
(units.mk0 c hc).smul_inv_smul x
lemma inv_smul_eq_iff {a : G} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y :=
by { split; intro h, rw [← h, smul_inv_smul' ha], rw [h, inv_smul_smul' ha] }
lemma eq_inv_smul_iff {a : G} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y :=
by { split; intro h, rw [h, smul_inv_smul' ha], rw [← h, inv_smul_smul' ha] }
end gwz
variables (p : Prop) [decidable p]
lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) :=
by split_ifs; refl
lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) :=
by split_ifs; refl
end
namespace mul_action
variables (α) [monoid α]
/-- The regular action of a monoid on itself by left multiplication. -/
def regular : mul_action α α :=
{ smul := λ a₁ a₂, a₁ * a₂,
one_smul := λ a, one_mul a,
mul_smul := λ a₁ a₂ a₃, mul_assoc _ _ _, }
variables [mul_action α β]
/-- The orbit of an element under an action. -/
def orbit (b : β) := set.range (λ x : α, x • b)
variable {α}
lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ :=
iff.rfl
@[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b :=
⟨x, rfl⟩
@[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b :=
⟨1, by simp [mul_action.one_smul]⟩
variable (α)
/-- The stabilizer of an element under an action, i.e. what sends the element to itself. -/
def stabilizer (b : β) : set α :=
{x : α | x • b = b}
variable {α}
@[simp] lemma mem_stabilizer_iff {b : β} {x : α} :
x ∈ stabilizer α b ↔ x • b = b := iff.rfl
variables (α) (β)
/-- The set of elements fixed under the whole action. -/
def fixed_points : set β := {b : β | ∀ x, x ∈ stabilizer α b}
variables {α} (β)
@[simp] lemma mem_fixed_points {b : β} :
b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl
lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔
(∀ b', b' ∈ orbit α b → b' = b) :=
⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x,
λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩
/-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/
def comp_hom [monoid γ] (g : γ → α) [is_monoid_hom g] :
mul_action γ β :=
{ smul := λ x b, (g x) • b,
one_smul := by simp [is_monoid_hom.map_one g, mul_action.one_smul],
mul_smul := by simp [is_monoid_hom.map_mul g, mul_action.mul_smul] }
instance (b : β) : is_submonoid (stabilizer α b) :=
{ one_mem := one_smul _ b,
mul_mem := λ a a' (ha : a • b = b) (hb : a' • b = b),
by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] }
end mul_action
namespace mul_action
variables [group α] [mul_action α β]
section
open mul_action quotient_group
@[simp] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x :=
(to_units α c).inv_smul_smul x
@[simp] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x :=
(to_units α c).smul_inv_smul x
variables (α) (β)
/-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/
def to_perm (g : α) : equiv.perm β :=
{ to_fun := (•) g,
inv_fun := (•) g⁻¹,
left_inv := inv_smul_smul g,
right_inv := smul_inv_smul g }
variables {α} {β}
instance : is_group_hom (to_perm α β) :=
{ map_mul := λ x y, equiv.ext (λ a, mul_action.mul_smul x y a) }
protected lemma bijective (g : α) : bijective (λ b : β, g • b) :=
(to_perm α β g).bijective
lemma orbit_eq_iff {a b : β} :
orbit α a = orbit α b ↔ a ∈ orbit α b:=
⟨λ h, h ▸ mem_orbit_self _,
λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x,
show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩,
λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹,
show (y * x⁻¹) • a = c, by
conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc,
mul_action.mul_smul, hx]}⟩⟩)⟩
instance (b : β) : is_subgroup (stabilizer α b) :=
{ one_mem := mul_action.one_smul _,
mul_mem := λ x y (hx : x • b = b) (hy : y • b = b),
show (x * y) • b = b, by rw mul_action.mul_smul; simp *,
inv_mem := λ x (hx : x • b = b), show x⁻¹ • b = b,
by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx] }
@[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) :=
⟨g⁻¹, by simp⟩
@[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) :=
⟨g * h⁻¹, by simp [mul_smul]⟩
variables (α) (β)
/-- The relation "in the same orbit". -/
def orbit_rel : setoid β :=
{ r := λ a b, a ∈ orbit α b,
iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm],
λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ }
variables {β}
open quotient_group
/-- Orbit-stabilizer theorem. -/
noncomputable def orbit_equiv_quotient_stabilizer (b : β) :
orbit α b ≃ quotient (stabilizer α b) :=
equiv.symm (equiv.of_bijective
(λ x : quotient (stabilizer α b), quotient.lift_on' x
(λ x, (⟨x • b, mem_orbit _ _⟩ : orbit α b))
(λ g h (H : _ = _), subtype.eq $ (mul_action.bijective (g⁻¹)).1
$ show g⁻¹ • (g • b) = g⁻¹ • (h • b),
by rw [← mul_action.mul_smul, ← mul_action.mul_smul,
H, inv_mul_self, mul_action.one_smul]))
⟨λ g h, quotient.induction_on₂' g h (λ g h H, quotient.sound' $
have H : g • b = h • b := subtype.mk.inj H,
show (g⁻¹ * h) • b = b,
by rw [mul_action.mul_smul, ← H, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul]),
λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩)
@[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) :
((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b :=
rfl
end
open quotient_group mul_action is_subgroup
/-- Action on left cosets. -/
def mul_left_cosets (H : set α) [is_subgroup H]
(x : α) (y : quotient H) : quotient H :=
quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y))
(λ a b (hab : _ ∈ H), quotient_group.eq.2
(by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one]))
instance (H : set α) [is_subgroup H] : mul_action α (quotient H) :=
{ smul := mul_left_cosets H,
one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2
(by simp [is_submonoid.one_mem])),
mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2
(by simp [mul_inv_rev, is_submonoid.one_mem, mul_assoc])) }
instance mul_left_cosets_comp_subtype_val (H I : set α) [is_subgroup H] [is_subgroup I] :
mul_action I (quotient H) :=
mul_action.comp_hom (quotient H) (subtype.val : I → α)
end mul_action
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/
class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β :=
(smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y)
(smul_zero : ∀(r : α), r • (0 : β) = 0)
end prio
section
variables [monoid α] [add_monoid β] [distrib_mul_action α β]
theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ :=
distrib_mul_action.smul_add _ _ _
@[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 :=
distrib_mul_action.smul_zero _
/-- Pullback a distributive multiplicative action along an injective additive monoid
homomorphism. -/
protected def function.injective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : γ →+ β)
(hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) :
distrib_mul_action α γ :=
{ smul := (•),
smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add],
smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero],
.. hf.mul_action f smul }
/-- Pushforward a distributive multiplicative action along a surjective additive monoid
homomorphism.-/
protected def function.surjective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : β →+ γ)
(hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) :
distrib_mul_action α γ :=
{ smul := (•),
smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩,
simp only [smul_add, ← smul, ← f.map_add] },
smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero],
.. hf.mul_action f smul }
theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 :=
⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩
theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 :=
not_congr u.smul_eq_zero
@[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} :
u • x = 0 ↔ x = 0 :=
exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero
variable (β)
/-- Scalar multiplication by `r` as an `add_monoid_hom`. -/
def const_smul_hom (r : α) : β →+ β :=
{ to_fun := (•) r,
map_zero' := smul_zero r,
map_add' := smul_add r }
variable {β}
@[simp] lemma const_smul_hom_apply (r : α) (x : β) :
const_smul_hom β r x = r • x := rfl
lemma list.smul_sum {r : α} {l : list β} :
r • l.sum = (l.map ((•) r)).sum :=
(const_smul_hom β r).map_list_sum l
end
section
variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β]
lemma multiset.smul_sum {r : α} {s : multiset β} :
r • s.sum = (s.map ((•) r)).sum :=
(const_smul_hom β r).map_multiset_sum s
lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} :
r • ∑ x in s, f x = ∑ x in s, r • f x :=
(const_smul_hom β r).map_sum f s
end
|
bf61081687bb14d0de15a50e74a9631261791b10 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/data/polynomial.lean | f2fd7ff1ca5b4c49e0958b31d8a70daa8013cde1 | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 96,895 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker
Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring.
-/
import data.finsupp algebra.gcd_domain ring_theory.euclidean_domain tactic.ring ring_theory.multiplicity
/-- `polynomial α` is the type of univariate polynomials over `α`.
Polynomials should be seen as (semi-)rings with the additional constructor `X`.
The embedding from α is called `C`. -/
def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α
open finsupp finset lattice
namespace polynomial
universes u v
variables {α : Type u} {β : Type v} {a b : α} {m n : ℕ}
section comm_semiring
variables [comm_semiring α] [decidable_eq α] {p q r : polynomial α}
instance : has_zero (polynomial α) := finsupp.has_zero
instance : has_one (polynomial α) := finsupp.has_one
instance : has_add (polynomial α) := finsupp.has_add
instance : has_mul (polynomial α) := finsupp.has_mul
instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring
instance : decidable_eq (polynomial α) := finsupp.decidable_eq
def polynomial.has_coe_to_fun : has_coe_to_fun (polynomial α) :=
finsupp.has_coe_to_fun
local attribute [instance] finsupp.to_comm_semiring polynomial.has_coe_to_fun
@[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl
/-- `C a` is the constant polynomial `a`. -/
def C (a : α) : polynomial α := single 0 a
/-- `X` is the polynomial variable (aka indeterminant). -/
def X : polynomial α := single 1 1
/-- coeff p n is the coefficient of X^n in p -/
def coeff (p : polynomial α) := p.to_fun
@[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial α) = f := rfl
instance [has_repr α] : has_repr (polynomial α) :=
⟨λ p, if p = 0 then "0"
else (p.support.sort (≤)).foldr
(λ n a, a ++ (if a = "" then "" else " + ") ++
if n = 0
then "C (" ++ repr (coeff p n) ++ ")"
else if n = 1
then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X"
else if (coeff p n) = 1 then "X ^ " ++ repr n
else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩
theorem ext {p q : polynomial α} : p = q ↔ ∀ n, coeff p n = coeff q n :=
⟨λ h n, h ▸ rfl, finsupp.ext⟩
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : polynomial α) : with_bot ℕ := p.support.sup some
def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) :=
inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf)
instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩
/-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/
def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0
lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n
| 0 := (mul_one _).symm
| (n+1) :=
calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one]
... = (C a * X^n) * X : by rw [single_eq_C_mul_X]
... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one]
lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p :=
eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _)
@[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α)
(h_C : ∀a, M (C a))
(h_add : ∀p q, M p → M q → M (p + q))
(h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) :
M p :=
have ∀{n:ℕ} {a}, M (C a * X^n),
begin
assume n a,
induction n with n ih,
{ simp only [pow_zero, mul_one, h_C] },
{ exact h_monomial _ _ ih }
end,
finsupp.induction p
(suffices M (C 0), by simpa only [C, single_zero],
h_C 0)
(assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X],
h_add _ _ this hp)
@[simp] lemma C_0 : C (0 : α) = 0 := single_zero
@[simp] lemma C_1 : C (1 : α) = 1 := rfl
@[simp] lemma C_mul : C (a * b) = C a * C b :=
(@single_mul_single _ _ _ _ _ _ 0 0 a b).symm
@[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add
instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) :=
⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩
@[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _
section coeff
lemma apply_eq_coeff : p n = coeff p n := rfl
@[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial α) n = 0 := rfl
@[simp] lemma coeff_one_zero (n : ℕ) : coeff (1 : polynomial α) 0 = 1 := rfl
@[simp] lemma coeff_add (p q : polynomial α) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl
lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 :=
by simp [coeff, eq_comm, C, single]; congr
@[simp] lemma coeff_C_zero : coeff (C a) 0 = a := rfl
@[simp] lemma coeff_X_one : coeff (X : polynomial α) 1 = 1 := rfl
@[simp] lemma coeff_X_zero : coeff (X : polynomial α) 0 = 0 := rfl
lemma coeff_X : coeff (X : polynomial α) n = if 1 = n then 1 else 0 := rfl
@[simp] lemma coeff_C_mul_X (x : α) (k n : ℕ) :
coeff (C x * X^k : polynomial α) n = if n = k then x else 0 :=
by rw [← single_eq_C_mul_X]; simp [single, eq_comm, coeff]; congr
lemma coeff_sum [comm_semiring β] [decidable_eq β] (n : ℕ) (f : ℕ → α → polynomial β) :
coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply
lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := rfl
@[simp] lemma coeff_C_mul (p : polynomial α) : coeff (C a * p) n = a * coeff p n :=
begin
conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, coeff_sum] },
rw [mul_def, C, sum_single_index],
{ simp [coeff_single, finsupp.mul_sum, coeff_sum],
apply sum_congr rfl,
assume i hi, by_cases i = n; simp [h] },
simp
end
@[simp] lemma coeff_one (n : ℕ) :
coeff (1 : polynomial α) n = if 0 = n then 1 else 0 := rfl
@[simp] lemma coeff_X_pow (k n : ℕ) :
coeff (X^k : polynomial α) n = if n = k then 1 else 0 :=
by simpa only [C_1, one_mul] using coeff_C_mul_X (1:α) k n
lemma coeff_mul_left (p q : polynomial α) (n : ℕ) :
coeff (p * q) n = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) :=
have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0
→ a.1 + a.2 = n, from λ a ha, by_contradiction
(λ h, absurd (eq.refl (0 : α)) (by rwa if_neg h at ha)),
calc coeff (p * q) n = sum (p.support) (λ a, sum (q.support)
(λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) :
by simp only [finsupp.mul_def, coeff_sum, coeff_single]; refl
... = (p.support.product q.support).sum
(λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) :
by rw sum_product
... = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) :
sum_bij_ne_zero (λ a _ _, a.1)
(λ a _ ha, mem_range.2 (nat.lt_succ_of_le (hite a ha ▸ le_add_right (le_refl _))))
(λ a₁ a₂ _ h₁ _ h₂ h, prod.ext h
((add_left_inj a₁.1).1 (by rw [hite a₁ h₁, h, hite a₂ h₂])))
(λ a h₁ h₂, ⟨(a, n - a), mem_product.2
⟨mem_support_iff.2 (ne_zero_of_mul_ne_zero_right h₂),
mem_support_iff.2 (ne_zero_of_mul_ne_zero_left h₂)⟩,
by simpa [nat.add_sub_cancel' (nat.le_of_lt_succ (mem_range.1 h₁))],
rfl⟩)
(λ a _ ha, by rw [← hite a ha, if_pos rfl, nat.add_sub_cancel_left])
lemma coeff_mul_right (p q : polynomial α) (n : ℕ) :
coeff (p * q) n = (range (n+1)).sum (λ k, coeff p (n-k) * coeff q k) :=
by rw [mul_comm, coeff_mul_left]; simp only [mul_comm]
theorem coeff_mul_X_pow (p : polynomial α) (n d : ℕ) :
coeff (p * polynomial.X ^ n) (d + n) = coeff p d :=
begin
rw [coeff_mul_right, sum_eq_single n, coeff_X_pow, if_pos rfl, mul_one, nat.add_sub_cancel],
{ intros b h1 h2, rw [coeff_X_pow, if_neg h2, mul_zero] },
{ exact λ h1, (h1 (mem_range.2 (nat.le_add_left _ _))).elim }
end
theorem coeff_mul_X (p : polynomial α) (n : ℕ) :
coeff (p * X) (n + 1) = coeff p n :=
by simpa only [pow_one] using coeff_mul_X_pow p 1 n
theorem mul_X_pow_eq_zero {p : polynomial α} {n : ℕ}
(H : p * X ^ n = 0) : p = 0 :=
ext.2 $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext.1 H (k+n)
end coeff
lemma C_inj : C a = C b ↔ a = b :=
⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩
section eval₂
variables [semiring β]
variables (f : α → β) (x : β)
open is_semiring_hom
/-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring
to the target and a value `x` for the variable in the target -/
def eval₂ (p : polynomial α) : β :=
p.sum (λ e a, f a * x ^ e)
variables [is_semiring_hom f]
@[simp] lemma eval₂_C : (C a).eval₂ f x = f a :=
(sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one]
@[simp] lemma eval₂_X : X.eval₂ f x = x :=
(sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one]
@[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x :=
finsupp.sum_add_index
(λ _, by rw [map_zero f, zero_mul])
(λ _ _ _, by rw [map_add f, add_mul])
@[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 :=
by rw [← C_1, eval₂_C, map_one f]
instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) :=
⟨eval₂_zero _ _, λ _ _, eval₂_add _ _⟩
end eval₂
section eval₂
variables [comm_semiring β]
variables (f : α → β) [is_semiring_hom f] (x : β)
open is_semiring_hom
@[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x :=
begin
dunfold eval₂,
rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index],
{ apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index],
{ apply sum_congr rfl, assume j hj, dsimp only,
rw [sum_single_index, map_mul f, pow_add],
{ simp only [mul_assoc, mul_left_comm] },
{ rw [map_zero f, zero_mul] } },
{ intro, rw [map_zero f, zero_mul] },
{ intros, rw [map_add f, add_mul] } },
{ intro, rw [map_zero f, zero_mul] },
{ intros, rw [map_add f, add_mul] }
end
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) :=
⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩
lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _
lemma eval₂_sum (p : polynomial α) (g : ℕ → α → polynomial α) (x : β) :
(p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) :=
finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f])
(by intros; simp [right_distrib, is_add_monoid_hom.map_add f])
end eval₂
section eval
variable {x : α}
/-- `eval x p` is the evaluation of the polynomial `p` at `x` -/
def eval : α → polynomial α → α := eval₂ id
@[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _
@[simp] lemma eval_X : X.eval x = x := eval₂_X _ _
@[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _
@[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _
@[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _
@[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _
lemma eval_sum (p : polynomial α) (f : ℕ → α → polynomial α) (x : α) :
(p.sum f).eval x = p.sum (λ n a, (f n a).eval x) :=
eval₂_sum _ _ _ _
lemma eval₂_hom [comm_semiring β] (f : α → β) [is_semiring_hom f] (x : α) :
p.eval₂ f (f x) = f (p.eval x) :=
polynomial.induction_on p
(by simp)
(by simp [is_semiring_hom.map_add f] {contextual := tt})
(by simp [is_semiring_hom.map_mul f, eval_pow,
is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt})
/-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/
def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0
instance : decidable (is_root p a) := by unfold is_root; apply_instance
@[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl
lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} :
is_root q a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero]
lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) :
is_root p a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul]
lemma coeff_zero_eq_eval_zero (p : polynomial α) :
coeff p 0 = p.eval 0 :=
calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp
... = p.eval 0 : eq.symm $
finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp)
end eval
section comp
def comp (p q : polynomial α) : polynomial α := p.eval₂ C q
lemma eval₂_comp [comm_semiring β] (f : α → β) [is_semiring_hom f] {x : β} :
(p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) :=
show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q),
by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl
lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _
@[simp] lemma comp_X : p.comp X = p :=
begin
refine polynomial.ext.2 (λ n, _),
rw [comp, eval₂],
conv in (C _ * _) { rw ← single_eq_C_mul_X },
rw finsupp.sum_single
end
@[simp] lemma X_comp : X.comp p = p := eval₂_X _ _
@[simp] lemma comp_C : p.comp (C a) = C (p.eval a) :=
begin
dsimp [comp, eval₂, eval, finsupp.sum],
rw [← sum_hom (@C α _ _)],
apply finset.sum_congr rfl; simp
end
@[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _
@[simp] lemma comp_zero : p.comp (0 : polynomial α) = C (p.eval 0) :=
by rw [← C_0, comp_C]
@[simp] lemma zero_comp : comp (0 : polynomial α) p = 0 :=
by rw [← C_0, C_comp]
@[simp] lemma comp_one : p.comp 1 = C (p.eval 1) :=
by rw [← C_1, comp_C]
@[simp] lemma one_comp : comp (1 : polynomial α) p = 1 :=
by rw [← C_1, C_comp]
instance : is_semiring_hom (λ q : polynomial α, q.comp p) :=
by unfold comp; apply_instance
@[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _
@[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _
end comp
section map
variables [comm_semiring β] [decidable_eq β]
variables (f : α → β)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : polynomial α → polynomial β := eval₂ (C ∘ f) X
variables [is_semiring_hom f]
@[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _
@[simp] lemma map_X : X.map f = X := eval₂_X _ _
@[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _
@[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _
@[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _
@[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _
instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _
lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _
lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) :=
begin
rw [map, eval₂, coeff_sum],
conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum,
← finset.sum_hom f], },
refine finset.sum_congr rfl (λ x hx, _),
simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f],
split_ifs; simp [is_semiring_hom.map_zero f],
end
lemma map_map {γ : Type*} [comm_semiring γ] [decidable_eq γ] (g : β → γ) [is_semiring_hom g]
(p : polynomial α) : (p.map f).map g = p.map (λ x, g (f x)) :=
polynomial.ext.2 (by simp [coeff_map])
lemma eval₂_map {γ : Type*} [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (x : γ) :
(p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x :=
polynomial.induction_on p
(by simp)
(by simp [is_semiring_hom.map_add f] {contextual := tt})
(by simp [is_semiring_hom.map_mul f,
is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt})
lemma eval_map (x : β) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _
@[simp] lemma map_id : p.map id = p := by simp [id, polynomial.ext, coeff_map]
end map
/-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/
def leading_coeff (p : polynomial α) : α := coeff p (nat_degree p)
/-- a polynomial is `monic` if its leading coefficient is 1 -/
def monic (p : polynomial α) := leading_coeff p = (1 : α)
lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl
instance monic.decidable : decidable (monic p) :=
by unfold monic; apply_instance
@[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl
@[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := rfl
@[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) :=
show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl
lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) :=
by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _]
lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) :=
by rw [← C_1]; exact degree_C_le
lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h;
exact support_eq_empty.1 (max_eq_none.1 h),
λ h, h.symm ▸ rfl⟩
lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) :=
let ⟨n, hn⟩ :=
classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in
have hn : degree p = some n := not_not.1 hn,
by rw [nat_degree, hn]; refl
lemma nat_degree_eq_of_degree_eq_some {p : polynomial α} {n : ℕ}
(h : degree p = n) : nat_degree p = n :=
have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h,
option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n,
by rwa [← degree_eq_nat_degree hp0]
@[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p :=
begin
by_cases hp : p = 0, { rw hp, exact bot_le },
rw [degree_eq_nat_degree hp],
exact le_refl _
end
lemma nat_degree_eq_of_degree_eq [comm_semiring β] [decidable_eq β] {q : polynomial β}
(h : degree p = degree q) : nat_degree p = nat_degree q :=
by unfold nat_degree; rw h
lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p :=
show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ),
from finset.le_sup (finsupp.mem_support_iff.2 h)
lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p :=
begin
rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree],
exact le_degree_of_ne_zero h,
{ assume h, subst h, exact h rfl }
end
lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q :=
begin
by_cases hp : p = 0,
{ rw hp, exact bot_le },
{ rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h }
end
@[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 :=
begin
by_cases ha : a = 0,
{ have : C a = 0, { rw [ha, C_0] },
rw [nat_degree, degree_eq_bot.2 this],
refl },
{ rw [nat_degree, degree_C ha], refl }
end
@[simp] lemma nat_degree_one : nat_degree (1 : polynomial α) = 0 := nat_degree_C 1
@[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n :=
by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl
lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n :=
if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h)
lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 :=
not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h))
lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 :=
coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree)
lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 :=
mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h)))
lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) :=
begin
refine polynomial.ext.2 (λ n, _),
cases n,
{ refl },
{ have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)),
rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] }
end
lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) :=
eq_C_of_degree_le_zero (h ▸ le_refl _)
lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) :=
⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩
lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) :=
calc degree (p + q) = ((p + q).support).sup some : rfl
... ≤ (p.support ∪ q.support).sup some : sup_mono support_add
... = p.support.sup some ⊔ q.support.sup some : sup_union
... = _ : with_bot.sup_eq_max _ _
@[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl
@[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 :=
⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1
(not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)),
λ h, h.symm ▸ leading_coeff_zero⟩
lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ :=
by rw [leading_coeff_eq_zero, degree_eq_bot]
lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q :=
le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $
begin
rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add],
exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h)
end
lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) :
degree (p + q) = max p.degree q.degree :=
le_antisymm (degree_add_le _ _) $
match lt_trichotomy (degree p) (degree q) with
| or.inl hlt :=
by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _
| or.inr (or.inl heq) :=
le_of_not_gt $
assume hlt : max (degree p) (degree q) > degree (p + q),
h $ show leading_coeff p + leading_coeff q = 0,
begin
rw [heq, max_self] at hlt,
rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add],
exact coeff_nat_degree_eq_zero_of_degree_lt hlt
end
| or.inr (or.inr hlt) :=
by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _
end
lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p :=
sup_mono (erase_subset _ _)
lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p :=
lt_of_le_of_ne (degree_erase_le _ _) $
(degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h)
lemma degree_sum_le [decidable_eq β] (s : finset β) (f : β → polynomial α) :
degree (s.sum f) ≤ s.sup (λ b, degree (f b)) :=
finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $
assume a s has ih,
calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) :
by rw sum_insert has; exact degree_add_le _ _
... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih
lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q :=
calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) :
by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _
... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) :
finset.sup_mono_fun (assume i hi, degree_sum_le _ _)
... ≤ degree p + degree q :
begin
refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)),
rw [with_bot.coe_add],
rw mem_support_iff at ha hb,
exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb)
end
lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p)
| 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le
| (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) :
by rw pow_succ; exact degree_mul_le _ _
... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _)
@[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a :=
begin
by_cases ha : a = 0,
{ simp only [ha, C_0, zero_mul, leading_coeff_zero] },
{ rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X],
exact @finsupp.single_eq_same _ _ _ _ _ n a }
end
@[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a :=
suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this,
leading_coeff_monomial a 0
@[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this,
leading_coeff_monomial 1 1
@[simp] lemma monic_X : monic (X : polynomial α) := leading_coeff_X
@[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this,
leading_coeff_monomial 1 0
@[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _
lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) :
leading_coeff (p + q) = leading_coeff q :=
have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h,
by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h),
this, coeff_add, zero_add]
lemma leading_coeff_add_of_degree_eq (h : degree p = degree q)
(hlc : leading_coeff p + leading_coeff q ≠ 0) :
leading_coeff (p + q) = leading_coeff p + leading_coeff q :=
have nat_degree (p + q) = nat_degree p,
by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self],
by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add]
@[simp] lemma coeff_mul_degree_add_degree (p q : polynomial α) :
coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q :=
calc coeff (p * q) (nat_degree p + nat_degree q) =
(range (nat_degree p + nat_degree q + 1)).sum
(λ k, coeff p k * coeff q (nat_degree p + nat_degree q - k)) : coeff_mul_left _ _ _
... = coeff p (nat_degree p) * coeff q (nat_degree p + nat_degree q - nat_degree p) :
finset.sum_eq_single _ (λ n hn₁ hn₂, (le_total n (nat_degree p)).elim
(λ h, have degree q < (nat_degree p + nat_degree q - n : ℕ),
from lt_of_le_of_lt degree_le_nat_degree
(with_bot.coe_lt_coe.2 (nat.lt_sub_left_iff_add_lt.2
(add_lt_add_right (lt_of_le_of_ne h hn₂) _))),
by simp [coeff_eq_zero_of_degree_lt this])
(λ h, have degree p < n, from lt_of_le_of_lt degree_le_nat_degree
(with_bot.coe_lt_coe.2 (lt_of_le_of_ne h hn₂.symm)),
by simp [coeff_eq_zero_of_degree_lt this]))
(λ h, false.elim (h (mem_range.2 (lt_of_le_of_lt (nat.le_add_right _ _) (nat.lt_succ_self _)))))
... = _ : by simp [leading_coeff, nat.add_sub_cancel_left]
lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
degree (p * q) = degree p + degree q :=
have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul],
have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero],
le_antisymm (degree_mul_le _ _)
begin
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq],
refine le_degree_of_ne_zero _,
rwa coeff_mul_degree_add_degree
end
lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
nat_degree (p * q) = nat_degree p + nat_degree q :=
have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]),
have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]),
have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h;
exact h rfl,
option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q,
by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq])
lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
leading_coeff (p * q) = leading_coeff p * leading_coeff q :=
begin
unfold leading_coeff,
rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree],
refl
end
lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 →
leading_coeff (p ^ n) = leading_coeff p ^ n :=
nat.rec_on n (by simp) $
λ n ih h,
have h₁ : leading_coeff p ^ n ≠ 0 :=
λ h₁, h $ by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← ih h₁] at h,
by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁]
lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 →
degree (p ^ n) = add_monoid.smul n (degree p)
| 0 := λ h, by rw [pow_zero, ← C_1] at *;
rw [degree_C h, add_monoid.zero_smul]
| (n+1) := λ h,
have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $
by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← leading_coeff_pow' h₁] at h,
by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁]
lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0 then
if hn0 : n = 0 then by simp *
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else
have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h,
by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h;
exact h rfl,
option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ),
by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0,
← with_bot.coe_smul]; simp
@[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1
| 0 := by simp
| (n+1) :=
if h10 : (1 : α) = 0
then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp
else
have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0,
by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul];
exact h10,
by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul]
lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q :=
if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _
else with_bot.coe_le_coe.1 $
calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm
... ≤ _ : degree_sum_le _ _
... ≤ _ : sup_le (λ n hn,
calc degree (C (coeff p n) * q ^ n)
≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _
... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) :
add_le_add' degree_le_nat_degree (degree_pow_le _ _)
... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) :
add_le_add_left' (add_monoid.smul_le_smul_of_le_right
(@degree_le_nat_degree _ _ _ q) n)
... = (n * nat_degree q : ℕ) :
by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul,
add_monoid.smul_eq_mul]; simp
... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $
mul_le_mul_of_nonneg_right
(le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn))
(nat.zero_le _))
lemma degree_map_le [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] :
degree (p.map f) ≤ degree p :=
if h : p.map f = 0 then by simp [h]
else begin
rw [degree_eq_nat_degree h],
refine le_degree_of_ne_zero (mt (congr_arg f) _),
rw [← coeff_map f, is_semiring_hom.map_zero f],
exact mt leading_coeff_eq_zero.1 h
end
lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) :
(∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) :=
by rw [monic.def, leading_coeff_zero] at h;
exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero],
λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩
lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring β] [decidable_eq β] (f : α → β)
[is_semiring_hom f] (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p :=
le_antisymm (degree_map_le f) $
have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf,
begin
rw [degree_eq_nat_degree hp0],
refine le_degree_of_ne_zero _,
rw [coeff_map], exact hf
end
lemma degree_map_eq_of_injective [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f]
(hf : function.injective f) : degree (p.map f) = degree p :=
if h : p = 0 then by simp [h]
else degree_map_eq_of_leading_coeff_ne_zero _
(by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1
(mt leading_coeff_eq_zero.1 h))
lemma monic_map [comm_semiring β] [decidable_eq β] (f : α → β)
[is_semiring_hom f] (hp : monic p) : monic (p.map f) :=
if h : (0 : β) = 1 then
by haveI := subsingleton_of_zero_eq_one β h;
exact subsingleton.elim _ _
else
have f (leading_coeff p) ≠ 0,
by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm],
by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq
(degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map,
← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f]
lemma zero_le_degree_iff {p : polynomial α} : 0 ≤ degree p ↔ p ≠ 0 :=
by rw [ne.def, ← degree_eq_bot];
cases degree p; exact dec_trivial
@[simp] lemma coeff_mul_X_zero (p : polynomial α) : coeff (p * X) 0 = 0 :=
by rw [coeff_mul_left, sum_range_succ]; simp
instance [subsingleton α] : subsingleton (polynomial α) :=
⟨λ _ _, polynomial.ext.2 (λ _, subsingleton.elim _ _)⟩
lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : α) ≠ 1) :
p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc
lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) :
p = C (p.coeff 1) * X + C (p.coeff 0) :=
polynomial.ext.2 (λ n, nat.cases_on n (by simp)
(λ n, nat.cases_on n (by simp [coeff_C])
(λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial,
by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X,
nat.succ_inj', @eq_comm ℕ 0])))
lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) :
p = C (p.leading_coeff) * X + C (p.coeff 0) :=
(eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans
(by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h])
theorem degree_C_mul_X_pow_le (r : α) (n : ℕ) : degree (C r * X^n) ≤ n :=
begin
rw [← single_eq_C_mul_X],
refine finset.sup_le (λ b hb, _),
rw list.eq_of_mem_singleton (finsupp.support_single_subset hb),
exact le_refl _
end
theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial α) ≤ n :=
by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:α) n
theorem degree_X_le : degree (X : polynomial α) ≤ 1 :=
by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:α) 1
lemma degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α)
{f : α → β} [is_semiring_hom f] (hf : function.injective f) :
degree (p.map f) = degree p :=
degree_map_eq_of_injective _ hf
lemma nat_degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α)
{f : α → β} [is_semiring_hom f] (hf : function.injective f) :
nat_degree (p.map f) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_map' _ hf)
theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p :=
decidable.by_cases
(assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one α $
H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _)
(assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H])
theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) :=
have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)),
monic_of_degree_le (n+1)
(le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1)))
(by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero])
theorem monic_X_add_C (x : α) : monic (X + C x) :=
pow_one (X : polynomial α) ▸ monic_X_pow_add degree_C_le
theorem degree_le_iff_coeff_zero (f : polynomial α) (n : with_bot ℕ) :
degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 :=
⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4,
have H1 : m ∉ f.support,
from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm,
H1 $ (finsupp.mem_support_to_fun f m).2 H4,
λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn,
(finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩
theorem nat_degree_le_of_degree_le {p : polynomial α} {n : ℕ}
(H : degree p ≤ n) : nat_degree p ≤ n :=
show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with
| none, H := zero_le _
| (some d), H := with_bot.coe_le_coe.1 H
end
theorem leading_coeff_mul_X_pow {p : polynomial α} {n : ℕ} :
leading_coeff (p * X ^ n) = leading_coeff p :=
decidable.by_cases
(assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero])
(assume H : leading_coeff p ≠ 0,
by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one];
rwa [leading_coeff_X_pow, mul_one])
lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) :=
if h0 : (0 : α) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0;
exact subsingleton.elim _ _
else
have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0],
by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul]
lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n)
| 0 := monic_one
| (n+1) := monic_mul hp (monic_pow n)
lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p)
(hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q :=
have zn0 : (0 : α) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h;
exact hq (subsingleton.elim _ _),
⟨nat_degree q, λ ⟨r, hr⟩,
have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction,
have hr0 : r ≠ 0, from λ hr0, by simp * at *,
have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1,
by simp [show _ = _, from hmp],
have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0,
from hpn1.symm ▸ zn0.symm,
have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0,
by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1,
one_pow, one_mul, ne.def, hr0]; simp,
have hpn0 : p ^ (nat_degree q + 1) ≠ 0,
from mt leading_coeff_eq_zero.2 $
by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm,
have hnp : 0 < nat_degree p,
by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0];
exact hp,
begin
have := congr_arg nat_degree hr,
rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this,
exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_ge_one_right' (nat.zero_le _) hnp)
(add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this
end⟩
end comm_semiring
section nonzero_comm_semiring
variables [nonzero_comm_semiring α] [decidable_eq α] {p q : polynomial α}
instance : nonzero_comm_semiring (polynomial α) :=
{ zero_ne_one := λ (h : (0 : polynomial α) = 1),
@zero_ne_one α _ $
calc (0 : α) = eval 0 0 : eval_zero.symm
... = eval 0 1 : congr_arg _ h
... = 1 : eval_C,
..polynomial.comm_semiring }
@[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) :=
degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm)
@[simp] lemma degree_X : degree (X : polynomial α) = 1 :=
begin
unfold X degree single finsupp.support,
rw if_neg (zero_ne_one).symm,
refl
end
lemma X_ne_zero : (X : polynomial α) ≠ 0 :=
mt (congr_arg (λ p, coeff p 1)) (by simp)
@[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n
| 0 := by simp only [pow_zero, degree_one]; refl
| (n+1) :=
have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0,
by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul];
exact zero_ne_one.symm,
by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl
@[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) :=
by simpa only [monic, leading_coeff_zero] using zero_ne_one
lemma ne_zero_of_monic (h : monic p) : p ≠ 0 :=
λ h₁, @not_monic_zero α _ _ (h₁ ▸ h)
end nonzero_comm_semiring
section comm_semiring
variables [comm_semiring α] [decidable_eq α] {p q : polynomial α}
/-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`.
It can be used in a semiring where the usual division algorithm is not possible -/
def div_X (p : polynomial α) : polynomial α :=
{ to_fun := λ n, p.coeff (n + 1),
support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1),
multiset.nodup_map_on begin
simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter],
assume x hx y hy hxy,
rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2,
nat.sub_add_cancel hy.2] at hxy
end
(p.support.filter (> 0)).2⟩,
mem_support_to_fun := λ n,
suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔
¬coeff p (n + 1) = 0,
by simpa [finset.mem_def.symm, apply_eq_coeff],
⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1,
λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ }
lemma div_X_mul_X_add (p : polynomial α) : div_X p * X + C (p.coeff 0) = p :=
polynomial.ext.2 $ λ n,
nat.cases_on n
(by simp)
(by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X])
@[simp] lemma div_X_C (a : α) : div_X (C a) = 0 :=
polynomial.ext.2 $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff]
lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) :=
⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p,
λ h, by rw [h, div_X_C]⟩
lemma div_X_add : div_X (p + q) = div_X p + div_X q :=
polynomial.ext.2 $ by simp [div_X]
def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring α :=
{ zero_ne_one := λ h01 : 0 = 1, h $
by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero],
..show comm_semiring α, by apply_instance }
lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree :=
by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact
have leading_coeff p * leading_coeff X ≠ 0, by simpa,
by erw [degree_mul_eq' this, degree_eq_nat_degree hp,
degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe];
exact nat.lt_succ_self _
lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree :=
by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact
calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree :
if h : degree p ≤ 0
then begin
have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h],
rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add],
exact lt_of_le_of_ne lattice.bot_le (ne.symm (mt degree_eq_bot.1 $
by simp [h'])),
end
else
have hXp0 : div_X p ≠ 0,
by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h,
have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa,
have degree (C (p.coeff 0)) < degree (div_X p * X),
from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le
... < 1 : dec_trivial
... = degree (X : polynomial α) : degree_X.symm
... ≤ degree (div_X p * X) :
by rw [← zero_add (degree X), degree_mul_eq' this];
exact add_le_add'
(by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff];
exact λ h0, h (h0.symm ▸ degree_C_le))
(le_refl _),
by rw [add_comm, degree_add_eq_of_degree_lt this];
exact degree_lt_degree_mul_X hXp0
... = p.degree : by rw div_X_mul_X_add
@[elab_as_eliminator] def rec_on_horner
{M : polynomial α → Sort*} : Π (p : polynomial α),
M 0 →
(Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) →
(Π p, p ≠ 0 → M p → M (p * X)) →
M p
| p := λ M0 MC MX,
if hp : p = 0 then eq.rec_on hp.symm M0
else
have wf : degree (div_X p) < degree p,
from degree_div_X_lt hp,
by rw [← div_X_mul_X_add p] at *;
exact
if hcp0 : coeff p 0 = 0
then by rw [hcp0, C_0, add_zero];
exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp)
(rec_on_horner _ M0 MC MX)
else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0
then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0
else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX))
using_well_founded {dec_tac := tactic.assumption}
@[elab_as_eliminator] lemma degree_pos_induction_on
{P : polynomial α → Prop} (p : polynomial α) (h0 : 0 < degree p)
(hC : ∀ {a}, a ≠ 0 → P (C a * X))
(hX : ∀ {p}, 0 < degree p → P p → P (p * X))
(hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p :=
rec_on_horner p
(λ h, by rw degree_zero at h; exact absurd h dec_trivial)
(λ p a _ _ ih h0,
have 0 < degree p,
from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $
by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0),
hadd this (ih this))
(λ p _ ih h0',
if h0 : 0 < degree p
then hX h0 (ih h0)
else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *;
exact hC (λ h : coeff p 0 = 0,
by simpa [h, not_lt.2 (@lattice.bot_le ( ℕ) _ _)] using h0'))
h0
end comm_semiring
section comm_ring
variables [comm_ring α] [decidable_eq α] {p q : polynomial α}
instance : comm_ring (polynomial α) := finsupp.to_comm_ring
instance : has_scalar α (polynomial α) := finsupp.to_has_scalar
-- TODO if this becomes a semimodule then the below lemma could be proved for semimodules
instance : module α (polynomial α) := finsupp.to_module ℕ α
-- TODO -- this is OK for semimodules
@[simp] lemma coeff_smul (p : polynomial α) (r : α) (n : ℕ) :
coeff (r • p) n = r * coeff p n := finsupp.smul_apply
-- TODO -- this is OK for semimodules
lemma C_mul' (a : α) (f : polynomial α) : C a * f = a • f :=
ext.2 $ λ n, coeff_C_mul f
variable (α)
def lcoeff (n : ℕ) : polynomial α →ₗ α :=
{ to_fun := λ f, coeff f n,
add := λ f g, coeff_add f g n,
smul := λ r p, coeff_smul p r n }
variable {α}
@[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial α) : lcoeff α n f = coeff f n := rfl
instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring
@[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C
@[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C
instance eval₂.is_ring_hom {β} [comm_ring β]
(f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) :=
by apply is_ring_hom.of_semiring
instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _
instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β]
(f : α → β) [is_ring_hom f] : is_ring_hom (map f) :=
eval₂.is_ring_hom (C ∘ f)
@[simp] lemma map_sub {β} [comm_ring β] [decidable_eq β]
(f : α → β) [is_ring_hom f] : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _
@[simp] lemma map_neg {β} [comm_ring β] [decidable_eq β]
(f : α → β) [is_ring_hom f] : (-p).map f = -(p.map f) := is_ring_hom.map_neg _
@[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p :=
by unfold degree; rw support_neg
@[simp] lemma coeff_neg (p : polynomial α) (n : ℕ) : coeff (-p) n = -coeff p n := rfl
@[simp] lemma coeff_sub (p q : polynomial α) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl
@[simp] lemma eval₂_neg {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} :
(-p).eval₂ f x = -p.eval₂ f x :=
is_ring_hom.map_neg _
@[simp] lemma eval₂_sub {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} :
(p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x :=
is_ring_hom.map_sub _
@[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x :=
is_ring_hom.map_neg _
@[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x :=
is_ring_hom.map_sub _
lemma degree_sub_lt (hd : degree p = degree q)
(hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) :
degree (p - q) < degree p :=
have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p :=
finsupp.single_add_erase,
have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q :=
finsupp.single_add_erase,
have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd,
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0),
calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) :
by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]}
... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q))
: degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _
... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0
| h := begin
rw [h, monic.def, leading_coeff_zero] at hq,
rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp,
exact hp rfl
end
lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) :
degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p :=
have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2,
have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) *
leading_coeff q ≠ 0,
by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one],
if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0
then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2))
else
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq,
have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1
(by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0];
exact h.1),
degree_sub_lt
(by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2,
degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt])
h.2
(by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one])
def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α},
monic q → polynomial α × polynomial α
| p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then
let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in
have wf : _ := div_wf_lemma h hq,
let dm := div_mod_by_monic_aux (p - z * q) hq in
⟨z + dm.1, dm.2⟩
else ⟨0, p⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/
def div_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0
/-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/
def mod_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).2 else p
infixl ` /ₘ ` : 70 := div_by_monic
infixl ` %ₘ ` : 70 := mod_by_monic
lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q)
(hq0 : q ≠ 0), degree (p %ₘ q) < degree q
| p := λ q hq hq0,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq,
have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q :=
degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q)
hq hq0,
begin
unfold mod_by_monic at this ⊢,
unfold div_mod_by_monic_aux,
rw dif_pos hq at this ⊢,
rw if_pos h,
exact this
end
else
or.cases_on (not_and_distrib.1 h) begin
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h],
exact lt_of_not_ge,
end
begin
assume hp,
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, not_not.1 hp],
exact lt_of_le_of_ne bot_le
(ne.symm (mt degree_eq_bot.1 hq0)),
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q),
p %ₘ q = p - q * (p /ₘ q)
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma h hq,
have ih : _ := mod_by_monic_eq_sub_mul_div
(p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq,
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_pos h],
rw [mod_by_monic, dif_pos hq] at ih,
refine ih.trans _,
unfold div_by_monic,
rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm]
end
else
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero]
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) :
p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq)
@[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 :=
begin
unfold mod_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 :=
begin
unfold div_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h
@[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h
lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq
lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq
lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q :=
⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q :=
⟨λ h, by have := mod_by_monic_add_div p hq;
rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) :
degree q + degree (p /ₘ q) = degree p :=
if hq0 : q = 0 then
have ∀ (p : polynomial α), p = 0,
from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _,
by rw [this (p /ₘ q), this p, this q]; refl
else
have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt],
have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero],
have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) :=
calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0
... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe];
exact nat.le_add_right _ _,
calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc)
... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm
... = _ : congr_arg _ (mod_by_monic_add_div _ hq)
lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p :=
if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl]
else if hq : monic q then
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if h : degree q ≤ degree p
then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))];
exact with_bot.coe_le_coe.2 (nat.le_add_left _ _)
else
by unfold div_by_monic div_mod_by_monic_aux;
simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le]
else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le
lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q)
(hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p :=
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if hpq : degree p < degree q
then begin
rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0],
exact with_bot.bot_lt_some _
end
else begin
rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)],
exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left
(with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q))
end
lemma div_mod_by_monic_unique {f g} (q r : polynomial α) (hg : monic g)
(h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r :=
if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero
(hg0 ▸ hg : monic (0 : polynomial α))).1 _ _
else
have h₁ : r - f %ₘ g = -g * (q - f /ₘ g),
from eq_of_sub_eq_zero
(by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)];
simp [mul_add, mul_comm]),
have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)),
by simp [h₁],
have h₄ : degree (r - f %ₘ g) < degree g,
from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) :
degree_add_le _ _
... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩,
have h₅ : q - (f /ₘ g) = 0,
from by_contradiction
(λ hqf, not_le_of_gt h₄ $
calc degree g ≤ degree g + degree (q - f /ₘ g) :
by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf,
with_bot.coe_le_coe];
exact nat.le_add_right _ _
... = degree (r - f %ₘ g) :
by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]),
⟨eq.symm $ eq_of_sub_eq_zero h₅,
eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩
lemma map_mod_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f :=
if h01 : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h01;
exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩
else
have h01α : (0 : α) ≠ 1, from mt (congr_arg f)
(by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]),
have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q),
from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq)
⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq],
calc _ ≤ degree (p %ₘ q) : degree_map_le _
... < degree q : degree_mod_by_monic_lt _ hq
$ (ne_zero_of_monic_of_zero_ne_one hq h01α)
... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _
(by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩),
⟨this.1.symm, this.2.symm⟩
lemma map_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f :=
(map_mod_div_by_monic f hq).1
lemma map_mod_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) :
(p %ₘ q).map f = p.map f %ₘ q.map f :=
(map_mod_div_by_monic f hq).2
lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p :=
⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add];
exact dvd_mul_right _ _,
λ h, if hq0 : q = 0 then by rw hq0 at hq;
exact (subsingleton_of_monic_zero hq).1 _ _
else
let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in
by_contradiction (λ hpq0,
have hmod : p %ₘ q = q * (r - p /ₘ q) :=
by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr],
have degree (q * (r - p /ₘ q)) < degree q :=
hmod ▸ degree_mod_by_monic_lt _ hq hq0,
have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 :=
λ h, hpq0 $ leading_coeff_eq_zero.1
(by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]),
have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul],
by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this;
exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩
@[simp] lemma mod_by_monic_one (p : polynomial α) : p %ₘ 1 = 0 :=
(dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _)
@[simp] lemma div_by_monic_one (p : polynomial α) : p /ₘ 1 = p :=
by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp
lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p :=
lt_of_not_ge $ λ hlt, begin
have := eq_C_of_degree_le_zero hlt,
rw [is_root, this, eval_C] at h,
exact hp (finsupp.ext (λ n, show coeff p n = 0, from
nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt
(with_bot.coe_lt_coe.2 (nat.succ_pos _)))))),
end
theorem monic_X_sub_C (x : α) : monic (X - C x) :=
by simpa only [C_neg] using monic_X_add_C (-x)
theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) :=
monic_X_pow_add ((degree_neg p).symm ▸ H)
theorem degree_mod_by_monic_le (p : polynomial α) {q : polynomial α}
(hq : monic q) : degree (p %ₘ q) ≤ degree q :=
decidable.by_cases
(assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq;
have : (0:polynomial α) = 1 := (by rw [← C_0, ← C_1, hq]);
rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _)
(assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H)
lemma root_X_sub_C : is_root (X - C a) b ↔ a = b :=
by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm]
def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring α :=
{ zero := 0,
one := 1,
zero_ne_one := λ h01, h $
by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul],
..show comm_ring α, by apply_instance }
end comm_ring
section nonzero_comm_ring
variables [nonzero_comm_ring α] [decidable_eq α] {p q : polynomial α}
instance : nonzero_comm_ring (polynomial α) :=
{ ..polynomial.nonzero_comm_semiring,
..polynomial.comm_ring }
@[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 :=
begin
rw [sub_eq_add_neg, add_comm, ← @degree_X α],
by_cases ha : a = 0,
{ simp only [ha, C_0, neg_zero, zero_add] },
exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial)
end
lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) :
degree ((X : polynomial α) ^ n - C a) = n :=
have degree (-C a) < degree ((X : polynomial α) ^ n),
from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le
... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow];
exact with_bot.coe_lt_coe.2 hn,
by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow]
lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) :
(X : polynomial α) ^ n - C a ≠ 0 :=
mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥,
by rw degree_X_pow_sub_C hn; exact dec_trivial)
end nonzero_comm_ring
section comm_ring
variables [comm_ring α] [decidable_eq α] {p q : polynomial α}
@[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) :=
if h0 : (0 : α) = 1 then by letI := subsingleton_of_zero_eq_one α h0; exact subsingleton.elim _ _
else
by letI : nonzero_comm_ring α := nonzero_comm_ring.of_ne h0; exact
have h : (p %ₘ (X - C a)).eval a = p.eval a :=
by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul,
eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero],
have degree (p %ₘ (X - C a)) < 1 :=
degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸
ne_zero_of_monic (monic_X_sub_C _)),
have degree (p %ₘ (X - C a)) ≤ 0 :=
begin
cases (degree (p %ₘ (X - C a))),
{ exact bot_le },
{ exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) }
end,
begin
rw [eq_C_of_degree_le_zero this, eval_C] at h,
rw [eq_C_of_degree_le_zero this, h]
end
lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a :=
⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul],
λ h : p.eval a = 0,
by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)};
rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩
lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a :=
⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _),
mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h,
λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩
lemma mod_by_monic_X (p : polynomial α) : p %ₘ X = C (p.eval 0) :=
by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero]
section multiplicity
def decidable_dvd_monic (p : polynomial α) (hq : monic q): decidable (q ∣ p) :=
decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq)
local attribute [instance, priority 0] classical.dec
lemma multiplicity_X_sub_C_finite (a : α) (h0 : p ≠ 0) :
multiplicity.finite (X - C a) p :=
multiplicity_finite_of_degree_pos_of_monic
(have (0 : α) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h;
exact h0 (subsingleton.elim _ _)),
by letI : nonzero_comm_ring α := { zero_ne_one := this, ..show comm_ring α, by apply_instance };
rw degree_X_sub_C; exact dec_trivial)
(monic_X_sub_C _) h0
def root_multiplicity (a : α) (p : polynomial α) : ℕ :=
if h0 : p = 0 then 0
else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) :=
λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in
by exactI nat.find (multiplicity_X_sub_C_finite a h0)
lemma root_multiplicity_eq_multiplicity (p : polynomial α) (a : α) :
root_multiplicity a p = if h0 : p = 0 then 0 else
(multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) :=
by simp [multiplicity, root_multiplicity, roption.dom];
congr; funext; congr
lemma pow_root_multiplicity_dvd (p : polynomial α) (a : α) :
(X - C a) ^ root_multiplicity a p ∣ p :=
if h : p = 0 then by simp [h]
else by rw [root_multiplicity_eq_multiplicity, dif_neg h];
exact multiplicity.pow_multiplicity_dvd _
lemma div_by_monic_mul_pow_root_multiplicity_eq
(p : polynomial α) (a : α) :
p /ₘ ((X - C a) ^ root_multiplicity a p) *
(X - C a) ^ root_multiplicity a p = p :=
have monic ((X - C a) ^ root_multiplicity a p),
from monic_pow (monic_X_sub_C _) _,
by conv_rhs { rw [← mod_by_monic_add_div p this,
(dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] };
simp [mul_comm]
lemma eval_div_by_monic_pow_root_multiplicity_ne_zero
{p : polynomial α} (a : α) (hp : p ≠ 0) :
(p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 :=
begin
letI : nonzero_comm_ring α := nonzero_comm_ring.of_polynomial_ne hp,
rw [ne.def, ← is_root.def, ← dvd_iff_is_root],
rintros ⟨q, hq⟩,
have := div_by_monic_mul_pow_root_multiplicity_eq p a,
rw [mul_comm, hq, ← mul_assoc, ← pow_succ',
root_multiplicity_eq_multiplicity, dif_neg hp] at this,
exact multiplicity.is_greatest'
(multiplicity_finite_of_degree_pos_of_monic
(show (0 : with_bot ℕ) < degree (X - C a),
by rw degree_X_sub_C; exact dec_trivial) _ hp)
(nat.lt_succ_self _) (dvd_of_mul_right_eq _ this)
end
end multiplicity
end comm_ring
section integral_domain
variables [integral_domain α] [decidable_eq α] {p q : polynomial α}
@[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q :=
if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add]
else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot]
else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(mt leading_coeff_eq_zero.1 hq0)
@[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) :
degree (p ^ n) = add_monoid.smul n (degree p) :=
by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul],
simp only [*, pow_succ, succ_smul, degree_mul_eq]]
@[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) =
leading_coeff p * leading_coeff q :=
begin
by_cases hp : p = 0,
{ simp only [hp, zero_mul, leading_coeff_zero] },
{ by_cases hq : q = 0,
{ simp only [hq, mul_zero, leading_coeff_zero] },
{ rw [leading_coeff_mul'],
exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } }
end
@[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) :
leading_coeff (p ^ n) = leading_coeff p ^ n :=
by induction n; [simp only [pow_zero, leading_coeff_one],
simp only [*, pow_succ, leading_coeff_mul]]
instance : integral_domain (polynomial α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b,
rw [leading_coeff_zero, eq_comm] at this,
rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
exact eq_zero_or_eq_zero_of_mul_eq_zero this
end,
..polynomial.nonzero_comm_ring }
lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) =
nat_degree p + nat_degree q :=
by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq),
with_bot.coe_add, ← degree_eq_nat_degree hp,
← degree_eq_nat_degree hq, degree_mul_eq]
@[simp] lemma nat_degree_pow_eq (p : polynomial α) (n : ℕ) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0
then if hn0 : n = 0 then by simp [hp0, hn0]
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else nat_degree_pow_eq'
(by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0)
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
by rw [is_root, eval_mul] at h;
exact eq_zero_or_eq_zero_of_mul_eq_zero h
lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) :=
if hp : p = 0 then by simp only [hp, zero_mul, le_refl]
else by rw [degree_mul_eq, degree_eq_nat_degree hp,
degree_eq_nat_degree hq];
exact with_bot.coe_le_coe.2 (nat.le_add_right _ _)
lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0),
∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 :
with_bot.coe_le_coe.2 $ finset.card_insert_le _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add' (le_refl (1 : with_bot ℕ)) htd,
begin
assume y,
rw [mem_insert, htr, eq_comm, ← root_X_sub_C],
conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx},
exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _),
root_or_root_of_root_mul⟩
end⟩
else
⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by simpa only [not_mem_empty, false_iff, not_exists] using h⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a finset containing all the roots of `p` -/
noncomputable def roots (p : polynomial α) : finset α :=
if h : p = 0 then ∅ else classical.some (exists_finset_roots h)
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_finset_roots hp0)).1
end
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _
lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) :
(roots ((X : polynomial α) ^ n - C a)).card ≤ n :=
with_bot.coe_le_coe.1 $
calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ)
≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a)
... = n : degree_X_pow_sub_C hn a
/-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/
noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α :=
by letI := classical.prop_decidable; exact
roots ((X : polynomial α) ^ n - C a)
@[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} :
x ∈ nth_roots n a ↔ x ^ n = a :=
by letI := classical.prop_decidable;
rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a),
is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq]
lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) :
(nth_roots n a).card ≤ n :=
by letI := classical.prop_decidable; exact
if hn : n = 0
then if h : (X : polynomial α) ^ n - C a = 0
then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty]
else with_bot.coe_le_coe.1 (le_trans (card_roots h)
(by rw [hn, pow_zero, ← @C_1 α _ _, ← is_ring_hom.map_sub (@C α _ _)];
exact degree_C_le))
else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a];
exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a)
lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) :
coeff (p.comp q) (nat_degree p * nat_degree q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
if hp0 : p = 0 then by simp [hp0] else
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) :
by rw [comp, eval₂, coeff_sum]
... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) :
finset.sum_eq_single _
begin
assume b hbs hbp,
have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]),
have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff],
dsimp [apply_eq_coeff],
refine coeff_eq_zero_of_degree_lt _,
rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0,
← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id],
exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2
(lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp)
end
(by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero,
classical.not_not]; simp {contextual := tt})
... = _ :
have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p),
by rw [leading_coeff, nat_degree_pow_eq],
by rw [coeff_C_mul, this, leading_coeff_pow]
lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q :=
le_antisymm nat_degree_comp_le
(if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul]
else if hqd0 : nat_degree q = 0
then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree,
by rw [eq_C_of_degree_le_zero this]; simp
else le_nat_degree_of_ne_zero $
have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero],
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= leading_coeff p * leading_coeff q ^ nat_degree p :
coeff_comp_degree_mul_degree hqd0
... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0)))
lemma leading_coeff_comp (hq : nat_degree q ≠ 0): leading_coeff (p.comp q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl
lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 :=
let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in
have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq,
have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq,
have nat_degree (1 : polynomial α) = nat_degree (p * q),
from congr_arg _ hq,
by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm,
add_eq_zero_iff, ← with_bot.coe_eq_coe,
← degree_eq_nat_degree hp0] at this;
exact this.1
@[simp] lemma degree_coe_units (u : units (polynomial α)) :
degree (u : polynomial α) = 0 :=
degree_eq_zero_of_is_unit ⟨u, rfl⟩
@[simp] lemma nat_degree_coe_units (u : units (polynomial α)) :
nat_degree (u : polynomial α) = 0 :=
nat_degree_eq_of_degree_eq_some (degree_coe_units u)
lemma coeff_coe_units_zero_ne_zero (u : units (polynomial α)) :
coeff (u : polynomial α) 0 ≠ 0 :=
begin
conv in (0) {rw [← nat_degree_coe_units u]},
rw [← leading_coeff, ne.def, leading_coeff_eq_zero],
exact units.coe_ne_zero _
end
lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q :=
let ⟨u, hu⟩ := h in by simp [hu.symm]
end integral_domain
section field
variables [discrete_field α] {p q : polynomial α}
instance : vector_space α (polynomial α) :=
{ ..finsupp.to_module ℕ α }
lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 :=
⟨degree_eq_zero_of_is_unit,
λ h, have degree p ≤ 0, by simp [*, le_refl],
have hc : coeff p 0 ≠ 0, from λ hc,
by rw [eq_C_of_degree_le_zero this, hc] at h;
simpa using h,
is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin
conv in p { rw eq_C_of_degree_le_zero this },
rw [← C_mul, _root_.mul_inv_cancel hc, C_1]
end⟩⟩
lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) :
0 < degree p :=
lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp;
exact hp ⟨units.map C (units.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0))), rfl⟩)
lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p :=
⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩,
absurd (congr_arg degree hq) (λ h,
have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm,
nat.with_bot.add_eq_zero_iff] at h; exact h.2,
by simp [degree_mul_eq, this, degree_one, hp1] at h;
exact absurd h dec_trivial)),
λ q r hpqr, begin
have := congr_arg degree hpqr,
rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this,
rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology
end⟩
lemma monic_mul_leading_coeff_inv (h : p ≠ 0) :
monic (p * C (leading_coeff p)⁻¹) :=
by rw [monic, leading_coeff_mul, leading_coeff_C,
mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)]
lemma degree_mul_leading_coeff_inv (p : polynomial α) (h : q ≠ 0) :
degree (p * C (leading_coeff q)⁻¹) = degree p :=
have h₁ : (leading_coeff q)⁻¹ ≠ 0 :=
inv_ne_zero (mt leading_coeff_eq_zero.1 h),
by rw [degree_mul_eq, degree_C h₁, add_zero]
def div (p q : polynomial α) :=
C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹))
def mod (p q : polynomial α) :=
p %ₘ (q * C (leading_coeff q)⁻¹)
private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) :
q * div p q + mod p q = p :=
if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add]
else begin
conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)},
rw [div, mod, add_comm, mul_assoc]
end
private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) :
degree (mod p q) < degree q :=
by rw ← degree_mul_leading_coeff_inv q hq; exact
degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq)
(mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C;
exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq))))
instance : has_div (polynomial α) := ⟨div⟩
instance : has_mod (polynomial α) := ⟨mod⟩
lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl
lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl
lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q :=
show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1]
lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q :=
show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)),
by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one]
lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) :=
mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _
lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a :=
div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root
instance : euclidean_domain (polynomial α) :=
{ quotient := (/),
quotient_zero := by simp [div_def],
remainder := (%),
r := _,
r_well_founded := degree_lt_wf,
quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux,
remainder_lt := λ p q hq, remainder_lt_aux _ hq,
mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) }
lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q :=
⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0,
λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p :=
not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0,
begin
rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)],
unfold div_mod_by_monic_aux,
simp only [this, false_and, if_false]
end⟩
lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q :=
⟨λ h, by have := euclidean_domain.div_add_mod p q;
rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this,
λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹),
by rwa degree_mul_leading_coeff_inv q hq0,
have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0,
by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩
lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) :
degree q + degree (p / q) = degree p :=
have degree (p % q) < degree (q * (p / q)) :=
calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0
... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)),
by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm,
degree_add_eq_of_degree_lt this, degree_mul_eq]}
lemma degree_div_le (p q : polynomial α) : degree (p / q) ≤ degree p :=
if hq : q = 0 then by simp [hq]
else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq];
exact degree_div_by_monic_le _ _
lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p :=
have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq,
by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0];
exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp
(by rw degree_mul_leading_coeff_inv _ hq0; exact hq)
@[simp] lemma degree_map [discrete_field β] (p : polynomial α) (f : α → β) [is_field_hom f] :
degree (p.map f) = degree p :=
degree_map_eq_of_injective _ (is_field_hom.injective f)
@[simp] lemma nat_degree_map [discrete_field β] (f : α → β) [is_field_hom f] :
nat_degree (p.map f) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_map _ f)
@[simp] lemma leading_coeff_map [discrete_field β] (f : α → β) [is_field_hom f] :
leading_coeff (p.map f) = f (leading_coeff p) :=
by simp [leading_coeff, coeff_map f]
lemma map_div [discrete_field β] (f : α → β) [is_field_hom f] :
(p / q).map f = p.map f / q.map f :=
if hq0 : q = 0 then by simp [hq0]
else
by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)];
simp [is_field_hom.map_inv f, leading_coeff, coeff_map f]
lemma map_mod [discrete_field β] (f : α → β) [is_field_hom f] :
(p % q).map f = p.map f % q.map f :=
if hq0 : q = 0 then by simp [hq0]
else by rw [mod_def, mod_def, leading_coeff_map f, ← is_field_hom.map_inv f, ← map_C f,
← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)]
@[simp] lemma map_eq_zero [discrete_field β] (f : α → β) [is_field_hom f] :
p.map f = 0 ↔ p = 0 :=
by simp [polynomial.ext, is_field_hom.map_eq_zero f, coeff_map]
lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x :=
⟨-(p.coeff 0 / p.coeff 1),
have p.coeff 1 ≠ 0,
by rw ← nat_degree_eq_of_degree_eq_some h;
exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h),
by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] };
simp [is_root, mul_div_cancel' _ this]⟩
lemma coeff_inv_units (u : units (polynomial α)) (n : ℕ) :
((↑u : polynomial α).coeff n)⁻¹ = ((↑u⁻¹ : polynomial α).coeff n) :=
begin
rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹),
coeff_C, coeff_C, inv_eq_one_div],
split_ifs,
{ rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero,
coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self];
simp },
{ simp }
end
instance : normalization_domain (polynomial α) :=
{ norm_unit := λ p, if hp0 : p = 0 then 1
else ⟨C p.leading_coeff⁻¹, C p.leading_coeff,
by rw [← C_mul, inv_mul_cancel, C_1];
exact mt leading_coeff_eq_zero.1 hp0,
by rw [← C_mul, mul_inv_cancel, C_1];
exact mt leading_coeff_eq_zero.1 hp0,⟩,
norm_unit_zero := dif_pos rfl,
norm_unit_mul := λ p q hp0 hq0, begin
rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)],
apply units.ext,
show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹,
rw [leading_coeff_mul, mul_inv', C_mul, mul_comm]
end,
norm_unit_coe_units := λ u,
have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩,
begin
apply units.ext,
rw [dif_neg (units.coe_ne_zero u)],
conv_rhs {rw eq_C_of_degree_eq_zero hu},
refine C_inj.2 _,
rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff,
coeff_inv_units],
simp
end,
..polynomial.integral_domain }
lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) :=
show leading_coeff (p * ↑(dite _ _ _)) = 1,
by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0
lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial α) = C p.leading_coeff⁻¹ :=
show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl
end field
section derivative
variables [comm_semiring α] [decidable_eq α]
/-- `derivative p` formal derivative of the polynomial `p` -/
def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1))
lemma coeff_derivative (p : polynomial α) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) :=
begin
rw [derivative],
simp only [coeff_X_pow, coeff_sum, coeff_C_mul],
rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff],
{ rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] },
{ assume b, cases b,
{ intros, rw [nat.cast_zero, mul_zero, zero_mul] },
{ intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } },
{ intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] }
end
@[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 :=
finsupp.sum_zero_index
lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) :=
by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X];
simp only [zero_mul, C_0]; refl
@[simp] lemma derivative_C {a : α} : derivative (C a) = 0 :=
suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0,
by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero],
derivative_monomial a 0
@[simp] lemma derivative_X : derivative (X : polynomial α) = 1 :=
suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ 0,
by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero],
derivative_monomial 1 1
@[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 :=
derivative_C
@[simp] lemma derivative_add {f g : polynomial α} :
derivative (f + g) = derivative f + derivative g :=
by refine finsupp.sum_add_index _ _; intros;
simp only [add_mul, zero_mul, C_0, C_add, C_mul]
instance : is_add_monoid_hom (derivative : polynomial α → polynomial α) :=
by refine_struct {..}; simp
@[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} :
derivative (s.sum f) = s.sum (λb, derivative (f b)) :=
(finset.sum_hom derivative).symm
@[simp] lemma derivative_mul {f g : polynomial α} :
derivative (f * g) = derivative f * g + f * derivative g :=
calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) :
begin
transitivity, exact derivative_sum,
transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum },
apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm,
transitivity,
{ apply congr_arg, exact single_eq_C_mul_X },
exact derivative_monomial _ _
end
... = f.sum (λn a, g.sum (λm b,
(C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) :
sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm,
by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul];
cases n; simp only [nat.succ_sub_succ, pow_zero];
cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero,
nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm]
... = derivative f * g + f * derivative g :
begin
conv { to_rhs, congr,
{ rw [← sum_C_mul_X_eq g] },
{ rw [← sum_C_mul_X_eq f] } },
unfold derivative finsupp.sum,
simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul]
end
lemma derivative_eval (p : polynomial α) (x : α) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) :=
by simp [derivative, eval_sum, eval_pow]
end derivative
section domain
variables [integral_domain α] [decidable_eq α]
lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) :
n ∈ (derivative p).support ↔ n + 1 ∈ p.support :=
suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : α) = 0)) ↔ coeff p (n + 1) ≠ 0,
by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero],
by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false]
@[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) :
degree (derivative p) = (nat_degree p - 1 : ℕ) :=
le_antisymm
(le_trans (degree_sum_le _ _) $ sup_le $ assume n hn,
have n ≤ nat_degree p, begin
rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree],
{ refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn },
{ assume h, simpa only [h, support_zero] using hn }
end,
le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _)
begin
refine le_sup _,
rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff],
{ show ¬ leading_coeff p = 0,
rw [leading_coeff_eq_zero],
assume h, rw [h, nat_degree_zero] at hp,
exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), },
exact hp
end
end domain
section identities
/- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials.
These belong somewhere else. But not in group_power because they depend on tactic.ring
Maybe use data.nat.choose to prove it.
-/
def pow_add_expansion {α : Type*} [comm_semiring α] (x y : α) : ∀ (n : ℕ),
{k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2}
| 0 := ⟨0, by simp⟩
| 1 := ⟨0, by simp⟩
| (n+2) :=
begin
cases pow_add_expansion (n+1) with z hz,
rw [_root_.pow_succ, hz],
existsi (x*z + (n+1)*x^n+z*y),
simp [_root_.pow_succ],
ring -- expensive!
end
variables [comm_ring α] [decidable_eq α]
private def poly_binom_aux1 (x y : α) (e : ℕ) (a : α) :
{k : α // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} :=
begin
existsi (pow_add_expansion x y e).val,
congr,
apply (pow_add_expansion _ _ _).property
end
private lemma poly_binom_aux2 (f : polynomial α) (x y : α) :
f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) :=
begin
unfold eval eval₂, congr, ext,
apply (poly_binom_aux1 x y _ _).property
end
private lemma poly_binom_aux3 (f : polynomial α) (x y : α) : f.eval (x + y) =
f.sum (λ e a, a * x^e) +
f.sum (λ e a, (a * e * x^(e-1)) * y) +
f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) :=
by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc]
def binom_expansion (f : polynomial α) (x y : α) :
{k : α // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} :=
begin
existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)),
rw poly_binom_aux3,
congr,
{ rw derivative_eval, symmetry,
apply finsupp.sum_mul },
{ symmetry, apply finsupp.sum_mul }
end
def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z : α // x^i - y^i = z*(x - y)}
| 0 := ⟨0, by simp⟩ --sorry --false.elim $ not_lt_of_ge h zero_lt_one
| 1 := ⟨1, by simp⟩
| (k+2) :=
begin
cases pow_sub_pow_factor with z hz,
existsi z*x + y^(k+1),
rw [_root_.pow_succ x, _root_.pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)),
←mul_sub x, hz],
simp only [_root_.pow_succ],
ring
end
def eval_sub_factor (f : polynomial α) (x y : α) :
{z : α // f.eval x - f.eval y = z*(x - y)} :=
begin
existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val),
unfold eval eval₂,
rw [←finsupp.sum_sub],
have : finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val) * (x - y) =
finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val * (x - y)),
{ apply finsupp.sum_mul },
rw this,
congr, ext e a,
rw [mul_assoc, ←(pow_sub_pow_factor x y).property],
simp [left_distrib]
end
end identities
end polynomial
|
b90285bce969ca6335a48324a3a6797bf90ea05d | a537b538f2bea3181e24409d8a52590603d1ddd9 | /src/tidy/rewrite_search/tactic.lean | 41ff0af92b9059341812dc2962dcf5994b6b3fad | [] | no_license | rwbarton/lean-tidy | 6134813ded72b275d19d4d32514dba80c21708e3 | fe1125d32adb60decda7a77d0f679614ba9f6fbb | refs/heads/master | 1,585,549,718,705 | 1,538,120,619,000 | 1,538,120,624,000 | 150,864,330 | 0 | 0 | null | 1,538,225,790,000 | 1,538,225,790,000 | null | UTF-8 | Lean | false | false | 3,605 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Keeley Hoek, Scott Morrison
import .init
import .discovery
import tidy.lib.list
open tactic
variables {α β γ δ : Type}
namespace tidy.rewrite_search
meta def try_search (cfg : rewrite_search_config α β γ δ) (prog : discovery.progress) (rs : list (expr × bool)) (eqn : sided_pair expr) : tactic (option string) := do
i ← try_mk_search_instance cfg prog rs eqn,
match i with
| none := return none
| some i := do
(i, result) ← i.search_until_solved,
match result with
| search_result.failure reason := fail reason
| search_result.success proof steps := do
exact proof,
some <$> i.explain proof steps
end
end
meta def rewrite_search_pair (cfg : rewrite_search_config α β γ δ) (prog : discovery.progress) (rs : list (expr × bool)) (eqn : sided_pair expr) := do
result ← try_search cfg prog rs eqn,
match result with
| some str := return str
| none := do
trace "\nError initialising rewrite_search instance, falling back to emergency config!",
result ← try_search (mk_fallback_config cfg) prog rs eqn,
match result with
| some str := return str
| none := fail "Could not initialise emergency rewrite_search instance!"
end
end
-- TODO If try_search fails due to a failure to init any of the tracer, metric, or strategy we try again
-- using the "fallback" default versions of all three of these. Instead we could be more thoughtful,
-- and try again only replacing the failing one of these with its respective fallback module version.
meta def rewrite_search_target (cfg : rewrite_search_config α β γ δ) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr × bool)) : tactic string := do
t ← target,
if t.has_meta_var then
fail "rewrite_search is not suitable for goals containing metavariables"
else skip,
let per := if cfg.help_me then discovery.persistence.try_everything else per,
(prog, rws) ← discovery.collect use_suggest_annotations per cfg.suggest extra_names,
let rws := rws ++ extra_rws,
if cfg.trace_rules then
do rs_strings ← pp_rules rws,
trace ("rewrite_search using:\n---\n" ++ (string.intercalate "\n" rs_strings) ++ "\n---")
else skip,
match t with
| `(%%lhs = %%rhs) := rewrite_search_pair cfg prog rws ⟨lhs, rhs⟩
| `(%%lhs ↔ %%rhs) := rewrite_search_pair cfg prog rws ⟨lhs, rhs⟩
| _ := fail "target is not an equation or iff"
end
end tidy.rewrite_search
namespace tactic.interactive
open interactive
open tidy.rewrite_search tidy.rewrite_search.discovery.persistence
meta def rewrite_search (cfg : rewrite_search_config α β γ δ . pick_default_config) : tactic string :=
rewrite_search_target cfg tt try_everything [] []
meta def rewrite_search_using (as : list name) (cfg : rewrite_search_config α β γ δ . pick_default_config) : tactic string := do
extra_names ← discovery.load_attr_list as,
rewrite_search_target cfg ff try_bundles extra_names []
meta def rewrite_search_with (rs : parse rw_rules) (cfg : rewrite_search_config α β γ δ . pick_default_config) : tactic string := do
extra_rws ← discovery.rewrite_list_from_rw_rules rs,
rewrite_search_target cfg ff speedy [] extra_rws
-- @Scott should we still do this?
-- exprs ← close_under_apps exprs, -- TODO don't do this for everything, it's too expensive: only for specially marked lemmas
end tactic.interactive
|
a89227ed0cb768f3340ef874d47a1297f041b435 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/order/bounded_lattice.lean | 4df0b13738cc4f977444a1665a3ec7bce0a7adf7 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 38,857 | 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
Defines bounded lattice type class hierarchy.
Includes the Prop and fun instances.
-/
import order.lattice
import data.option.basic
import tactic.pi_instances
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
attribute [pattern] has_bot.bot has_top.top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- An `order_top` is a partial order with a maximal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
end prio
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_antisymm le_top h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
assume h, lt_irrefl a (lt_of_le_of_lt le_top h)
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff,
by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)]
end
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
assume ha, hb $ top_unique $ ha ▸ hab
end order_top
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- An `order_bot` is a partial order with a minimal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
end prio
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
le_antisymm h bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
assume h, lt_irrefl a (lt_of_lt_of_le h bot_le)
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
assume ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)]
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
end order_bot
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
end prio
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
end prio
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
end prio
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
end prio
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/- Bounded lattices -/
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
end prio
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α
end prio
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨assume : a ⊓ b = ⊥,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [this, inf_le_right],
assume : a ≤ c,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this }
... = ⊥ : h₂⟩
/- Prop instance -/
instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop :=
{ le := λa b, a → b,
le_refl := assume _, id,
le_trans := assume a b c f g, g ∘ f,
le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := assume a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := assume a b c H, classical.or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := assume a Ha, true.intro,
bot := false,
bot_le := @false.elim }
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∧ q x) :=
assume a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∨ q x) :=
assume a b h, or.imp (m_p h) (m_q h)
end logic
/- Function lattices -/
instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) :=
⟨λ f g i, f i ⊔ g i⟩
@[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) :
(f ⊔ g) i = f i ⊔ g i :=
rfl
instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) :=
⟨λ f g i, f i ⊓ g i⟩
@[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) :
(f ⊓ g) i = f i ⊓ g i :=
rfl
instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) :=
⟨λ i, ⊥⟩
@[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) :
(⊥ : Π i, α i) i = ⊥ :=
rfl
instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) :=
⟨λ i, ⊤⟩
@[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) :
(⊤ : Π i, α i) i = ⊤ :=
rfl
instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] :
semilattice_sup (Π i, α i) :=
by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] :
semilattice_inf (Π i, α i) :=
by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] :
semilattice_inf_bot (Π i, α i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] :
semilattice_inf_top (Π i, α i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] :
semilattice_sup_bot (Π i, α i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] :
semilattice_sup_top (Π i, α i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) :=
{ .. pi.semilattice_sup, .. pi.semilattice_inf }
instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] :
bounded_lattice (Π i, α i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [partial_order α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [partial_order α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
instance linear_order [linear_order α] : linear_order (with_bot α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end,
..with_bot.partial_order }
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) :=
{ decidable_le := λ a b, begin
cases a with a,
{ exact is_true bot_le },
cases b with b,
{ exact is_false (mt (le_antisymm bot_le) (by simp)) },
{ exact decidable_of_iff _ some_le_some }
end,
..with_bot.linear_order }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
theorem lattice_eq_DLO [decidable_linear_order α] :
lattice_of_decidable_linear_order = @with_bot.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ assume a b,
match a, b with
| a, none := assume h : a < ⊥, (not_lt_bot h).elim
| none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem none_le [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem none_lt_some [has_lt α] {a : α} :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [partial_order α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ :=
lt_of_le_of_ne le_top (λ h, option.no_confusion h)
lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance linear_order [linear_order α] : linear_order (with_top α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end,
..with_top.partial_order }
instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) :=
{ decidable_le := λ a b, begin
cases b with b,
{ exact is_true le_top },
cases a with a,
{ exact is_false (mt (le_antisymm le_top) (by simp)) },
{ exact decidable_of_iff _ some_le_some }
end,
..with_top.linear_order }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
theorem lattice_eq_DLO [decidable_linear_order α] :
lattice_of_decidable_linear_order = @with_top.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ assume a b,
match a, b with
| none, a := assume h : ⊤ < a, (not_top_lt h).elim
| some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
namespace subtype
/-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/
protected def semilattice_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} :=
{ sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩,
le_sup_left := λ x y, @le_sup_left _ _ (x : α) y,
le_sup_right := λ x y, @le_sup_right _ _ (x : α) y,
sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/
protected def semilattice_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} :=
{ inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩,
inf_le_left := λ x y, @inf_le_left _ _ (x : α) y,
inf_le_right := λ x y, @inf_le_right _ _ (x : α) y,
le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/
protected def lattice [lattice α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) :
lattice {x : α // P x} :=
{ ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := assume a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := assume a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
section disjoint
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm {a b : α} : disjoint a b → disjoint b a :=
disjoint.comm.1
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
end disjoint
/-!
### `is_compl` predicate
-/
/-- Two elements `x` and `y` are complements of each other if
`x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
⟨λ hz, h.disjoint.mono_left hz,
λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
disjoint_iff.trans h.inf_left_eq_bot_iff
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
|
bc7961493a531c16f07a9f8b78c7085b9b18d2c9 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/tactic/lint.lean | 1c36de17fd6edecd344da84db4f4e50146757d30 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 25,364 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis
-/
import tactic.core
/-!
# lint command
This file defines the following user commands to spot common mistakes in the code.
* `#lint`: check all declarations in the current file
* `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects,
and also excluding the current file)
* `#lint_all`: check all declarations in the environment (the current file and all
imported files)
The following linters are run by default:
1. `unused_arguments` checks for unused arguments in declarations.
2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma.
3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration.
4. `illegal_constant` checks whether ≥/> is used in the declaration.
5. `instance_priority` checks that instances that always apply have priority below default.
6. `doc_blame` checks for missing doc strings on definitions and constants.
Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems.
This is not run by default.
The command `#list_linters` prints a list of the names of all available linters.
You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4).
You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint
that suppresses the output of passing checks.
A silent lint will fail if any test fails.
You can append a sequence of linter names to any command to run extra tests, in addition to the
default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`.
You can append `only name1 name2 ...` to any command to run a subset of linters, e.g.
`#lint only unused_arguments`
You can add custom linters by defining a term of type `linter` in the `linter` namespace.
A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check`
or `lint only my_new_check`.
If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default.
Adding the attribute `@[nolint]` to a declaration omits it from all linter checks.
## Tags
sanity check, lint, cleanup, command, tactic
-/
universe variable u
open expr tactic native
reserve notation `#lint`
reserve notation `#lint_mathlib`
reserve notation `#lint_all`
reserve notation `#list_linters`
run_cmd tactic.skip -- apparently doc strings can't come directly after `reserve notation`
/-- Defines the user attribute `nolint` for skipping `#lint` -/
@[user_attribute]
meta def nolint_attr : user_attribute :=
{ name := "nolint",
descr := "Do not report this declaration in any of the tests of `#lint`" }
attribute [nolint] imp_intro
classical.dec classical.dec_pred classical.dec_rel classical.dec_eq
/--
A linting test for the `#lint` command.
`test` defines a test to perform on every declaration. It should never fail. Returning `none`
signifies a passing test. Returning `some msg` reports a failing test with error `msg`.
`no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed
when at least one test is positive.
If `is_fast` is false, this test will be omitted from `#lint-`.
-/
meta structure linter :=
(test : declaration → tactic (option string))
(no_errors_found : string)
(errors_found : string)
(is_fast : bool := tt)
/-- Takes a list of names that resolve to declarations of type `linter`,
and produces a list of linters. -/
meta def get_linters (l : list name) : tactic (list linter) :=
l.mmap (λ n, mk_const n >>= eval_expr linter <|> fail format!"invalid linter: {n}")
/-- Defines the user attribute `linter` for adding a linter to the default set.
Linters should be defined in the `linter` namespace.
A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace)
when used in `#lint`.
-/
@[user_attribute]
meta def linter_attr : user_attribute unit unit :=
{ name := "linter",
descr := "Use this declaration as a linting test in #lint",
after_set := some $ λ nm _ _,
mk_const nm >>= infer_type >>= unify `(linter) }
setup_tactic_parser
universe variable v
/-- Find all declarations in `l` where tac returns `some x` and list them. -/
meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) :
tactic (list (declaration × α)) :=
l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d
/-- Find all declarations in `l` where tac returns `some x` and sort the resulting list by file name. -/
meta def fold_over_with_cond_sorted {α} (l : list declaration)
(tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do
e ← get_env,
ds ← fold_over_with_cond l tac,
let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).iget, x))),
return $ ds₂.to_list
/-- Make the output of `fold_over_with_cond` printable, in the following form:
`#print <name> <open multiline comment> <elt of α> <close multiline comment>` -/
meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format :=
ds.foldl
(λ f x, f ++ "\n" ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " /- " ++ to_fmt x.2 ++ " -/")
format.nil
/-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/
meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) :
format :=
ds.foldl
(λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2)
format.nil
/-- Same as `print_decls_sorted`, but removing the first `n` characters from the string.
Useful for omitting the mathlib directory from the output. -/
meta def print_decls_sorted_mathlib {α} [has_to_format α] (n : ℕ)
(ds : list (string × list (declaration × α))) : format :=
ds.foldl
(λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt (x.1.popn n) ++ print_decls x.2)
format.nil
/-- Auxilliary definition for `check_unused_arguments` -/
meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e :=
if n > n_max then l else
if ¬ is_lambda e ∧ ¬ is_pi e then l else
let b := e.binding_body in
let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b
/-- Check which arguments of a declaration are not used.
Prints a list of natural numbers corresponding to which arguments are not used (e.g.
this outputs [1, 4] if the first and fourth arguments are unused).
Checks both the type and the value of `d` for whether the argument is used
(in rare cases an argument is used in the type but not in the value).
We return [] if the declaration was automatically generated.
We print arguments that are larger than the arity of the type of the declaration
(without unfolding definitions). -/
meta def check_unused_arguments (d : declaration) : option (list ℕ) :=
let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in
if l = [] then none else
let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in
(l.filter $ λ n, n ∈ l2).reverse
/-- Check for unused arguments, and print them with their position, variable name, type and whether
the argument is a duplicate.
See also `check_unused_arguments`.
This tactic additionally filters out all unused arguments of type `parse _` -/
meta def unused_arguments (d : declaration) : tactic (option string) := do
let ns := check_unused_arguments d,
if ¬ ns.is_some then return none else do
let ns := ns.iget,
(ds, _) ← get_pi_binders d.type,
let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)),
let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []),
if ns = [] then return none else do
ds' ← ds.mmap pp,
ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++
(if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b),
return $ some $ ns.to_string_aux tt
/-- A linter object for checking for unused arguments. This is in the default linter set. -/
@[linter, priority 1500] meta def linter.unused_arguments : linter :=
{ test := unused_arguments,
no_errors_found := "No unused arguments",
errors_found := "UNUSED ARGUMENTS" }
/-- Checks whether the correct declaration constructor (definition or theorem) by comparing it
to its sort. Instances will not be printed. -/
/- This test is not very quick: maybe we can speed-up testing that something is a proposition?
This takes almost all of the execution time. -/
meta def incorrect_def_lemma (d : declaration) : tactic (option string) :=
if d.is_constant ∨ d.is_axiom
then return none else do
is_instance_d ← is_instance d.to_name,
if is_instance_d then return none else do
-- the following seems to be a little quicker than `is_prop d.type`.
expr.sort n ← infer_type d.type, return $
if d.is_theorem ↔ n = level.zero then none
else if (d.is_definition : bool) then "is a def, should be a lemma/theorem"
else "is a lemma/theorem, should be a def"
/-- A linter for checking whether the correct declaration constructor (definition or theorem)
has been used. -/
@[linter, priority 1490] meta def linter.def_lemma : linter :=
{ test := incorrect_def_lemma,
no_errors_found := "All declarations correctly marked as def/lemma",
errors_found := "INCORRECT DEF/LEMMA" }
/-- Checks whether a declaration has a namespace twice consecutively in its name -/
meta def dup_namespace (d : declaration) : tactic (option string) :=
is_instance d.to_name >>= λ is_inst,
return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none
else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in
some $ "The namespace `" ++ s ++ "` is duplicated in the name"
/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/
@[linter, priority 1480] meta def linter.dup_namespace : linter :=
{ test := dup_namespace,
no_errors_found := "No declarations have a duplicate namespace",
errors_found := "DUPLICATED NAMESPACES IN NAME" }
/-- Checks whether a `>`/`≥` is used in the statement of `d`. -/
-- TODO: the commented out code also checks for classicality in statements, but needs fixing
-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _
-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=
-- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧
-- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge])
-- then
-- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq],
-- illegal2 := [`gt, `ge],
-- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)),
-- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in
-- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++
-- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++
-- (if occur2 = [] then "" else " Use ≤/< instead.")
-- else none
meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=
return $ let illegal := [`gt, `ge] in if d.type.contains_constant (λ n, n ∈ illegal)
then some "the type contains ≥/>. Use ≤/< instead."
else none
/-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/
@[linter, priority 1470] meta def linter.illegal_constants : linter :=
{ test := illegal_constants_in_statement,
no_errors_found := "No illegal constants in declarations",
errors_found := "ILLEGAL CONSTANTS IN DECLARATIONS",
is_fast := ff }
library_note "nolint_ge" "Currently, the linter forbids the use of `>` and `≥` in definitions and
statements, as they cause problems in rewrites. However, we still allow them in some contexts,
for instance when expressing properties of the operator (as in `cobounded (≥)`), or in quantifiers
such as `∀ ε > 0`. Such statements should be marked with the attribute `nolint` to avoid linter
failures."
/-- checks whether an instance that always applies has priority ≥ 1000. -/
-- TODO: instance_priority should also be tested on automatically-generated declarations
meta def instance_priority (d : declaration) : tactic (option string) := do
let nm := d.to_name,
b ← is_instance nm,
/- return `none` if `d` is not an instance -/
if ¬ b then return none else do
prio ← has_attribute `instance nm,
/- return `none` if `d` is has low priority -/
if prio < 1000 then return none else do
let (fn, args) := d.type.pi_codomain.get_app_fn_args,
cls ← get_decl fn.const_name,
let (pi_args, _) := cls.type.pi_binders,
guard (args.length = pi_args.length),
/- List all the arguments of the class that block type-class inference from firing
(if they are metavariables). These are all the arguments except instance-arguments and
out-params. -/
let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩,
if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param
then none else some e,
let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup,
if always_applies then return $ some "set priority below 1000" else return none
library_note "lower instance priority"
"Certain instances always apply during type-class resolution. For example, the instance
`add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class
resolution problems of the form `add_group _`, and type-class inference will then do an
exhaustive search to find a commutative group. These instances take a long time to fail.
Other instances will only apply if the goal has a certain shape. For example
`int.add_group : add_group ℤ` or
`add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances
will fail quickly, and when they apply, they are almost the desired instance.
For this reason, we want the instances of the second type (that only apply in specific cases) to
always have higher priority than the instances of the first type (that always apply).
See also #1561.
Therefore, if we create an instance that always applies, we set the priority of these instances to
100 (or something similar, which is below the default value of 1000)."
library_note "default priority"
"Instances that always apply should be applied after instances that only apply in specific cases,
see note [lower instance priority] above.
Classes that use the `extends` keyword automatically generate instances that always apply.
Therefore, we set the priority of these instances to 100 (or something similar, which is below the
default value of 1000) using `set_option default_priority 100`.
We have to put this option inside a section, so that the default priority is the default
1000 outside the section."
/-- A linter object for checking instance priorities of instances that always apply.
This is in the default linter set. -/
@[linter, priority 1460] meta def linter.instance_priority : linter :=
{ test := instance_priority,
no_errors_found := "All instance priorities are good",
errors_found := "DANGEROUS INSTANCE PRIORITIES.\nThe following instances always apply, and therefore should have a priority < 1000.\nIf you don't know what priority to choose, use priority 100." }
/-- Reports definitions and constants that are missing doc strings -/
meta def doc_blame_report_defn : declaration → tactic (option string)
| (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string"
| (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string"
| _ := return none
/-- Reports definitions and constants that are missing doc strings -/
meta def doc_blame_report_thm : declaration → tactic (option string)
| (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string"
| _ := return none
/-- A linter for checking definition doc strings -/
@[linter, priority 1450] meta def linter.doc_blame : linter :=
{ test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none),
no_errors_found := "No definitions are missing documentation.",
errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" }
/-- A linter for checking theorem doc strings. This is not in the default linter set. -/
meta def linter.doc_blame_thm : linter :=
{ test := doc_blame_report_thm,
no_errors_found := "No theorems are missing documentation.",
errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS",
is_fast := ff }
/-- `get_checks slow extra use_only` produces a list of linters.
`extras` is a list of names that should resolve to declarations with type `linter`.
If `use_only` is true, it only uses the linters in `extra`.
Otherwise, it uses all linters in the environment tagged with `@[linter]`.
If `slow` is false, it only uses the fast default tests. -/
meta def get_checks (slow : bool) (extra : list name) (use_only : bool) :
tactic (list linter) := do
default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters,
let default := if slow then default else default.filter (λ l, l.is_fast),
list.append default <$> get_linters extra
/-- If `verbose` is true, return `old ++ new`, else return `old`. -/
private meta def append_when (verbose : bool) (old new : format) : format :=
cond verbose (old ++ new) old
private meta def check_fold (printer : (declaration → tactic (option string)) → tactic (name_set × format))
(verbose : bool) : name_set × format → linter → tactic (name_set × format)
| (ns, s) ⟨tac, ok_string, warning_string, _⟩ :=
do (new_ns, f) ← printer tac,
if f.is_nil then return $ (ns, append_when verbose s format!"/- OK: {ok_string}. -/\n")
else return $ (ns.union new_ns, s ++ format!"/- {warning_string}: -/" ++ f ++ "\n\n")
/-- The common denominator of `#lint[|mathlib|all]`.
The different commands have different configurations for `l`, `printer` and `where_desc`.
If `slow` is false, doesn't do the checks that take a lot of time.
If `verbose` is false, it will suppress messages from passing checks.
By setting `checks` you can customize which checks are performed.
Returns a `name_set` containing the names of all declarations that fail any check in `check`,
and a `format` object describing the failures. -/
meta def lint_aux (l : list declaration)
(printer : (declaration → tactic (option string)) → tactic (name_set × format))
(where_desc : string) (slow verbose : bool) (checks : list linter) : tactic (name_set × format) := do
let s : format := append_when verbose format.nil "/- Note: This command is still in development. -/\n",
let s := append_when verbose s format!"/- Checking {l.length} declarations {where_desc} -/\n\n",
(ns, s) ← checks.mfoldl (check_fold printer verbose) (mk_name_set, s),
return $ (ns, if slow then s else append_when verbose s "/- (slow tests skipped) -/\n")
/-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/
meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
l ← e.mfilter (λ d,
if e.in_current_file' d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
lint_aux l (λ t, do lst ← fold_over_with_cond l t, return
(name_set.of_list (lst.map (declaration.to_name ∘ prod.fst)), print_decls lst))
"in the current file" slow verbose checks
private meta def name_list_of_decl_lists (l : list (string × list (declaration × string))) :
name_set :=
name_set.of_list $ list.join $ l.map $ λ ⟨_, l'⟩, l'.map $ declaration.to_name ∘ prod.fst
/-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/
meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
ml ← get_mathlib_dir,
/- note: we don't separate out some of these tests in `lint_aux` because that causes a
performance hit. That is also the reason for the current formulation using if then else. -/
l ← e.mfilter (λ d,
if e.is_prefix_of_file ml d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
let ml' := ml.length,
lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t,
return (name_list_of_decl_lists lst, print_decls_sorted_mathlib ml' lst))
"in mathlib (only in imported files)" slow verbose checks
/-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/
meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
l ← e.mfilter (λ d, if ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t,
return (name_list_of_decl_lists lst, print_decls_sorted lst))
"in all imported files (including this one)" slow verbose checks
/-- Parses an optional `only`, followed by a sequence of zero or more identifiers.
Prepends `linter.` to each of these identifiers. -/
private meta def parse_lint_additions : parser (bool × list name) :=
prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*)
/-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/
private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) :
parser unit :=
do silent ← optional (tk "-"),
fast_only ← optional (tk "*"),
silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *-
(use_only, extra) ← parse_lint_additions,
(_, s) ← scope fast_only.is_none silent.is_none extra use_only,
when (¬ s.is_nil) $ do
trace s,
when silent.is_some $ fail "Linting did not succeed"
/-- The command `#lint` at the bottom of a file will warn you about some common mistakes
in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`.
`#lint-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit :=
lint_cmd_aux @lint
/-- The command `#lint_mathlib` checks all of mathlib for certain mistakes.
Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`.
`#lint_mathlib-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit :=
lint_cmd_aux @lint_mathlib
/-- The command `#lint_all` checks all imported files for certain mistakes.
Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`.
`#lint_all-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit :=
lint_cmd_aux @lint_all
/-- The command `#list_linters` prints a list of all available linters. -/
@[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit :=
do env ← get_env,
let ns := env.decl_filter_map $ λ dcl,
if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none,
trace "Available linters:\n linters marked with (*) are in the default lint set\n",
ns.mmap' $ λ n, do
b ← has_attribute' `linter n,
trace $ n.pop_prefix.to_string ++ if b then " (*)" else ""
/-- Use `lint` as a hole command. Note: In a large file, there might be some delay between
choosing the option and the information appearing -/
@[hole_command] meta def lint_hole_cmd : hole_command :=
{ name := "Lint",
descr := "Lint: Find common mistakes in current file.",
action := λ es, do (_, s) ← lint, return [(s.to_string,"")] }
/-- Tries to apply the `nolint` attribute to a list of declarations. Always succeeds, even if some
of the declarations don't exist. -/
meta def apply_nolint_tac (decls : list name) : tactic unit :=
decls.mmap' (λ d, try (nolint_attr.set d () tt))
/-- `apply_nolint id1 id2 ...` tries to apply the `nolint` attribute to `id1`, `id2`, ...
It will always succeed, even if some of the declarations do not exist. -/
@[user_command] meta def apply_nolint_cmd (_ : parse $ tk "apply_nolint") : parser unit :=
ident_* >>= ↑apply_nolint_tac
|
75bf4a05d68b981ed82eb8f065acb9833b45cd03 | 193da933cf42f2f9188bb47e3c973205bc2abc5c | /AA_Algebras/02_dm_nat/dm_nat_test.lean | d43a15892a3ca9f4aaa0e957558f59ac03cafded | [] | no_license | pandaman64/cs-dm | aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3 | bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c | refs/heads/master | 1,647,620,340,607 | 1,570,055,187,000 | 1,570,055,187,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,151 | lean | inductive natural : Type
| O: natural
| S: natural -> natural
-- discuss semantics of this definition
--- injectivity
--- smallest set closed under finite squences of applications of constructors
--- the set of terms generated by all finite sequences of applications of the constructors
open natural
#check O
#check S O
#check S (S O)
#check S (S (S O))
-- etc.
-- abstraction
def zero_nat (n: natural): natural :=
O
-- abstraction
def succ_nat (n: natural): natural :=
S n
#eval succ_nat (S (S O)) -- KEVIN: raw rep
def pred_nat (n: natural): natural :=
match n with
| O := O -- discuss: partial functions, being closed / totality
| S n' := n'
end
#eval pred_nat (S (S (S O))) -- KEVIN: raw rep
def plus_natural: natural -> natural -> natural -- KEVIN: Introduce → types in very first unit
| O n2 := n2
| (S n1') n2 := S (plus_natural n1' n2)
def mult_natural: natural -> natural -> natural -- KEVIN: Introduce → types in very first unit
| O n2 := O
| (S n1') n2 := plus_natural n2 (mult_natural n1' n2)
#eval mult_natural (S (S O)) (S (S (S O)))
-- HOMEWORK: minus, exponentiate |
b7823b8a1637b623a9bf1d3472da4db6fee67a5a | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/nat/order/basic.lean | e1a9995b9225f6eb5e22a61cddd1f9214d2d0e01 | [
"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 | 24,580 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import algebra.order.ring.canonical
import data.nat.basic
/-!
# The natural numbers as a linearly ordered commutative semiring
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We also have a variety of lemmas which have been deferred from `data.nat.basic` because it is
easier to prove them with this ordered semiring instance available.
You may find that some theorems can be moved back to `data.nat.basic` by modifying their proofs.
-/
universes u v
/-! ### instances -/
instance nat.order_bot : order_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le }
instance : linear_ordered_comm_semiring ℕ :=
{ lt := nat.lt,
add_le_add_left := @nat.add_le_add_left,
le_of_add_le_add_left := @nat.le_of_add_le_add_left,
zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0),
mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right,
decidable_eq := nat.decidable_eq,
exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩,
..nat.comm_semiring, ..nat.linear_order }
instance : linear_ordered_comm_monoid_with_zero ℕ :=
{ mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h,
..nat.linear_ordered_comm_semiring,
..(infer_instance : comm_monoid_with_zero ℕ)}
/-! Extra instances to short-circuit type class resolution and ensure computability -/
-- Not using `infer_instance` avoids `classical.choice` in the following two
instance : linear_ordered_semiring ℕ := infer_instance
instance : strict_ordered_semiring ℕ := infer_instance
instance : strict_ordered_comm_semiring ℕ := infer_instance
instance : ordered_semiring ℕ := strict_ordered_semiring.to_ordered_semiring'
instance : ordered_comm_semiring ℕ := strict_ordered_comm_semiring.to_ordered_comm_semiring'
instance : linear_ordered_cancel_add_comm_monoid ℕ := infer_instance
instance : canonically_ordered_comm_semiring ℕ :=
{ exists_add_of_le := λ a b h, (nat.le.dest h).imp $ λ _, eq.symm,
le_self_add := nat.le_add_right,
eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, nat.eq_zero_of_mul_eq_zero,
.. nat.nontrivial,
.. nat.order_bot,
.. (infer_instance : ordered_add_comm_monoid ℕ),
.. (infer_instance : linear_ordered_semiring ℕ),
.. (infer_instance : comm_semiring ℕ) }
instance : canonically_linear_ordered_add_monoid ℕ :=
{ .. (infer_instance : canonically_ordered_add_monoid ℕ),
.. nat.linear_order }
variables {m n k l : ℕ}
namespace nat
/-! ### Equalities and inequalities involving zero and one -/
lemma one_le_iff_ne_zero : 1 ≤ n ↔ n ≠ 0 :=
(show 1 ≤ n ↔ 0 < n, from iff.rfl).trans pos_iff_ne_zero
lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := dec_trivial
protected theorem mul_ne_zero (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0
| nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0
@[simp] protected theorem mul_eq_zero : m * n = 0 ↔ m = 0 ∨ n = 0 :=
iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt})
@[simp] protected theorem zero_eq_mul : 0 = m * n ↔ m = 0 ∨ n = 0 :=
by rw [eq_comm, nat.mul_eq_zero]
lemma eq_zero_of_double_le (h : 2 * n ≤ n) : n = 0 :=
add_right_eq_self.mp $ le_antisymm ((two_mul n).symm.trans_le h) le_add_self
lemma eq_zero_of_mul_le (hb : 2 ≤ n) (h : n * m ≤ m) : m = 0 :=
eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h
lemma zero_max : max 0 n = n := max_eq_right (zero_le _)
@[simp] lemma min_eq_zero_iff : min m n = 0 ↔ m = 0 ∨ n = 0 :=
begin
split,
{ intro h,
cases le_total m n with H H,
{ simpa [H] using or.inl h },
{ simpa [H] using or.inr h } },
{ rintro (rfl|rfl);
simp }
end
@[simp] lemma max_eq_zero_iff : max m n = 0 ↔ m = 0 ∧ n = 0 :=
begin
split,
{ intro h,
cases le_total m n with H H,
{ simp only [H, max_eq_right] at h,
exact ⟨le_antisymm (H.trans h.le) (zero_le _), h⟩ },
{ simp only [H, max_eq_left] at h,
exact ⟨h, le_antisymm (H.trans h.le) (zero_le _)⟩ } },
{ rintro ⟨rfl, rfl⟩,
simp }
end
lemma add_eq_max_iff : m + n = max m n ↔ m = 0 ∨ n = 0 :=
begin
rw ←min_eq_zero_iff,
cases le_total m n with H H;
simp [H]
end
lemma add_eq_min_iff : m + n = min m n ↔ m = 0 ∧ n = 0 :=
begin
rw ←max_eq_zero_iff,
cases le_total m n with H H;
simp [H]
end
lemma one_le_of_lt (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h
theorem eq_one_of_mul_eq_one_right (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩
theorem eq_one_of_mul_eq_one_left (H : m * n = 1) : n = 1 :=
eq_one_of_mul_eq_one_right (by rwa mul_comm)
/-! ### `succ` -/
lemma two_le_iff : ∀ n, 2 ≤ n ↔ n ≠ 0 ∧ n ≠ 1
| 0 := by simp
| 1 := by simp
| (n+2) := by simp
@[simp] lemma lt_one_iff {n : ℕ} : n < 1 ↔ n = 0 :=
lt_succ_iff.trans nonpos_iff_eq_zero
/-! ### `add` -/
theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n :=
calc
m + n > 0 + n : nat.add_lt_add_right h n
... = n : nat.zero_add n
... ≥ 0 : zero_le n
theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n :=
begin rw add_comm, exact add_pos_left h m end
theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n :=
iff.intro
begin
intro h,
cases m with m,
{simp [zero_add] at h, exact or.inr h},
exact or.inl (succ_pos _)
end
begin
intro h, cases h with mpos npos,
{ apply add_pos_left mpos },
apply add_pos_right _ npos
end
lemma add_eq_one_iff : m + n = 1 ↔ m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 :=
by cases n; simp [succ_eq_add_one, ← add_assoc, succ_inj']
lemma add_eq_two_iff : m + n = 2 ↔ m = 0 ∧ n = 2 ∨ m = 1 ∧ n = 1 ∨ m = 2 ∧ n = 0 :=
by cases n; simp [(succ_ne_zero 1).symm, succ_eq_add_one, ← add_assoc, succ_inj', add_eq_one_iff]
lemma add_eq_three_iff :
m + n = 3 ↔ m = 0 ∧ n = 3 ∨ m = 1 ∧ n = 2 ∨ m = 2 ∧ n = 1 ∨ m = 3 ∧ n = 0 :=
by cases n; simp [(succ_ne_zero 1).symm, succ_eq_add_one, ← add_assoc, succ_inj', add_eq_two_iff]
theorem le_add_one_iff : m ≤ n + 1 ↔ m ≤ n ∨ m = n + 1 :=
⟨λ h,
match nat.eq_or_lt_of_le h with
| or.inl h := or.inr h
| or.inr h := or.inl $ nat.le_of_succ_le_succ h
end,
or.rec (λ h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩
lemma le_and_le_add_one_iff : n ≤ m ∧ m ≤ n + 1 ↔ m = n ∨ m = n + 1 :=
begin
rw [le_add_one_iff, and_or_distrib_left, ←le_antisymm_iff, eq_comm, and_iff_right_of_imp],
rintro rfl,
exact n.le_succ
end
lemma add_succ_lt_add (hab : m < n) (hcd : k < l) : m + k + 1 < n + l :=
begin
rw add_assoc,
exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd)
end
/-! ### `pred` -/
lemma pred_le_iff : pred m ≤ n ↔ m ≤ succ n :=
⟨le_succ_of_pred_le, by { cases m, { exact λ _, zero_le n }, exact le_of_succ_le_succ }⟩
/-! ### `sub`
Most lemmas come from the `has_ordered_sub` instance on `ℕ`. -/
instance : has_ordered_sub ℕ :=
begin
constructor,
intros m n k,
induction n with n ih generalizing k,
{ simp },
{ simp only [sub_succ, add_succ, succ_add, ih, pred_le_iff] }
end
lemma lt_pred_iff : n < pred m ↔ succ n < m := show n < m - 1 ↔ n + 1 < m, from lt_tsub_iff_right
lemma lt_of_lt_pred (h : m < n - 1) : m < n := lt_of_succ_lt (lt_pred_iff.1 h)
lemma le_or_le_of_add_eq_add_pred (h : k + l = m + n - 1) : m ≤ k ∨ n ≤ l :=
begin
cases le_or_lt m k with h' h'; [left, right],
{ exact h' },
{ replace h' := add_lt_add_right h' l, rw h at h',
cases n.eq_zero_or_pos with hn hn, { rw hn, exact zero_le l },
rw [m.add_sub_assoc hn, add_lt_add_iff_left] at h',
exact nat.le_of_pred_lt h' },
end
/-- A version of `nat.sub_succ` in the form `_ - 1` instead of `nat.pred _`. -/
lemma sub_succ' (m n : ℕ) : m - n.succ = m - n - 1 := rfl
/-! ### `mul` -/
lemma mul_eq_one_iff : ∀ {m n : ℕ}, m * n = 1 ↔ m = 1 ∧ n = 1
| 0 0 := dec_trivial
| 0 1 := dec_trivial
| 1 0 := dec_trivial
| (m+2) 0 := by simp
| 0 (n+2) := by simp
| (m+1) (n+1) := ⟨
λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one,
(add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2],
λ h, by simp only [h, mul_one]⟩
lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn
theorem mul_self_le_mul_self (h : m ≤ n) : m * m ≤ n * n := mul_le_mul h h (zero_le _) (zero_le _)
theorem mul_self_lt_mul_self : Π {m n : ℕ}, m < n → m * m < n * n
| 0 n h := mul_pos h h
| (succ m) n h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _)
theorem mul_self_le_mul_self_iff : m ≤ n ↔ m * m ≤ n * n :=
⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩
theorem mul_self_lt_mul_self_iff : m < n ↔ m * m < n * n :=
le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff
theorem le_mul_self : Π (n : ℕ), n ≤ n * n
| 0 := le_rfl
| (n+1) := by simp
lemma le_mul_of_pos_left (h : 0 < n) : m ≤ n * m :=
begin
conv {to_lhs, rw [← one_mul(m)]},
exact mul_le_mul_of_nonneg_right h.nat_succ_le dec_trivial,
end
lemma le_mul_of_pos_right (h : 0 < n) : m ≤ m * n :=
begin
conv {to_lhs, rw [← mul_one(m)]},
exact mul_le_mul_of_nonneg_left h.nat_succ_le dec_trivial,
end
theorem mul_self_inj : m * m = n * n ↔ m = n :=
le_antisymm_iff.trans (le_antisymm_iff.trans
(and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm
lemma le_add_pred_of_pos (n : ℕ) {i : ℕ} (hi : i ≠ 0) : n ≤ i + (n - 1) :=
begin
refine le_trans _ (add_tsub_le_assoc),
simp [add_comm, nat.add_sub_assoc, one_le_iff_ne_zero.2 hi]
end
@[simp] theorem lt_mul_self_iff : ∀ {n : ℕ}, n < n * n ↔ 1 < n
| 0 := iff_of_false (lt_irrefl _) zero_le_one.not_lt
| (n + 1) := lt_mul_iff_one_lt_left n.succ_pos
/-!
### Recursion and induction principles
This section is here due to dependencies -- the lemmas here require some of the lemmas
proved above, and some of the results in later sections depend on the definitions in this section.
-/
/-- Given a predicate on two naturals `P : ℕ → ℕ → Prop`, `P a b` is true for all `a < b` if
`P (a + 1) (a + 1)` is true for all `a`, `P 0 (b + 1)` is true for all `b` and for all
`a < b`, `P (a + 1) b` is true and `P a (b + 1)` is true implies `P (a + 1) (b + 1)` is true. -/
@[elab_as_eliminator]
lemma diag_induction (P : ℕ → ℕ → Prop) (ha : ∀ a, P (a + 1) (a + 1)) (hb : ∀ b, P 0 (b + 1))
(hd : ∀ a b, a < b → P (a + 1) b → P a (b + 1) → P (a + 1) (b + 1)) :
∀ a b, a < b → P a b
| 0 (b + 1) h := hb _
| (a + 1) (b + 1) h :=
begin
apply hd _ _ ((add_lt_add_iff_right _).1 h),
{ have : a + 1 = b ∨ a + 1 < b,
{ rwa [← le_iff_eq_or_lt, ← nat.lt_succ_iff] },
rcases this with rfl | _,
{ exact ha _ },
apply diag_induction (a + 1) b this },
apply diag_induction a (b + 1),
apply lt_of_le_of_lt (nat.le_succ _) h,
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ p, p.1 + p.2.1)⟩] }
/-- A subset of `ℕ` containing `k : ℕ` and closed under `nat.succ` contains every `n ≥ k`. -/
lemma set_induction_bounded {S : set ℕ} (hk : k ∈ S) (h_ind: ∀ k : ℕ, k ∈ S → k + 1 ∈ S)
(hnk : k ≤ n) : n ∈ S :=
@le_rec_on (λ n, n ∈ S) k n hnk h_ind hk
/-- A subset of `ℕ` containing zero and closed under `nat.succ` contains all of `ℕ`. -/
lemma set_induction {S : set ℕ} (hb : 0 ∈ S) (h_ind: ∀ k : ℕ, k ∈ S → k + 1 ∈ S) (n : ℕ) : n ∈ S :=
set_induction_bounded hb h_ind (zero_le n)
/-! ### `div` -/
protected lemma div_le_of_le_mul' (h : m ≤ k * n) : m / k ≤ n :=
(nat.eq_zero_or_pos k).elim
(λ k0, by rw [k0, nat.div_zero]; apply zero_le)
(λ k0, (mul_le_mul_left k0).1 $
calc k * (m / k)
≤ m % k + k * (m / k) : nat.le_add_left _ _
... = m : mod_add_div _ _
... ≤ k * n : h)
protected lemma div_le_self' (m n : ℕ) : m / n ≤ m :=
(nat.eq_zero_or_pos n).elim
(λ n0, by rw [n0, nat.div_zero]; apply zero_le)
(λ n0, nat.div_le_of_le_mul' $ calc
m = 1 * m : (one_mul _).symm
... ≤ n * m : nat.mul_le_mul_right _ n0)
protected lemma div_lt_of_lt_mul (h : m < n * k) : m / n < k :=
lt_of_mul_lt_mul_left
(calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _
... = m : mod_add_div _ _
... < n * k : h)
(nat.zero_le n)
lemma eq_zero_of_le_div (hn : 2 ≤ n) (h : m ≤ m / n) : m = 0 :=
eq_zero_of_mul_le hn $
by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hn)).1 h
lemma div_mul_div_le_div (m n k : ℕ) : ((m / k) * n) / m ≤ n / k :=
if hm0 : m = 0 then by simp [hm0]
else calc m / k * n / m ≤ n * m / k / m :
nat.div_le_div_right (by rw [mul_comm];
exact mul_div_le_mul_div_assoc _ _ _)
... = n / k : by rw [nat.div_div_eq_div_mul, mul_comm n, mul_comm k,
nat.mul_div_mul _ _ (nat.pos_of_ne_zero hm0)]
lemma eq_zero_of_le_half (h : n ≤ n / 2) : n = 0 := eq_zero_of_le_div le_rfl h
lemma mul_div_mul_comm_of_dvd_dvd (hmk : k ∣ m) (hnl : l ∣ n) : m * n / (k * l) = m / k * (n / l) :=
begin
rcases k.eq_zero_or_pos with rfl | hk0, { simp },
rcases l.eq_zero_or_pos with rfl | hl0, { simp },
obtain ⟨_, rfl⟩ := hmk,
obtain ⟨_, rfl⟩ := hnl,
rw [mul_mul_mul_comm, nat.mul_div_cancel_left _ hk0, nat.mul_div_cancel_left _ hl0,
nat.mul_div_cancel_left _ (mul_pos hk0 hl0)]
end
lemma le_half_of_half_lt_sub {a b : ℕ} (h : a / 2 < a - b) : b ≤ a / 2 :=
begin
rw nat.le_div_iff_mul_le two_pos,
rw [nat.div_lt_iff_lt_mul two_pos, nat.mul_sub_right_distrib, lt_tsub_iff_right,
mul_two a] at h,
exact le_of_lt (nat.lt_of_add_lt_add_left h)
end
lemma half_le_of_sub_le_half {a b : ℕ} (h : a - b ≤ a / 2) : a / 2 ≤ b :=
begin
rw [nat.le_div_iff_mul_le two_pos, nat.mul_sub_right_distrib, tsub_le_iff_right,
mul_two, add_le_add_iff_left] at h,
rw [← nat.mul_div_left b two_pos],
exact nat.div_le_div_right h,
end
/-! ### `mod`, `dvd` -/
lemma two_mul_odd_div_two (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 :=
by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, add_tsub_cancel_left]}
lemma div_dvd_of_dvd (h : n ∣ m) : (m / n) ∣ m := ⟨n, (nat.div_mul_cancel h).symm⟩
protected lemma div_div_self (h : n ∣ m) (hm : m ≠ 0) : m / (m / n) = n :=
begin
rcases h with ⟨_, rfl⟩,
rw mul_ne_zero_iff at hm,
rw [mul_div_right _ (nat.pos_of_ne_zero hm.1), mul_div_left _ (nat.pos_of_ne_zero hm.2)]
end
lemma mod_mul_right_div_self (m n k : ℕ) : m % (n * k) / n = (m / n) % k :=
begin
rcases nat.eq_zero_or_pos n with rfl|hn, { simp },
rcases nat.eq_zero_or_pos k with rfl|hk, { simp },
conv_rhs { rw ← mod_add_div m (n * k) },
rw [mul_assoc, add_mul_div_left _ _ hn, add_mul_mod_self_left,
mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hn hk)))]
end
lemma mod_mul_left_div_self (m n k : ℕ) : m % (k * n) / n = (m / n) % k :=
by rw [mul_comm k, mod_mul_right_div_self]
lemma not_dvd_of_pos_of_lt (h1 : 0 < n) (h2 : n < m) : ¬ m ∣ n :=
begin
rintros ⟨k, rfl⟩,
rcases nat.eq_zero_or_pos k with (rfl | hk),
{ exact lt_irrefl 0 h1 },
{ exact not_lt.2 (le_mul_of_pos_right hk) h2 },
end
/-- If `m` and `n` are equal mod `k`, `m - n` is zero mod `k`. -/
lemma sub_mod_eq_zero_of_mod_eq (h : m % k = n % k) : (m - n) % k = 0 :=
by rw [←nat.mod_add_div m k, ←nat.mod_add_div n k, ←h, tsub_add_eq_tsub_tsub, add_tsub_cancel_left,
←mul_tsub, nat.mul_mod_right]
@[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1)
lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) :=
⟨k / n, tsub_eq_of_eq_add_rev (nat.mod_add_div k n).symm⟩
lemma add_mod_eq_ite :
(m + n) % k = if k ≤ m % k + n % k then m % k + n % k - k else m % k + n % k :=
begin
cases k, { simp },
rw nat.add_mod,
split_ifs with h,
{ rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt],
exact (tsub_lt_iff_right h).mpr
(nat.add_lt_add (m.mod_lt k.zero_lt_succ) (n.mod_lt k.zero_lt_succ)) },
{ exact nat.mod_eq_of_lt (lt_of_not_ge h) }
end
lemma div_mul_div_comm (hmn : n ∣ m) (hkl : l ∣ k) : (m / n) * (k / l) = (m * k) / (n * l) :=
have exi1 : ∃ x, m = n * x, from hmn,
have exi2 : ∃ y, k = l * y, from hkl,
if hn : n = 0 then by simp [hn]
else have 0 < n, from nat.pos_of_ne_zero hn,
if hl : l = 0 then by simp [hl]
else have 0 < l, from nat.pos_of_ne_zero hl,
begin
cases exi1 with x hx, cases exi2 with y hy,
rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left],
symmetry,
apply nat.div_eq_of_eq_mul_left,
apply mul_pos,
repeat {assumption},
cc
end
lemma div_eq_self : m / n = m ↔ m = 0 ∨ n = 1 :=
begin
split,
{ intro,
cases n,
{ simp * at * },
{ cases n,
{ right, refl },
{ left,
have : m / (n + 2) ≤ m / 2 := div_le_div_left (by simp) dec_trivial,
refine eq_zero_of_le_half _,
simp * at * } } },
{ rintros (rfl|rfl); simp }
end
lemma div_eq_sub_mod_div : m / n = (m - m % n) / n :=
begin
by_cases n0 : n = 0,
{ rw [n0, nat.div_zero, nat.div_zero] },
{ rw [← mod_add_div m n] { occs := occurrences.pos [2] },
rw [add_tsub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] }
end
/-- `m` is not divisible by `n` if it is between `n * k` and `n * (k + 1)` for some `k`. -/
lemma not_dvd_of_between_consec_multiples (h1 : n * k < m) (h2 : m < n * (k + 1)) : ¬ n ∣ m :=
begin
rintro ⟨d, rfl⟩,
exact monotone.ne_of_lt_of_lt_nat (covariant.monotone_of_const n) k h1 h2 d rfl
end
/-! ### `find` -/
section find
variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q]
@[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 :=
by rw [pos_iff_ne_zero, ne, nat.find_eq_zero]
lemma find_add {hₘ : ∃ m, p (m + n)} {hₙ : ∃ n, p n} (hn : n ≤ nat.find hₙ) :
nat.find hₘ + n = nat.find hₙ :=
begin
refine ((le_find_iff _ _).2 (λ m hm hpm, hm.not_le _)).antisymm _,
{ have hnm : n ≤ m := hn.trans (find_le hpm),
refine add_le_of_le_tsub_right_of_le hnm (find_le _),
rwa tsub_add_cancel_of_le hnm },
{ rw ←tsub_le_iff_right,
refine (le_find_iff _ _).2 (λ m hm hpm, hm.not_le _),
rw tsub_le_iff_right,
exact find_le hpm }
end
end find
/-! ### `find_greatest` -/
section find_greatest
variables {P Q : ℕ → Prop} [decidable_pred P]
lemma find_greatest_eq_iff :
nat.find_greatest P k = m ↔ m ≤ k ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ k → ¬P n) :=
begin
induction k with k ihk generalizing m,
{ rw [eq_comm, iff.comm],
simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero],
rintro rfl,
exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ },
{ by_cases hk : P (k + 1),
{ rw [find_greatest_eq hk], split,
{ rintro rfl,
exact ⟨le_rfl, λ _, hk, λ n hlt hle, (hlt.not_le hle).elim⟩ },
{ rintros ⟨hle, h0, hm⟩,
rcases decidable.eq_or_lt_of_le hle with rfl|hlt,
exacts [rfl, (hm hlt le_rfl hk).elim] } },
{ rw [find_greatest_of_not hk, ihk],
split,
{ rintros ⟨hle, hP, hm⟩,
refine ⟨hle.trans k.le_succ, hP, λ n hlt hle, _⟩,
rcases decidable.eq_or_lt_of_le hle with rfl|hlt',
exacts [hk, hm hlt $ lt_succ_iff.1 hlt'] },
{ rintros ⟨hle, hP, hm⟩,
refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans k.le_succ)⟩,
rintro rfl,
exact hk (hP k.succ_ne_zero) } } }
end
lemma find_greatest_eq_zero_iff : nat.find_greatest P k = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ k → ¬P n :=
by simp [find_greatest_eq_iff]
lemma find_greatest_spec (hmb : m ≤ n) (hm : P m) : P (nat.find_greatest P n) :=
begin
by_cases h : nat.find_greatest P n = 0,
{ cases m, { rwa h },
exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim },
{ exact (find_greatest_eq_iff.1 rfl).2.1 h }
end
lemma find_greatest_le (n : ℕ) : nat.find_greatest P n ≤ n := (find_greatest_eq_iff.1 rfl).1
lemma le_find_greatest (hmb : m ≤ n) (hm : P m) : m ≤ nat.find_greatest P n :=
le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm
lemma find_greatest_mono_right (P : ℕ → Prop) [decidable_pred P] : monotone (nat.find_greatest P) :=
begin
refine monotone_nat_of_le_succ (λ n, _),
rw [find_greatest_succ],
split_ifs,
{ exact (find_greatest_le n).trans (le_succ _) },
{ refl }
end
lemma find_greatest_mono_left [decidable_pred Q] (hPQ : P ≤ Q) :
nat.find_greatest P ≤ nat.find_greatest Q :=
begin
intro n,
induction n with n hn,
{ refl },
by_cases P (n + 1),
{ rw [find_greatest_eq h, find_greatest_eq (hPQ _ h)] },
{ rw find_greatest_of_not h,
exact hn.trans (nat.find_greatest_mono_right _ $ le_succ _) }
end
lemma find_greatest_mono [decidable_pred Q] (hPQ : P ≤ Q) (hmn : m ≤ n) :
nat.find_greatest P m ≤ nat.find_greatest Q n :=
(nat.find_greatest_mono_right _ hmn).trans $ find_greatest_mono_left hPQ _
lemma find_greatest_is_greatest (hk : nat.find_greatest P n < k) (hkb : k ≤ n) : ¬ P k :=
(find_greatest_eq_iff.1 rfl).2.2 hk hkb
lemma find_greatest_of_ne_zero (h : nat.find_greatest P n = m) (h0 : m ≠ 0) : P m :=
(find_greatest_eq_iff.1 h).2.1 h0
end find_greatest
/-! ### `bit0` and `bit1` -/
protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h
protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h)
theorem bit_le : ∀ (b : bool) {m n : ℕ}, m ≤ n → bit b m ≤ bit b n
| tt _ _ h := nat.bit1_le h
| ff _ _ h := nat.bit0_le h
theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n
| tt _ _ h := le_of_lt $ nat.bit0_lt_bit1 h
| ff _ _ h := nat.bit0_le h
theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n
| ff _ _ h := le_of_lt $ nat.bit0_lt_bit1 h
| tt _ _ h := nat.bit1_le h
theorem bit_lt_bit0 : ∀ (b) {m n : ℕ}, m < n → bit b m < bit0 n
| tt _ _ h := nat.bit1_lt_bit0 h
| ff _ _ h := nat.bit0_lt h
theorem bit_lt_bit (a b) (h : m < n) : bit a m < bit b n :=
lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ le_rfl)
@[simp] lemma bit0_le_bit1_iff : bit0 m ≤ bit1 n ↔ m ≤ n :=
⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq,
bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩
@[simp] lemma bit0_lt_bit1_iff : bit0 m < bit1 n ↔ m ≤ n :=
⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩
@[simp] lemma bit1_le_bit0_iff : bit1 m ≤ bit0 n ↔ m < n :=
⟨λ h, by rwa [m.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h,
λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩
@[simp] lemma bit1_lt_bit0_iff : bit1 m < bit0 n ↔ m < n :=
⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩
@[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n :=
by { convert bit1_le_bit0_iff, refl, }
@[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n :=
by { convert bit1_lt_bit0_iff, refl, }
@[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b m ≤ bit b n ↔ m ≤ n
| ff := bit0_le_bit0
| tt := bit1_le_bit1
@[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b m < bit b n ↔ m < n
| ff := bit0_lt_bit0
| tt := bit1_lt_bit1
@[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b m ≤ bit1 n ↔ m ≤ n
| ff := bit0_le_bit1_iff
| tt := bit1_le_bit1
/-! ### decidability of predicates -/
instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
decidable (∀x, lo ≤ x → x < hi → P x) :=
decidable_of_iff (∀ x < hi - lo, P (lo + x))
⟨λal x hl hh, by { have := al (x - lo) ((tsub_lt_tsub_iff_right hl).mpr hh),
rwa [add_tsub_cancel_of_le hl] at this, },
λal x h, al _ (nat.le_add_right _ _) (lt_tsub_iff_left.mp h)⟩
instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
decidable (∀x, lo ≤ x → x ≤ hi → P x) :=
decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $
ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl
end nat
|
8884c22544baeef7f9327e3f36474a0f2a58fd8a | 4fa161becb8ce7378a709f5992a594764699e268 | /src/data/set/function.lean | 4925ea70c3e3766a61b13c1df6f9c771504b319d | [
"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 | 20,359 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov
-/
import data.set.basic
import logic.function.conjugate
/-!
# Functions over sets
## Main definitions
### Predicate
* `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`;
* `maps_to f s t` : `f` sends every point of `s` to a point of `t`;
* `inj_on f s` : restriction of `f` to `s` is injective;
* `surj_on f s t` : every point in `s` has a preimage in `s`;
* `bij_on f s t` : `f` is a bijection between `s` and `t`;
* `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`;
* `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`;
* `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e.
we have `left_inv_on f' f s` and `right_inv_on f' f t`.
### Functions
* `restrict f s` : restrict the domain of `f` to the set `s`;
* `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`;
* `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s`
and the codomain to `t`.
-/
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
open function
namespace set
/-! ### Restrict -/
/-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version
takes an argument `↥s` instead of `subtype s`. -/
def restrict (f : α → β) (s : set α) : s → β := λ x, f x
lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl
@[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl
@[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s :=
range_comp.trans $ congr_arg (('') f) s.range_coe_subtype
/-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version
has codomain `↥s` instead of `subtype s`. -/
def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s :=
λ x, ⟨f x, h x⟩
@[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) :
(cod_restrict f s h x : β) = f x :=
rfl
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ}
{f' f₁' f₂' : β → α} {g' : γ → β}
/-! ### Equality on a set -/
/-- Two functions `f₁ f₂ : α → β` are equal on `s`
if `f₁ x = f₂ x` for all `x ∈ a`. -/
@[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x
@[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s :=
λ x hx, (h hx).symm
lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s :=
⟨eq_on.symm, eq_on.symm⟩
@[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s :=
λ _ _, rfl
@[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s :=
λ x hx, (h₁ hx).trans (h₂ hx)
theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s :=
image_congr heq
lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ :=
λ x hx, hf (hs hx)
/-! ### maps to -/
/-- `maps_to f a b` means that the image of `a` is contained in `b`. -/
@[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t
/-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s`
and the codomain to `t`. Same as `subtype.map`. -/
def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) :
s → t :=
subtype.map f h
@[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) :
(h.restrict f s t x : β) = f x := rfl
theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t :=
image_subset_iff.symm
theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _
theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t :=
maps_to'.1 h
theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) :
maps_to f₂ s t :=
λ x hx, h hx ▸ h₁ hx
theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p :=
λ x h, h₁ (h₂ h)
theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) :
∀ n, maps_to (f^[n]) s s
| 0 := λ _, id
| (n+1) := (maps_to.iterate n).comp h
theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) :
(h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ :=
begin
funext x,
rw [subtype.coe_ext, maps_to.coe_restrict_apply],
induction n with n ihn generalizing x,
{ refl },
{ simp [nat.iterate, ihn] }
end
theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) :
maps_to f s₂ t₂ :=
λ x hx, ht (hf $ hs hx)
theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial
theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to'
theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _
theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) :=
(maps_to_image f s).mono (subset.refl s) (image_subset_range _ _)
/-! ### Injectivity on a set -/
/-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/
@[reducible] def inj_on (f : α → β) (s : set α) : Prop :=
∀⦃x₁ x₂ : α⦄, x₁ ∈ s → x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂
theorem inj_on_empty (f : α → β) : inj_on f ∅ :=
λ _ _ h₁ _ _, false.elim h₁
theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) :
inj_on f₂ s :=
λ x y hx hy, h hx ▸ h hy ▸ h₁ hx hy
theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ :=
λ x y hx hy H, ht (h hx) (h hy) H
lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ :=
⟨λ h x y hx hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩
theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) :
inj_on (g ∘ f) s :=
λ x y hx hy heq, hf hx hy $ hg (h hx) (h hy) heq
lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) :=
⟨λ H a b h, subtype.eq $ H a.2 b.2 h,
λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩
lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) :
(inv_fun_on f s₂) '' (f '' s₁) = s₁ :=
begin
have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz),
rw [← image_comp, this.image_eq, image_id]
end
lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) :
inj_on (preimage f) B :=
begin
intros s t hs ht hst,
rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst]
end
/-! ### Surjectivity on a set -/
/-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/
@[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s
theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _
theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty :=
(ht.mono h).of_image
theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t :=
by rwa [surj_on, ← H.image_eq]
theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t :=
⟨λ H, H.congr h, λ H, H.congr h.symm⟩
theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ :=
subset.trans ht $ subset.trans hf $ image_subset _ hs
theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p :=
subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _
lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ :=
by simp [surjective, surj_on, subset_def]
lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) :=
⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩,
λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩
lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) :
f '' s = t :=
eq_of_subset_of_subset h₂.image_subset h₁
/-! ### Bijectivity -/
/-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/
@[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop :=
maps_to f s t ∧ inj_on f s ∧ surj_on f s t
lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left
lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left
lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right
lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) :
bij_on f s t :=
⟨h₁, h₂, h₃⟩
lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ :=
⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩
lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) :=
bij_on.mk (maps_to_image f s) h (subset.refl _)
theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) :
bij_on f₂ s t :=
bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h)
theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
lemma bij_on.image_eq (h : bij_on f s t) :
f '' s = t :=
h.surj_on.image_eq_of_maps_to h.maps_to
theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p :=
bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to)
(hg.surj_on.comp hf.surj_on)
lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ :=
iff.intro
(λ h, let ⟨inj, surj⟩ := h in
⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩)
(λ h, let ⟨map, inj, surj⟩ := h in
⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩)
/-! ### left inverse -/
/-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/
@[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f' (f x) = x
lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h
lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx
lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s)
{t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s :=
λ x hx, heq (h₁' hx) ▸ h₁ hx
theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) :
left_inv_on f₁' f₂ s :=
λ x hx, heq hx ▸ h₁ hx
theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s :=
λ x₁ x₂ h₁ h₂ heq,
calc
x₁ = f₁' (f x₁) : eq.symm $ h h₁
... = f₁' (f x₂) : congr_arg f₁' heq
... = x₂ : h h₂
theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s :=
λ x hx, ⟨f x, hf hx, h hx⟩
theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) :
left_inv_on (f' ∘ g') (g ∘ f) s :=
λ x h,
calc
(f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h))
... = x : hf' h
/-! ### Right inverse -/
/-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/
@[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop :=
left_inv_on f f' t
lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h
lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy
theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) :
right_inv_on f₂' f t :=
h₁.congr_right heq
theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s)
(heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t :=
left_inv_on.congr_left h₁ hg heq
theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) :
surj_on f s t :=
hf.surj_on hf'
theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p)
(g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p :=
hg.comp hf g'pt
theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t)
(h₁ : maps_to f s t) (h₂ : maps_to f' t s) :
right_inv_on f f' s :=
λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h))
theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t)
(h : maps_to f₂' t s) : eq_on f₁' f₂' t :=
λ y hy,
calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm
... = f₂' y : h₁ (h hy)
theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) :
left_inv_on f f' t :=
λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx]
/-! ### Two-side inverses -/
/-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/
@[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop :=
left_inv_on g f s ∧ right_inv_on g f t
lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩
theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) :
bij_on f s t :=
⟨hf, h.left.inj_on, h.right.surj_on hf'⟩
/-! ### `inv_fun_on` is a left/right inverse -/
theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) :
left_inv_on (inv_fun_on f s) f s :=
λ x hx, inv_fun_on_eq' h hx
theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
right_inv_on (inv_fun_on f s) f t :=
λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy
theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) :
inv_on (inv_fun_on f s) f s t :=
⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩
theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t :=
begin
refine ⟨_, h.right_inv_on_inv_fun_on⟩,
rintros _ ⟨y, hy, rfl⟩,
rw [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) :
maps_to (inv_fun_on f s) t s :=
λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy
theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) :
bij_on f (inv_fun_on f s '' t) t :=
begin
refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _),
rintros _ ⟨y, hy, rfl⟩,
rwa [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on_iff_exists_bij_on_subset :
surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t :=
begin
split,
{ rcases eq_empty_or_nonempty t with rfl|ht,
{ exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ },
{ assume h,
haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩,
exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }},
{ rintros ⟨s', hs', hfs'⟩,
exact hfs'.surj_on.mono hs' (subset.refl _) }
end
end set
/-! ### Piecewise defined function -/
namespace set
variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i)
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] :
piecewise set.univ f g = f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
variable [∀j, decidable (j ∈ s)]
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
simp [piecewise],
ext i,
by_cases h : i = j,
{ rw h, simp },
{ by_cases h' : i ∈ s; simp [h, h'] }
end
@[simp, priority 990]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
end set
namespace function
open set
variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α}
lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f :=
λ _ _ _ _ heq, h heq
lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) :=
(hg.inj_on univ).comp hf (maps_to_univ _ _)
lemma surjective.surj_on (hf : surjective f) (s : set β) :
surj_on f univ s :=
(surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _)
namespace semiconj
lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) :
maps_to fb (f '' s) (f '' t) :=
λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩
lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) :=
λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩
lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) :
surj_on fb (f '' s) (f '' t) :=
begin
rintros y ⟨x, hxt, rfl⟩,
rcases ha hxt with ⟨x, hxs, rfl⟩,
rw [h x],
exact mem_image_of_mem _ (mem_image_of_mem _ hxs)
end
lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) :
surj_on fb (range f) (range f) :=
by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) }
lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) :
inj_on fb (f '' s) :=
begin
rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ H,
simp only [← h.eq] at H,
exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H)
end
lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) :
inj_on fb (range f) :=
by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf }
lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) :
bij_on fb (f '' s) (f '' t) :=
⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf),
h.surj_on_image ha.surj_on⟩
lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) :
bij_on fb (range f) (range f) :=
begin
rw [← image_univ],
exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ)
end
lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) :
maps_to fa (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, by simp only [mem_preimage, h x, hb hx]
lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s)
(hf : inj_on f (f ⁻¹' s)) :
inj_on fa (f ⁻¹' s) :=
begin
intros x y hx hy H,
have := congr_arg f H,
rw [h.eq, h.eq] at this,
exact hf hx hy (hb hx hy this)
end
end semiconj
lemma update_comp_eq_of_not_mem_range [decidable_eq β]
(g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) :
(function.update g i a) ∘ f = g ∘ f :=
begin
ext p,
have : f p ≠ i,
{ by_contradiction H,
push_neg at H,
rw ← H at h,
exact h (set.mem_range_self _) },
simp [this],
end
lemma update_comp_eq_of_injective [decidable_eq α] [decidable_eq β]
(g : β → γ) {f : α → β} (hf : function.injective f) (i : α) (a : γ) :
(function.update g (f i) a) ∘ f = function.update (g ∘ f) i a :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp },
{ have : f j ≠ f i := hf.ne h,
simp [h, this] }
end
end function
|
b7ee49e9ff8404f9dee25ea8974a9c6fe16e77d3 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/measure_theory/integral/integral_eq_improper.lean | e68a8e1240559271a74cde59002abd4423dcdfc7 | [
"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 | 25,326 | lean | /-
Copyright (c) 2021 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Bhavik Mehta
-/
import measure_theory.integral.interval_integral
import order.filter.at_top_bot
/-!
# Links between an integral and its "improper" version
In its current state, mathlib only knows how to talk about definite ("proper") integrals,
in the sense that it treats integrals over `[x, +∞)` the same as it treats integrals over
`[y, z]`. For example, the integral over `[1, +∞)` is **not** defined to be the limit of
the integral over `[1, x]` as `x` tends to `+∞`, which is known as an **improper integral**.
Indeed, the "proper" definition is stronger than the "improper" one. The usual counterexample
is `x ↦ sin(x)/x`, which has an improper integral over `[1, +∞)` but no definite integral.
Although definite integrals have better properties, they are hardly usable when it comes to
computing integrals on unbounded sets, which is much easier using limits. Thus, in this file,
we prove various ways of studying the proper integral by studying the improper one.
## Definitions
The main definition of this file is `measure_theory.ae_cover`. It is a rather technical
definition whose sole purpose is generalizing and factoring proofs. Given an index type `ι`, a
countably generated filter `l` over `ι`, and an `ι`-indexed family `φ` of subsets of a measurable
space `α` equipped with a measure `μ`, one should think of a hypothesis `hφ : ae_cover μ l φ` as
a sufficient condition for being able to interpret `∫ x, f x ∂μ` (if it exists) as the limit
of `∫ x in φ i, f x ∂μ` as `i` tends to `l`.
When using this definition with a measure restricted to a set `s`, which happens fairly often,
one should not try too hard to use a `ae_cover` of subsets of `s`, as it often makes proofs
more complicated than necessary. See for example the proof of
`measure_theory.integrable_on_Iic_of_interval_integral_norm_tendsto` where we use `(λ x, Ioi x)`
as an `ae_cover` w.r.t. `μ.restrict (Iic b)`, instead of using `(λ x, Ioc x b)`.
## Main statements
- `measure_theory.ae_cover.lintegral_tendsto_of_countably_generated` : if `φ` is a `ae_cover μ l`,
where `l` is a countably generated filter, and if `f` is a measurable `ennreal`-valued function,
then `∫⁻ x in φ n, f x ∂μ` tends to `∫⁻ x, f x ∂μ` as `n` tends to `l`
- `measure_theory.ae_cover.integrable_of_integral_norm_tendsto` : if `φ` is a `ae_cover μ l`,
where `l` is a countably generated filter, if `f` is measurable and integrable on each `φ n`,
and if `∫ x in φ n, ∥f x∥ ∂μ` tends to some `I : ℝ` as n tends to `l`, then `f` is integrable
- `measure_theory.ae_cover.integral_tendsto_of_countably_generated` : if `φ` is a `ae_cover μ l`,
where `l` is a countably generated filter, and if `f` is measurable and integrable (globally),
then `∫ x in φ n, f x ∂μ` tends to `∫ x, f x ∂μ` as `n` tends to `+∞`.
We then specialize these lemmas to various use cases involving intervals, which are frequent
in analysis.
-/
open measure_theory filter set topological_space
open_locale ennreal nnreal topological_space
namespace measure_theory
section ae_cover
variables {α ι : Type*} [measurable_space α] (μ : measure α) (l : filter ι)
/-- A sequence `φ` of subsets of `α` is a `ae_cover` w.r.t. a measure `μ` and a filter `l`
if almost every point (w.r.t. `μ`) of `α` eventually belongs to `φ n` (w.r.t. `l`), and if
each `φ n` is measurable.
This definition is a technical way to avoid duplicating a lot of proofs.
It should be thought of as a sufficient condition for being able to interpret
`∫ x, f x ∂μ` (if it exists) as the limit of `∫ x in φ n, f x ∂μ` as `n` tends to `l`.
See for example `measure_theory.ae_cover.lintegral_tendsto_of_countably_generated`,
`measure_theory.ae_cover.integrable_of_integral_norm_tendsto` and
`measure_theory.ae_cover.integral_tendsto_of_countably_generated`. -/
structure ae_cover (φ : ι → set α) : Prop :=
(ae_eventually_mem : ∀ᵐ x ∂μ, ∀ᶠ i in l, x ∈ φ i)
(measurable : ∀ i, measurable_set $ φ i)
variables {μ} {l}
section preorder_α
variables [preorder α] [topological_space α] [order_closed_topology α]
[opens_measurable_space α] {a b : ι → α}
(ha : tendsto a l at_bot) (hb : tendsto b l at_top)
lemma ae_cover_Icc :
ae_cover μ l (λ i, Icc (a i) (b i)) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_le_at_bot x).mp $
(hb.eventually $ eventually_ge_at_top x).mono $
λ i hbi hai, ⟨hai, hbi⟩ ),
measurable := λ i, measurable_set_Icc }
lemma ae_cover_Ici :
ae_cover μ l (λ i, Ici $ a i) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_le_at_bot x).mono $
λ i hai, hai ),
measurable := λ i, measurable_set_Ici }
lemma ae_cover_Iic :
ae_cover μ l (λ i, Iic $ b i) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(hb.eventually $ eventually_ge_at_top x).mono $
λ i hbi, hbi ),
measurable := λ i, measurable_set_Iic }
end preorder_α
section linear_order_α
variables [linear_order α] [topological_space α] [order_closed_topology α]
[opens_measurable_space α] {a b : ι → α}
(ha : tendsto a l at_bot) (hb : tendsto b l at_top)
lemma ae_cover_Ioo [no_min_order α] [no_max_order α] :
ae_cover μ l (λ i, Ioo (a i) (b i)) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_lt_at_bot x).mp $
(hb.eventually $ eventually_gt_at_top x).mono $
λ i hbi hai, ⟨hai, hbi⟩ ),
measurable := λ i, measurable_set_Ioo }
lemma ae_cover_Ioc [no_min_order α] : ae_cover μ l (λ i, Ioc (a i) (b i)) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_lt_at_bot x).mp $
(hb.eventually $ eventually_ge_at_top x).mono $
λ i hbi hai, ⟨hai, hbi⟩ ),
measurable := λ i, measurable_set_Ioc }
lemma ae_cover_Ico [no_max_order α] : ae_cover μ l (λ i, Ico (a i) (b i)) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_le_at_bot x).mp $
(hb.eventually $ eventually_gt_at_top x).mono $
λ i hbi hai, ⟨hai, hbi⟩ ),
measurable := λ i, measurable_set_Ico }
lemma ae_cover_Ioi [no_min_order α] :
ae_cover μ l (λ i, Ioi $ a i) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(ha.eventually $ eventually_lt_at_bot x).mono $
λ i hai, hai ),
measurable := λ i, measurable_set_Ioi }
lemma ae_cover_Iio [no_max_order α] :
ae_cover μ l (λ i, Iio $ b i) :=
{ ae_eventually_mem := ae_of_all μ (λ x,
(hb.eventually $ eventually_gt_at_top x).mono $
λ i hbi, hbi ),
measurable := λ i, measurable_set_Iio }
end linear_order_α
lemma ae_cover.restrict {φ : ι → set α} (hφ : ae_cover μ l φ) {s : set α} :
ae_cover (μ.restrict s) l φ :=
{ ae_eventually_mem := ae_restrict_of_ae hφ.ae_eventually_mem,
measurable := hφ.measurable }
lemma ae_cover_restrict_of_ae_imp {s : set α} {φ : ι → set α}
(hs : measurable_set s) (ae_eventually_mem : ∀ᵐ x ∂μ, x ∈ s → ∀ᶠ n in l, x ∈ φ n)
(measurable : ∀ n, measurable_set $ φ n) :
ae_cover (μ.restrict s) l φ :=
{ ae_eventually_mem := by rwa ae_restrict_iff' hs,
measurable := measurable }
lemma ae_cover.inter_restrict {φ : ι → set α} (hφ : ae_cover μ l φ)
{s : set α} (hs : measurable_set s) :
ae_cover (μ.restrict s) l (λ i, φ i ∩ s) :=
ae_cover_restrict_of_ae_imp hs
(hφ.ae_eventually_mem.mono (λ x hx hxs, hx.mono $ λ i hi, ⟨hi, hxs⟩))
(λ i, (hφ.measurable i).inter hs)
lemma ae_cover.ae_tendsto_indicator {β : Type*} [has_zero β] [topological_space β]
(f : α → β) {φ : ι → set α} (hφ : ae_cover μ l φ) :
∀ᵐ x ∂μ, tendsto (λ i, (φ i).indicator f x) l (𝓝 $ f x) :=
hφ.ae_eventually_mem.mono (λ x hx, tendsto_const_nhds.congr' $
hx.mono $ λ n hn, (indicator_of_mem hn _).symm)
lemma ae_cover.ae_measurable {β : Type*} [measurable_space β] [l.is_countably_generated] [l.ne_bot]
{f : α → β} {φ : ι → set α} (hφ : ae_cover μ l φ)
(hfm : ∀ i, ae_measurable f (μ.restrict $ φ i)) : ae_measurable f μ :=
begin
obtain ⟨u, hu⟩ := l.exists_seq_tendsto,
have := ae_measurable_Union_iff.mpr (λ (n : ℕ), hfm (u n)),
rwa measure.restrict_eq_self_of_ae_mem at this,
filter_upwards [hφ.ae_eventually_mem] with x hx using
let ⟨i, hi⟩ := (hu.eventually hx).exists in mem_Union.mpr ⟨i, hi⟩
end
end ae_cover
lemma ae_cover.comp_tendsto {α ι ι' : Type*} [measurable_space α] {μ : measure α} {l : filter ι}
{l' : filter ι'} {φ : ι → set α} (hφ : ae_cover μ l φ)
{u : ι' → ι} (hu : tendsto u l' l) :
ae_cover μ l' (φ ∘ u) :=
{ ae_eventually_mem := hφ.ae_eventually_mem.mono (λ x hx, hu.eventually hx),
measurable := λ i, hφ.measurable (u i) }
section ae_cover_Union_Inter_encodable
variables {α ι : Type*} [encodable ι]
[measurable_space α] {μ : measure α}
lemma ae_cover.bUnion_Iic_ae_cover [preorder ι] {φ : ι → set α} (hφ : ae_cover μ at_top φ) :
ae_cover μ at_top (λ (n : ι), ⋃ k (h : k ∈ Iic n), φ k) :=
{ ae_eventually_mem := hφ.ae_eventually_mem.mono
(λ x h, h.mono (λ i hi, mem_bUnion right_mem_Iic hi)),
measurable := λ i, measurable_set.bUnion (countable_encodable _) (λ n _, hφ.measurable n) }
lemma ae_cover.bInter_Ici_ae_cover [semilattice_sup ι] [nonempty ι] {φ : ι → set α}
(hφ : ae_cover μ at_top φ) : ae_cover μ at_top (λ (n : ι), ⋂ k (h : k ∈ Ici n), φ k) :=
{ ae_eventually_mem := hφ.ae_eventually_mem.mono
begin
intros x h,
rw eventually_at_top at *,
rcases h with ⟨i, hi⟩,
use i,
intros j hj,
exact mem_bInter (λ k hk, hi k (le_trans hj hk)),
end,
measurable := λ i, measurable_set.bInter (countable_encodable _) (λ n _, hφ.measurable n) }
end ae_cover_Union_Inter_encodable
section lintegral
variables {α ι : Type*} [measurable_space α] {μ : measure α} {l : filter ι}
private lemma lintegral_tendsto_of_monotone_of_nat {φ : ℕ → set α}
(hφ : ae_cover μ at_top φ) (hmono : monotone φ) {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) :
tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) at_top (𝓝 $ ∫⁻ x, f x ∂μ) :=
let F := λ n, (φ n).indicator f in
have key₁ : ∀ n, ae_measurable (F n) μ, from λ n, hfm.indicator (hφ.measurable n),
have key₂ : ∀ᵐ (x : α) ∂μ, monotone (λ n, F n x), from ae_of_all _
(λ x i j hij, indicator_le_indicator_of_subset (hmono hij) (λ x, zero_le $ f x) x),
have key₃ : ∀ᵐ (x : α) ∂μ, tendsto (λ n, F n x) at_top (𝓝 (f x)), from hφ.ae_tendsto_indicator f,
(lintegral_tendsto_of_tendsto_of_monotone key₁ key₂ key₃).congr
(λ n, lintegral_indicator f (hφ.measurable n))
lemma ae_cover.lintegral_tendsto_of_nat {φ : ℕ → set α} (hφ : ae_cover μ at_top φ)
{f : α → ℝ≥0∞} (hfm : ae_measurable f μ) :
tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) at_top (𝓝 $ ∫⁻ x, f x ∂μ) :=
begin
have lim₁ := lintegral_tendsto_of_monotone_of_nat (hφ.bInter_Ici_ae_cover)
(λ i j hij, bInter_subset_bInter_left (Ici_subset_Ici.mpr hij)) hfm,
have lim₂ := lintegral_tendsto_of_monotone_of_nat (hφ.bUnion_Iic_ae_cover)
(λ i j hij, bUnion_subset_bUnion_left (Iic_subset_Iic.mpr hij)) hfm,
have le₁ := λ n, lintegral_mono_set (bInter_subset_of_mem left_mem_Ici),
have le₂ := λ n, lintegral_mono_set (subset_bUnion_of_mem right_mem_Iic),
exact tendsto_of_tendsto_of_tendsto_of_le_of_le lim₁ lim₂ le₁ le₂
end
lemma ae_cover.lintegral_tendsto_of_countably_generated [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞}
(hfm : ae_measurable f μ) : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) l (𝓝 $ ∫⁻ x, f x ∂μ) :=
tendsto_of_seq_tendsto (λ u hu, (hφ.comp_tendsto hu).lintegral_tendsto_of_nat hfm)
lemma ae_cover.lintegral_eq_of_tendsto [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞} (I : ℝ≥0∞)
(hfm : ae_measurable f μ) (htendsto : tendsto (λ i, ∫⁻ x in φ i, f x ∂μ) l (𝓝 I)) :
∫⁻ x, f x ∂μ = I :=
tendsto_nhds_unique (hφ.lintegral_tendsto_of_countably_generated hfm) htendsto
lemma ae_cover.supr_lintegral_eq_of_countably_generated [nonempty ι] [l.ne_bot]
[l.is_countably_generated] {φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ≥0∞}
(hfm : ae_measurable f μ) : (⨆ (i : ι), ∫⁻ x in φ i, f x ∂μ) = ∫⁻ x, f x ∂μ :=
begin
have := hφ.lintegral_tendsto_of_countably_generated hfm,
refine csupr_eq_of_forall_le_of_forall_lt_exists_gt
(λ i, lintegral_mono' measure.restrict_le_self le_rfl) (λ w hw, _),
rcases exists_between hw with ⟨m, hm₁, hm₂⟩,
rcases (eventually_ge_of_tendsto_gt hm₂ this).exists with ⟨i, hi⟩,
exact ⟨i, lt_of_lt_of_le hm₁ hi⟩,
end
end lintegral
section integrable
variables {α ι E : Type*} [measurable_space α] {μ : measure α} {l : filter ι}
[normed_group E] [measurable_space E] [opens_measurable_space E]
lemma ae_cover.integrable_of_lintegral_nnnorm_bounded [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ) (hfm : ae_measurable f μ)
(hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ∥f x∥₊ ∂μ ≤ ennreal.of_real I) :
integrable f μ :=
begin
refine ⟨hfm, (le_of_tendsto _ hbounded).trans_lt ennreal.of_real_lt_top⟩,
exact hφ.lintegral_tendsto_of_countably_generated
(measurable_nnnorm.comp_ae_measurable hfm).coe_nnreal_ennreal,
end
lemma ae_cover.integrable_of_lintegral_nnnorm_tendsto [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ)
(hfm : ae_measurable f μ)
(htendsto : tendsto (λ i, ∫⁻ x in φ i, ∥f x∥₊ ∂μ) l (𝓝 $ ennreal.of_real I)) :
integrable f μ :=
begin
refine hφ.integrable_of_lintegral_nnnorm_bounded (max 1 (I + 1)) hfm _,
refine htendsto.eventually (ge_mem_nhds _),
refine (ennreal.of_real_lt_of_real_iff (lt_max_of_lt_left zero_lt_one)).2 _,
exact lt_max_of_lt_right (lt_add_one I),
end
lemma ae_cover.integrable_of_lintegral_nnnorm_bounded' [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ≥0) (hfm : ae_measurable f μ)
(hbounded : ∀ᶠ i in l, ∫⁻ x in φ i, ∥f x∥₊ ∂μ ≤ I) :
integrable f μ :=
hφ.integrable_of_lintegral_nnnorm_bounded I hfm
(by simpa only [ennreal.of_real_coe_nnreal] using hbounded)
lemma ae_cover.integrable_of_lintegral_nnnorm_tendsto' [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (I : ℝ≥0)
(hfm : ae_measurable f μ)
(htendsto : tendsto (λ i, ∫⁻ x in φ i, ∥f x∥₊ ∂μ) l (𝓝 I)) :
integrable f μ :=
hφ.integrable_of_lintegral_nnnorm_tendsto I hfm
(by simpa only [ennreal.of_real_coe_nnreal] using htendsto)
lemma ae_cover.integrable_of_integral_norm_bounded [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E}
(I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ)
(hbounded : ∀ᶠ i in l, ∫ x in φ i, ∥f x∥ ∂μ ≤ I) :
integrable f μ :=
begin
have hfm : ae_measurable f μ := hφ.ae_measurable (λ i, (hfi i).ae_measurable),
refine hφ.integrable_of_lintegral_nnnorm_bounded I hfm _,
conv at hbounded in (integral _ _)
{ rw integral_eq_lintegral_of_nonneg_ae (ae_of_all _ (λ x, @norm_nonneg E _ (f x)))
hfm.norm.restrict },
conv at hbounded in (ennreal.of_real _) { dsimp, rw ← coe_nnnorm, rw ennreal.of_real_coe_nnreal },
refine hbounded.mono (λ i hi, _),
rw ←ennreal.of_real_to_real (ne_top_of_lt (hfi i).2),
apply ennreal.of_real_le_of_real hi,
end
lemma ae_cover.integrable_of_integral_norm_tendsto [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E}
(I : ℝ) (hfi : ∀ i, integrable_on f (φ i) μ)
(htendsto : tendsto (λ i, ∫ x in φ i, ∥f x∥ ∂μ) l (𝓝 I)) :
integrable f μ :=
let ⟨I', hI'⟩ := htendsto.is_bounded_under_le in hφ.integrable_of_integral_norm_bounded I' hfi hI'
lemma ae_cover.integrable_of_integral_bounded_of_nonneg_ae [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ)
(hfi : ∀ i, integrable_on f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x)
(hbounded : ∀ᶠ i in l, ∫ x in φ i, f x ∂μ ≤ I) :
integrable f μ :=
hφ.integrable_of_integral_norm_bounded I hfi $ hbounded.mono $ λ i hi,
(integral_congr_ae $ ae_restrict_of_ae $ hnng.mono $ λ x, real.norm_of_nonneg).le.trans hi
lemma ae_cover.integrable_of_integral_tendsto_of_nonneg_ae [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ)
(hfi : ∀ i, integrable_on f (φ i) μ) (hnng : ∀ᵐ x ∂μ, 0 ≤ f x)
(htendsto : tendsto (λ i, ∫ x in φ i, f x ∂μ) l (𝓝 I)) :
integrable f μ :=
let ⟨I', hI'⟩ := htendsto.is_bounded_under_le in
hφ.integrable_of_integral_bounded_of_nonneg_ae I' hfi hnng hI'
end integrable
section integral
variables {α ι E : Type*} [measurable_space α] {μ : measure α} {l : filter ι}
[normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[complete_space E] [second_countable_topology E]
lemma ae_cover.integral_tendsto_of_countably_generated [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E} (hfi : integrable f μ) :
tendsto (λ i, ∫ x in φ i, f x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) :=
suffices h : tendsto (λ i, ∫ (x : α), (φ i).indicator f x ∂μ) l (𝓝 (∫ (x : α), f x ∂μ)),
by { convert h, ext n, rw integral_indicator (hφ.measurable n) },
tendsto_integral_filter_of_dominated_convergence (λ x, ∥f x∥)
(eventually_of_forall $ λ i, hfi.ae_measurable.indicator $ hφ.measurable i)
(eventually_of_forall $ λ i, ae_of_all _ $ λ x, norm_indicator_le_norm_self _ _)
hfi.norm (hφ.ae_tendsto_indicator f)
/-- Slight reformulation of
`measure_theory.ae_cover.integral_tendsto_of_countably_generated`. -/
lemma ae_cover.integral_eq_of_tendsto [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → E}
(I : E) (hfi : integrable f μ)
(h : tendsto (λ n, ∫ x in φ n, f x ∂μ) l (𝓝 I)) :
∫ x, f x ∂μ = I :=
tendsto_nhds_unique (hφ.integral_tendsto_of_countably_generated hfi) h
lemma ae_cover.integral_eq_of_tendsto_of_nonneg_ae [l.ne_bot] [l.is_countably_generated]
{φ : ι → set α} (hφ : ae_cover μ l φ) {f : α → ℝ} (I : ℝ)
(hnng : 0 ≤ᵐ[μ] f) (hfi : ∀ n, integrable_on f (φ n) μ)
(htendsto : tendsto (λ n, ∫ x in φ n, f x ∂μ) l (𝓝 I)) :
∫ x, f x ∂μ = I :=
have hfi' : integrable f μ,
from hφ.integrable_of_integral_tendsto_of_nonneg_ae I hfi hnng htendsto,
hφ.integral_eq_of_tendsto I hfi' htendsto
end integral
section integrable_of_interval_integral
variables {α ι E : Type*}
[topological_space α] [linear_order α] [order_closed_topology α]
[measurable_space α] [opens_measurable_space α] {μ : measure α}
{l : filter ι} [filter.ne_bot l] [is_countably_generated l]
[measurable_space E] [normed_group E] [borel_space E]
{a b : ι → α} {f : α → E}
lemma integrable_of_interval_integral_norm_bounded [no_min_order α] [nonempty α]
(I : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) (b i)) μ)
(ha : tendsto a l at_bot) (hb : tendsto b l at_top)
(h : ∀ᶠ i in l, ∫ x in a i .. b i, ∥f x∥ ∂μ ≤ I) :
integrable f μ :=
begin
let c : α := classical.choice ‹_›,
have hφ : ae_cover μ l _ := ae_cover_Ioc ha hb,
refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _),
filter_upwards [ha.eventually (eventually_le_at_bot c), hb.eventually (eventually_ge_at_top c)]
with i hai hbi ht,
rwa ←interval_integral.integral_of_le (hai.trans hbi)
end
lemma integrable_of_interval_integral_norm_tendsto [no_min_order α] [nonempty α]
(I : ℝ) (hfi : ∀ i, integrable_on f (Ioc (a i) (b i)) μ)
(ha : tendsto a l at_bot) (hb : tendsto b l at_top)
(h : tendsto (λ i, ∫ x in a i .. b i, ∥f x∥ ∂μ) l (𝓝 I)) :
integrable f μ :=
let ⟨I', hI'⟩ := h.is_bounded_under_le in
integrable_of_interval_integral_norm_bounded I' hfi ha hb hI'
lemma integrable_on_Iic_of_interval_integral_norm_bounded [no_min_order α] (I : ℝ) (b : α)
(hfi : ∀ i, integrable_on f (Ioc (a i) b) μ) (ha : tendsto a l at_bot)
(h : ∀ᶠ i in l, (∫ x in a i .. b, ∥f x∥ ∂μ) ≤ I) :
integrable_on f (Iic b) μ :=
begin
have hφ : ae_cover (μ.restrict $ Iic b) l _ := ae_cover_Ioi ha,
have hfi : ∀ i, integrable_on f (Ioi (a i)) (μ.restrict $ Iic b),
{ intro i,
rw [integrable_on, measure.restrict_restrict (hφ.measurable i)],
exact hfi i },
refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _),
filter_upwards [ha.eventually (eventually_le_at_bot b)] with i hai,
rw [interval_integral.integral_of_le hai, measure.restrict_restrict (hφ.measurable i)],
exact id
end
lemma integrable_on_Iic_of_interval_integral_norm_tendsto [no_min_order α] (I : ℝ) (b : α)
(hfi : ∀ i, integrable_on f (Ioc (a i) b) μ) (ha : tendsto a l at_bot)
(h : tendsto (λ i, ∫ x in a i .. b, ∥f x∥ ∂μ) l (𝓝 I)) :
integrable_on f (Iic b) μ :=
let ⟨I', hI'⟩ := h.is_bounded_under_le in
integrable_on_Iic_of_interval_integral_norm_bounded I' b hfi ha hI'
lemma integrable_on_Ioi_of_interval_integral_norm_bounded (I : ℝ) (a : α)
(hfi : ∀ i, integrable_on f (Ioc a (b i)) μ) (hb : tendsto b l at_top)
(h : ∀ᶠ i in l, (∫ x in a .. b i, ∥f x∥ ∂μ) ≤ I) :
integrable_on f (Ioi a) μ :=
begin
have hφ : ae_cover (μ.restrict $ Ioi a) l _ := ae_cover_Iic hb,
have hfi : ∀ i, integrable_on f (Iic (b i)) (μ.restrict $ Ioi a),
{ intro i,
rw [integrable_on, measure.restrict_restrict (hφ.measurable i), inter_comm],
exact hfi i },
refine hφ.integrable_of_integral_norm_bounded I hfi (h.mp _),
filter_upwards [hb.eventually (eventually_ge_at_top a)] with i hbi,
rw [interval_integral.integral_of_le hbi, measure.restrict_restrict (hφ.measurable i),
inter_comm],
exact id
end
lemma integrable_on_Ioi_of_interval_integral_norm_tendsto (I : ℝ) (a : α)
(hfi : ∀ i, integrable_on f (Ioc a (b i)) μ) (hb : tendsto b l at_top)
(h : tendsto (λ i, ∫ x in a .. b i, ∥f x∥ ∂μ) l (𝓝 $ I)) :
integrable_on f (Ioi a) μ :=
let ⟨I', hI'⟩ := h.is_bounded_under_le in
integrable_on_Ioi_of_interval_integral_norm_bounded I' a hfi hb hI'
end integrable_of_interval_integral
section integral_of_interval_integral
variables {α ι E : Type*}
[topological_space α] [linear_order α] [order_closed_topology α]
[measurable_space α] [opens_measurable_space α] {μ : measure α}
{l : filter ι} [is_countably_generated l]
[measurable_space E] [normed_group E] [normed_space ℝ E] [borel_space E]
[complete_space E] [second_countable_topology E]
{a b : ι → α} {f : α → E}
lemma interval_integral_tendsto_integral [no_min_order α] [nonempty α]
(hfi : integrable f μ) (ha : tendsto a l at_bot) (hb : tendsto b l at_top) :
tendsto (λ i, ∫ x in a i .. b i, f x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) :=
begin
let φ := λ i, Ioc (a i) (b i),
let c : α := classical.choice ‹_›,
have hφ : ae_cover μ l φ := ae_cover_Ioc ha hb,
refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _,
filter_upwards [ha.eventually (eventually_le_at_bot c), hb.eventually (eventually_ge_at_top c)]
with i hai hbi,
exact (interval_integral.integral_of_le (hai.trans hbi)).symm
end
lemma interval_integral_tendsto_integral_Iic [no_min_order α] (b : α)
(hfi : integrable_on f (Iic b) μ) (ha : tendsto a l at_bot) :
tendsto (λ i, ∫ x in a i .. b, f x ∂μ) l (𝓝 $ ∫ x in Iic b, f x ∂μ) :=
begin
let φ := λ i, Ioi (a i),
have hφ : ae_cover (μ.restrict $ Iic b) l φ := ae_cover_Ioi ha,
refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _,
filter_upwards [ha.eventually (eventually_le_at_bot $ b)] with i hai,
rw [interval_integral.integral_of_le hai, measure.restrict_restrict (hφ.measurable i)],
refl,
end
lemma interval_integral_tendsto_integral_Ioi (a : α)
(hfi : integrable_on f (Ioi a) μ) (hb : tendsto b l at_top) :
tendsto (λ i, ∫ x in a .. b i, f x ∂μ) l (𝓝 $ ∫ x in Ioi a, f x ∂μ) :=
begin
let φ := λ i, Iic (b i),
have hφ : ae_cover (μ.restrict $ Ioi a) l φ := ae_cover_Iic hb,
refine (hφ.integral_tendsto_of_countably_generated hfi).congr' _,
filter_upwards [hb.eventually (eventually_ge_at_top $ a)] with i hbi,
rw [interval_integral.integral_of_le hbi, measure.restrict_restrict (hφ.measurable i),
inter_comm],
refl,
end
end integral_of_interval_integral
end measure_theory
|
6e52da4a22e54d0178f6a5246e0a637da438b354 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/testing/slim_check/sampleable.lean | c9755192c6b80769fd645267bfb2b1ff3c2b660b | [
"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 | 31,349 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.lazy_list.basic
import data.tree
import data.int.basic
import control.bifunctor
import control.ulift
import tactic.linarith
import testing.slim_check.gen
/-!
# `sampleable` Class
This class permits the creation samples of a given type
controlling the size of those values using the `gen` monad`. It also
helps minimize examples by creating smaller versions of given values.
When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`,
`slim_check` requires that `ℕ` have an instance of `sampleable` and for
`prime n` to be decidable. `slim_check` will then use the instance of
`sampleable` to generate small examples of ℕ and progressively increase
in size. For each example `n`, `prime n` is tested. If it is false,
the example will be rejected (not a test success nor a failure) and
`slim_check` will move on to other examples. If `prime n` is true, `n
≤ 100` will be tested. If it is false, `n` is a counter-example of `∀
n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true,
the test passes and `slim_check` moves on to trying more examples.
This is a port of the Haskell QuickCheck library.
## Main definitions
* `sampleable` class
* `sampleable_functor` and `sampleable_bifunctor` class
* `sampleable_ext` class
### `sampleable`
`sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples.
### `sampleable_ext`
`sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type.
### `sampleable_functor` and `sampleable_bifunctor`
`sampleable_functor F` and `sampleable_bifunctor F` makes it possible
to create samples of and shrink `F α` given a sampling function and a
shrinking function for arbitrary `α`.
This allows us to separate the logic for generating the shape of a
collection from the logic for generating its contents. Specifically,
the contents could be generated using either `sampleable` or
`sampleable_ext` instance and the `sampleable_(bi)functor` does not
need to use that information
## Shrinking
Shrinking happens when `slim_check` find a counter-example to a
property. It is likely that the example will be more complicated than
necessary so `slim_check` proceeds to shrink it as much as
possible. Although equally valid, a smaller counter-example is easier
for a user to understand and use.
The `sampleable` class, beside having the `sample` function, has a
`shrink` function so that we can use specialized knowledge while
shrinking a value. It is not responsible for the whole shrinking process
however. It only has to take one step in the shrinking process.
`slim_check` will repeatedly call `shrink` until no more steps can
be taken. Because `shrink` guarantees that the size of the candidates
it produces is strictly smaller than the argument, we know that
`slim_check` is guaranteed to terminate.
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v w
namespace slim_check
variables (α : Type u)
local infix ` ≺ `:50 := has_well_founded.r
/-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/
def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y
/-- `shrink_fn α` is the type of functions that shrink an
argument of type `α` -/
@[reducible]
def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x }
/-- `sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples. -/
class sampleable :=
[wf : has_sizeof α]
(sample [] : gen α)
(shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil)
attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof
attribute [instance, priority 200] sampleable.wf
/-- `sampleable_functor F` makes it possible to create samples of and
shrink `F α` given a sampling function and a shrinking function for
arbitrary `α` -/
class sampleable_functor (F : Type u → Type v) [functor F] :=
[wf : Π α [has_sizeof α], has_sizeof (F α)]
(sample [] : ∀ {α}, gen α → gen (F α))
(shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α))
(p_repr : ∀ α, has_repr α → has_repr (F α))
/-- `sampleable_bifunctor F` makes it possible to create samples of
and shrink `F α β` given a sampling function and a shrinking function
for arbitrary `α` and `β` -/
class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] :=
[wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)]
(sample [] : ∀ {α β}, gen α → gen β → gen (F α β))
(shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β))
(p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β))
export sampleable (sample shrink)
/-- This function helps infer the proxy representation and
interpretation in `sampleable_ext` instances. -/
meta def sampleable.mk_trivial_interp : tactic unit :=
tactic.refine ``(id)
/-- `sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type. -/
class sampleable_ext (α : Sort u) :=
(proxy_repr : Type v)
[wf : has_sizeof proxy_repr]
(interp [] : proxy_repr → α . sampleable.mk_trivial_interp)
[p_repr : has_repr proxy_repr]
(sample [] : gen proxy_repr)
(shrink : shrink_fn proxy_repr)
attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf
open nat lazy_list
section prio
open sampleable_ext
set_option default_priority 50
instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α :=
{ proxy_repr := α,
sample := sampleable.sample α,
shrink := shrink }
instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] :
sampleable (F α) :=
{ wf := _,
sample := sampleable_functor.sample F (sampleable.sample α),
shrink := sampleable_functor.shrink α sampleable.shrink }
instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α]
[sampleable β] : sampleable (F α β) :=
{ wf := _,
sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β),
shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink }
set_option default_priority 100
instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] :
sampleable_ext (F α) :=
{ wf := _,
proxy_repr := F (proxy_repr α),
interp := functor.map (interp _),
sample := sampleable_functor.sample F (sampleable_ext.sample α),
shrink := sampleable_functor.shrink _ sampleable_ext.shrink,
p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr }
instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F]
[sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) :=
{ wf := _,
proxy_repr := F (proxy_repr α) (proxy_repr β),
interp := bifunctor.bimap (interp _) (interp _),
sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β),
shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink,
p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr }
end prio
/-- `nat.shrink' k n` creates a list of smaller natural numbers by
successively dividing `n` by 2 and subtracting the difference from
`k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k →
list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k }
| n hn ls :=
if h : n ≤ 1
then ls.reverse
else
have h₂ : 0 < n, by linarith,
have 1 * n / 2 < n,
from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂),
have n / 2 < n, by simpa,
let m := n / 2 in
have h₀ : m ≤ k, from le_trans (le_of_lt this) hn,
have h₃ : 0 < m,
by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith,
have h₁ : k - m < k,
from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃,
nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls)
/-- `nat.shrink n` creates a list of smaller natural numbers by
successively dividing by 2 and subtracting the difference from
`n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } :=
if h : n > 0 then
have ∀ k, 1 < k → n / k < n, from
λ k hk,
nat.div_lt_of_lt_mul
(suffices 1 * n < k * n, by simpa,
nat.mul_lt_mul_of_pos_right hk h),
⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n le_rfl []
else
[]
open gen
/--
Transport a `sampleable` instance from a type `α` to a type `β` using
functions between the two, going in both directions.
Function `g` is used to define the well-founded order that
`shrink` is expected to follow.
-/
def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α)
(h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β :=
{ wf := ⟨ sizeof ∘ g ⟩,
sample := f <$> sample α,
shrink := λ x,
have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x),
by introv h'; solve_by_elim [lt_of_le_of_lt],
subtype.map f this <$> shrink (g x) }
instance nat.sampleable : sampleable ℕ :=
{ sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))),
(3, coe <$> choose_any (fin $ succ sz))] dec_trivial,
shrink := λ x, lazy_list.of_list $ nat.shrink x }
/-- `iterate_shrink p x` takes a decidable predicate `p` and a
value `x` of some sampleable type and recursively shrinks `x`.
It first calls `shrink x` to get a list of candidate sample,
finds the first that satisfies `p` and recursively tries
to shrink that one. -/
def iterate_shrink {α} [has_to_string α] [sampleable α]
(p : α → Prop) [decidable_pred p] :
α → option α :=
well_founded.fix has_well_founded.wf $ λ x f_rec,
do trace sformat!"{x} : {(shrink x).to_list}" $ pure (),
y ← (shrink x).find (λ a, p a),
f_rec y y.property <|> some y.val .
instance fin.sampleable {n : ℕ} [ne_zero n] : sampleable (fin n) :=
sampleable.lift ℕ fin.of_nat' fin.val $
λ i, (mod_le _ _ : i % n ≤ i)
@[priority 100]
instance fin.sampleable' {n} : sampleable (fin (succ n)) :=
sampleable.lift ℕ fin.of_nat fin.val $
λ i, (mod_le _ _ : i % succ n ≤ i)
instance pnat.sampleable : sampleable ℕ+ :=
sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a,
by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, tsub_zero, succ_sub_succ_eq_sub]
/-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/
def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩
local attribute [instance, priority 2000] int.has_sizeof
instance int.sampleable : sampleable ℤ :=
{ wf := _,
sample := sized $ λ sz,
freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)),
(3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))]
dec_trivial,
shrink :=
λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $
λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] }
instance bool.sampleable : sampleable bool :=
{ wf := ⟨ λ b, if b then 1 else 0 ⟩,
sample := do { x ← choose_any bool,
return x },
shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩
else lazy_list.nil }
/--
Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by
first shrinking `x` and pairing the results with `y` and then shrinking
`y` and pairing the results with `x`.
All pairs either contain `x` untouched or `y` untouched. We rely on
shrinking being repeated for `x` to get maximally shrunken and then
for `y` to get shrunken too.
-/
def prod.shrink {α β} [has_sizeof α] [has_sizeof β]
(shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β)
| ⟨x₀,x₁⟩ :=
let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_a x₀).map $ subtype.map (λ a, (a, x₁))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h),
xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_b x₁).map $ subtype.map (λ a, (x₀, a))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in
xs₀.append xs₁
instance prod.sampleable : sampleable_bifunctor.{u v} prod :=
{ wf := _,
sample := λ α β sama samb, do
{ ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)),
⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)),
pure (x,y) },
shrink := @prod.shrink,
p_repr := @prod.has_repr }
instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) :=
sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_rfl
/-- shrinking function for sum types -/
def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α)
(shrink_β : shrink_fn β) : shrink_fn (α ⊕ β)
| (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
| (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
instance sum.sampleable : sampleable_bifunctor.{u v} sum :=
{ wf := _,
sample := λ (α : Type u) (β : Type v) sam_α sam_β,
(@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|>
@uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β),
shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β,
p_repr := @sum.has_repr }
instance rat.sampleable : sampleable ℚ :=
sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $
begin
intro i,
rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf;
dsimp [rat.mk_pnat],
mono*,
{ rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs],
apply int.abs_div_le_abs },
{ change _ - 1 ≤ y-1,
apply tsub_le_tsub_right,
apply nat.div_le_of_le_mul,
suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa },
apply nat.mul_le_mul_right,
apply gcd_pos_of_pos_right _ hy }
end
/-- `sampleable_char` can be specialized into customized `sampleable char` instances.
The resulting instance has `1 / length` chances of making an unrestricted choice of characters
and it otherwise chooses a character from `characters` with uniform probabilities. -/
def sampleable_char (length : nat) (characters : string) : sampleable char :=
{ sample := do { x ← choose_nat 0 length dec_trivial,
if x.val = 0 then do
n ← sample ℕ,
pure $ char.of_nat n
else do
i ← choose_nat 0 (characters.length - 1) dec_trivial,
pure (characters.mk_iterator.nextn i).curr },
shrink := λ _, lazy_list.nil }
instance char.sampleable : sampleable char :=
sampleable_char 3 " 0123abcABC:,;`\\/"
variables {α}
section list_shrink
variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x })
lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k}
(hk : 0 < k) (hk' : k < xs.length) :
sizeof (list.drop k xs) < sizeof xs :=
begin
induction xs with x xs generalizing k,
{ cases hk' },
cases k,
{ cases hk },
have : sizeof xs < sizeof (x :: xs),
{ unfold_wf },
cases k,
{ simp only [this, list.drop] },
{ simp only [list.drop],
transitivity,
{ solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] },
{ assumption } }
end
lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) :
sizeof (a :: xs) < sizeof (b :: xs) :=
by unfold_wf; assumption
lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') :
sizeof (x :: xs) < sizeof (x :: xs') :=
by unfold_wf; assumption
lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') :
sizeof (xs ++ ys) < sizeof (xs ++ ys') :=
begin
induction xs,
{ apply h },
{ unfold_wf,
simp only [list.sizeof, add_lt_add_iff_left],
exact xs_ih }
end
lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs :=
by cases xs; unfold_wf; linarith
/--
`list.shrink_removes` shrinks a list by removing chunks of size `k` in
the middle of the list.
-/
def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n,
n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs }
| xs n hn :=
if hkn : k > n then lazy_list.nil
else
if hkn' : k = n then
have 1 < xs.sizeof,
by { subst_vars, cases xs, { contradiction },
unfold_wf, apply lt_of_lt_of_le,
show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith },
{ mono, apply list.one_le_sizeof, } },
lazy_list.singleton ⟨[], this ⟩
else
have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn',
match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with
| ⟨xs₁,xs₂⟩, h :=
have h₄ : xs₁ = xs.take k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have h₃ : xs₂ = xs.drop k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have sizeof xs₂ < sizeof xs,
by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length],
have h₁ : n - k = xs₂.length,
by simp only [h₃, ←hn, list.length_drop],
have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs,
by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄];
solve_by_elim [list.sizeof_append_lt_left],
lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁
end
/--
`list.shrink_one xs` shrinks list `xs` by shrinking only one item in
the list.
-/
def list.shrink_one : shrink_fn (list α)
| [] := lazy_list.nil
| (x :: xs) :=
lazy_list.append
(subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x)
(subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs)
/-- `list.shrink_with shrink_f xs` shrinks `xs` by first
considering `xs` with chunks removed in the middle (starting with
chunks of size `xs.length` and halving down to `1`) and then
shrinks only one element of the list.
This strategy is taken directly from Haskell's QuickCheck -/
def list.shrink_with (xs : list α) :
lazy_list { ys : list α // sizeof_lt ys xs } :=
let n := xs.length in
lazy_list.append
((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k,
if hk : 0 < k
then list.shrink_removes k hk xs n rfl
else lazy_list.nil ))
(list.shrink_one shr _)
end list_shrink
instance list.sampleable : sampleable_functor list.{u} :=
{ wf := _,
sample := λ α sam_α, list_of sam_α,
shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α,
p_repr := @list.has_repr }
instance Prop.sampleable_ext : sampleable_ext Prop :=
{ proxy_repr := bool,
interp := coe,
sample := choose_any bool,
shrink := λ _, lazy_list.nil }
/-- `no_shrink` is a type annotation to signal that
a certain type is not to be shrunk. It can be useful in
combination with other types: e.g. `xs : list (no_shrink ℤ)`
will result in the list being cut down but individual
integers being kept as is. -/
def no_shrink (α : Type*) := α
instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) :=
⟨ (default : α) ⟩
/-- Introduction of the `no_shrink` type. -/
def no_shrink.mk {α} (x : α) : no_shrink α := x
/-- Selector of the `no_shrink` type. -/
def no_shrink.get {α} (x : no_shrink α) : α := x
instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) :=
{ sample := no_shrink.mk <$> sample α }
instance string.sampleable : sampleable string :=
{ sample := do { x ← list_of (sample char), pure x.as_string },
.. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_rfl }
/-- implementation of `sampleable (tree α)` -/
def tree.sample (sample : gen α) : ℕ → gen (tree α) | n :=
if h : n > 0
then have n / 2 < n, from div_lt_self h (by norm_num),
tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2)
else pure tree.nil
/-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced
by `well_founded.fix` and turns it into a shrinking function whose
result is adequate to use in a recursive call. -/
def rec_shrink {α : Type*} [has_sizeof α] (t : α)
(sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) :
shrink_fn { t' : α // sizeof_lt t' t }
| ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' },
⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht'
lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t :=
by cases t; unfold_wf; linarith
instance : functor tree :=
{ map := @tree.map }
/--
Recursion principle for shrinking tree-like structures.
-/
def rec_shrink_with [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x })) :
shrink_fn α :=
well_founded.fix (sizeof_measure_wf _) $ λ t f_rec,
lazy_list.join
(lazy_list.of_list $
shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _)
lemma rec_shrink_with_eq [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x }))
(x : α) :
rec_shrink_with shrink_a x =
lazy_list.join
(lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) :=
begin
conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], },
congr, ext ⟨y, h⟩, refl
end
/-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree,
each subtrees, and by shrinking the subtree to recombine them.
This strategy is taken directly from Haskell's QuickCheck -/
def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) :=
rec_shrink_with $ λ t,
match t with
| tree.nil := λ f_rec, []
| (tree.node x t₀ t₁) :=
λ f_rec,
have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁),
by clear _match; have := tree.one_le_sizeof t₀;
dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *;
unfold_wf; linarith,
have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
[lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩],
(prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map
$ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁,
by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩]
end
instance sampleable_tree : sampleable_functor tree :=
{ wf := _,
sample := λ α sam_α, sized $ tree.sample sam_α,
shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α,
p_repr := @tree.has_repr }
/-- Type tag that signals to `slim_check` to use small values for a given type. -/
def small (α : Type*) := α
/-- Add the `small` type tag -/
def small.mk {α} (x : α) : small α := x
/-- Type tag that signals to `slim_check` to use large values for a given type. -/
def large (α : Type*) := α
/-- Add the `large` type tag -/
def large.mk {α} (x : α) : large α := x
instance small.functor : functor small := id.monad.to_functor
instance large.functor : functor large := id.monad.to_functor
instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default : α) ⟩
instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default : α) ⟩
instance small.sampleable_functor : sampleable_functor small :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance large.sampleable_functor : sampleable_functor large :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n * 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance ulift.sampleable_functor : sampleable_functor ulift.{u v} :=
{ wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩,
sample := λ α samp, uliftable.up_map ulift.up $ samp,
shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)),
p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ }
/-!
## Subtype instances
The following instances are meant to improve the testing of properties of the form
`∀ i j, i ≤ j, ...`
The naive way to test them is to choose two numbers `i` and `j` and check that
the proper ordering is satisfied. Instead, the following instances make it
so that `j` will be chosen with considerations to the required ordering
constraints. The benefit is that we will not have to discard any choice
of `j`.
-/
/-! ### Subtypes of `ℕ` -/
instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } :=
{ sample :=
do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial,
pure ⟨x, h.2⟩},
shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $
λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x }
instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y, by norm_num⟩ },
shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) },
subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, lt_tsub_iff_left.mp h'⟩) <$>
shrink (y - x) }
/- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice
to satisfy `x < y` -/
instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y+1, by linarith⟩ },
shrink := λ x, shrink _ }
/-! ### Subtypes of any `linear_ordered_add_comm_group` -/
instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { x : α // x ≤ y } :=
{ sample :=
do { x ← sample α,
pure ⟨y - |x|, sub_le_self _ (abs_nonneg _) ⟩ },
shrink := λ _, lazy_list.nil }
instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { y : α // x ≤ y } :=
{ sample :=
do { y ← sample α,
pure ⟨x + |y|, by norm_num [abs_nonneg]⟩ },
shrink := λ _, lazy_list.nil }
/-!
### Subtypes of `ℤ`
Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search.
-/
instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs)
(λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring)
instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs)
(λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring)
instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $
by linarith [int.coe_nat_nonneg n]⟩)
(λ ⟨i, h⟩, (y - i - 1).nat_abs)
(λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring)
instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs)
(λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring)
/-! ### Subtypes of any `list` -/
instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } :=
{ sample := permutation_of xs,
shrink := λ _, lazy_list.nil }
instance perm'.slim_check {xs : list α} :
slim_check.sampleable { ys : list α // list.perm ys xs } :=
{ sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs,
shrink := λ _, lazy_list.nil }
setup_tactic_parser
open tactic
/--
Print (at most) 10 samples of a given type to stdout for debugging.
-/
def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do
xs ← io.run_rand $ uliftable.down $
do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up,
pure ⟨xs.map repr⟩ },
xs.mmap' io.put_str_ln
/-- Create a `gen α` expression from the argument of `#sample` -/
meta def mk_generator (e : expr) : tactic (expr × expr) := do
t ← infer_type e,
match t with
| `(gen %%t) := do
repr_inst ← mk_app ``has_repr [t] >>= mk_instance,
pure (repr_inst, e)
| _ := do
samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance,
repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst],
gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst],
pure (repr_inst, gen)
end
/--
`#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random
values of type `my_type` of using an increasing size parameter.
```lean
#sample nat
-- prints
-- 0
-- 0
-- 2
-- 24
-- 64
-- 76
-- 5
-- 132
-- 8
-- 449
-- or some other sequence of numbers
#sample list int
-- prints
-- []
-- [1, 1]
-- [-7, 9, -6]
-- [36]
-- [-500, 105, 260]
-- [-290]
-- [17, 156]
-- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968]
-- [-643]
-- [11892, 16329, -15095, -15461]
-- or whatever
```
-/
@[user_command]
meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit :=
do e ← texpr,
of_tactic $ do
e ← i_to_expr e,
(repr_inst, gen) ← mk_generator e,
print_samples ← mk_mapp ``print_samples [none, repr_inst, gen],
sample ← eval_expr (io unit) print_samples,
unsafe_run_io sample
end slim_check
|
933d0385db8a77b0f8660e528b22ad7417e56ffc | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/field_theory/abel_ruffini.lean | 63889b513a29bdd4c47286d8e5ba1b6aad19140b | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,299 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import group_theory.solvable
import field_theory.polynomial_galois_group
import ring_theory.roots_of_unity
/-!
# The Abel-Ruffini Theorem
This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable
by radicals, then its minimal polynomial has solvable Galois group.
## Main definitions
* `SBF F E` : the intermediate field of solvable-by-radicals elements
## Main results
* `solvable_gal_of_solvable_by_rad` : the minimal polynomial of an element of `SBF F E` has
solvable Galois group
-/
noncomputable theory
open_locale classical
open polynomial intermediate_field
section abel_ruffini
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
lemma gal_zero_is_solvable : is_solvable (0 : polynomial F).gal :=
by apply_instance
lemma gal_one_is_solvable : is_solvable (1 : polynomial F).gal :=
by apply_instance
lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal :=
by apply_instance
lemma gal_X_is_solvable : is_solvable (X : polynomial F).gal :=
by apply_instance
lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal :=
by apply_instance
lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : polynomial F).gal :=
by apply_instance
lemma gal_mul_is_solvable {p q : polynomial F}
(hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal :=
solvable_of_solvable_injective (gal.restrict_prod_injective p q)
lemma gal_prod_is_solvable {s : multiset (polynomial F)}
(hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal :=
begin
apply multiset.induction_on' s,
{ exact gal_one_is_solvable },
{ intros p t hps hts ht,
rw [multiset.insert_eq_cons, multiset.prod_cons],
exact gal_mul_is_solvable (hs p hps) ht },
end
lemma gal_is_solvable_of_splits {p q : polynomial F}
(hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) :
is_solvable p.gal :=
begin
haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq,
exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field),
end
lemma gal_is_solvable_tower (p q : polynomial F)
(hpq : p.splits (algebra_map F q.splitting_field))
(hp : is_solvable p.gal)
(hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) :
is_solvable q.gal :=
begin
let K := p.splitting_field,
let L := q.splitting_field,
haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩,
let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal :=
(is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr,
have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective,
haveI : is_solvable (K ≃ₐ[F] K) := hp,
haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj,
exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field,
end
section gal_X_pow_sub_C
lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : polynomial F).gal :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact gal_zero_is_solvable },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
apply is_solvable_of_comm,
intros σ τ,
ext a ha,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha,
have key : ∀ σ : (X ^ n - 1 : polynomial F).gal, ∃ m : ℕ, σ a = a ^ m,
{ intro σ,
obtain ⟨m, hm⟩ := σ.to_alg_hom.to_ring_hom.map_root_of_unity_eq_pow_self
⟨is_unit.unit (is_unit_of_pow_eq_one a n ha hn'),
by { ext, rwa [units.coe_pow, is_unit.unit_spec, subtype.coe_mk n hn'] }⟩,
use m,
convert hm,
all_goals { exact (is_unit.unit_spec _).symm } },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'],
end
lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F)
(h : (X ^ n - 1 : polynomial F).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal :=
begin
by_cases ha : a = 0,
{ rw [ha, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 :=
mt ((ring_hom.injective_iff _).mp (ring_hom.injective _) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←C_sub],
exact gal_C_is_solvable (1 - a) },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : X ^ n - C a ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_C hn').symm.trans (congr_arg leading_coeff h)),
have hn''' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c :=
λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (or.resolve_left h hn'''
(minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c
(by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))),
apply is_solvable_of_comm,
intros σ τ,
ext b hb,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c,
{ intro σ,
have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'],
obtain ⟨c, hc⟩ := mem_range key,
use c,
rw [hc, mul_div_cancel' (σ b) hb'] },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc],
rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm],
end
lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E]
(i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i :=
begin
have ha' : i a ≠ 0 := mt (i.injective_iff.mp (i.injective) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact splits_zero i },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - C a).degree ≠ 0 :=
ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn),
obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'',
rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
let s := ((X ^ n - C a).map i).roots,
have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h,
rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs,
have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C,
apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)),
rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map],
have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1,
{ rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] },
have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X),
{ rw [map_sub, map_sub, map_pow, map_X, map_C, map_one, sub_comp, pow_comp, X_comp, C_comp,
mul_pow, ←C_pow, hb, mul_sub, ←mul_assoc, C_mul_C, one_mul] },
have key2 : (λ q : polynomial E, q.comp (C b * X)) ∘ (λ c : E, X - C c) =
(λ c : E, C b * (X - C (c / b))),
{ ext1 c,
change (X - C c).comp (C b * X) = C b * (X - C (c / b)),
rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] },
rw [key1, hs, prod_comp, multiset.map_map, key2, multiset.prod_map_mul, multiset.map_const,
multiset.prod_repeat, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul],
all_goals { exact field.to_nontrivial F },
end
lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal :=
begin
by_cases hx : x = 0,
{ rw [hx, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x),
{ exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) },
{ exact gal_X_pow_sub_one_is_solvable n },
{ rw [map_sub, map_pow, map_X, map_C],
apply gal_X_pow_sub_C_is_solvable_aux,
have key := splitting_field.splits (X ^ n - 1 : polynomial F),
rwa [←splits_id_iff_splits, map_sub, map_pow, map_X, map_one] at key },
end
end gal_X_pow_sub_C
variables (F)
/-- Inductive definition of solvable by radicals -/
inductive is_solvable_by_rad : E → Prop
| base (a : F) : is_solvable_by_rad (algebra_map F E a)
| add (a b : E) : is_solvable_by_rad a → is_solvable_by_rad b → is_solvable_by_rad (a + b)
| neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α)
| mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β)
| inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹
| rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α
variables (E)
/-- The intermediate field of solvable-by-radicals elements -/
def solvable_by_rad : intermediate_field F E :=
{ carrier := is_solvable_by_rad F,
zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero },
add_mem' := is_solvable_by_rad.add,
neg_mem' := is_solvable_by_rad.neg,
one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one },
mul_mem' := is_solvable_by_rad.mul,
inv_mem' := is_solvable_by_rad.inv,
algebra_map_mem' := is_solvable_by_rad.base }
namespace solvable_by_rad
variables {F} {E} {α : E}
lemma induction (P : solvable_by_rad F E → Prop)
(base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α))
(add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β))
(neg : ∀ α : solvable_by_rad F E, P α → P (-α))
(mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β))
(inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹)
(rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α)
(α : solvable_by_rad F E) : P α :=
begin
revert α,
suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β),
{ intro α,
obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α),
convert Pα,
exact subtype.ext hα₀.symm },
apply is_solvable_by_rad.rec,
{ exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ },
{ intros α n hn hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩,
convert Pα,
exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) }
end
theorem is_integral (α : solvable_by_rad F E) : is_integral F α :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ _, is_integral_algebra_map },
{ exact λ _ _, is_integral_add },
{ exact λ _, is_integral_neg },
{ exact λ _ _, is_integral_mul },
{ exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E))
(show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)),
by exact (is_algebraic_iff_is_integral F).mpr hα) },
{ intros α n hn hα,
obtain ⟨p, h1, h2⟩ := (is_algebraic_iff_is_integral F).mpr hα,
refine (is_algebraic_iff_is_integral F).mp ⟨p.comp (X ^ n),
⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩,
rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h,
rwa nat_degree_X_pow }
end
/-- The statement to be proved inductively -/
def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α :=
begin
let p := minpoly F (α ^ n),
have hp : p.comp (X ^ n) ≠ 0,
{ intro h,
cases (comp_eq_zero_iff.mp h) with h' h',
{ exact minpoly.ne_zero (is_integral (α ^ n)) h' },
{ exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } },
apply gal_is_solvable_of_splits,
{ exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n)))
(minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ },
{ refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _,
{ exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) },
{ obtain ⟨s, hs⟩ := exists_multiset_of_splits _ (splitting_field.splits p),
rw [map_comp, map_pow, map_X, hs, mul_comp, C_comp],
apply gal_mul_is_solvable (gal_C_is_solvable _),
rw prod_comp,
apply gal_prod_is_solvable,
intros q hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw [sub_comp, X_comp, C_comp],
exact gal_X_pow_sub_C_is_solvable n q } },
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ :=
begin
let p := (minpoly F α),
let q := (minpoly F β),
have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α))
(minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)),
let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits
begin
intros x hx,
cases hx,
rw hx,
exact ⟨is_integral α, hpq.1⟩,
cases hx,
exact ⟨is_integral β, hpq.2⟩,
end),
have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.unique'
(minpoly.irreducible (is_integral γ)) begin
suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0,
{ rw [aeval_alg_hom_apply, this, alg_hom.map_zero] },
apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective,
rw [ring_hom.map_zero, is_scalar_tower.algebra_map_aeval],
exact minpoly.aeval F γ,
end (minpoly.monic (is_integral γ)),
rw [P, key],
exact gal_is_solvable_of_splits ⟨normal.splits (splitting_field.normal _) _⟩
(gal_mul_is_solvable hα hβ),
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β :=
induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα
theorem is_solvable (α : solvable_by_rad F E) :
is_solvable (minpoly F α).gal :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } },
{ exact λ α β, induction2 (add_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (neg_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α β, induction2 (mul_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (inv_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α n, induction3 },
end
/-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an
`is_solvable_by_rad` root has solvable Galois group -/
lemma is_solvable' {α : E} {q : polynomial F} (q_irred : irreducible q)
(q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) :
_root_.is_solvable q.gal :=
begin
haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal,
{ rw [minpoly.unique'' q_irred q_aeval,
←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α,
from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl],
exact is_solvable ⟨α, hα⟩ },
refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _),
rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero],
exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩,
end
end solvable_by_rad
end abel_ruffini
|
3d3a893b0c4b53483ee557440222f04b1666f51f | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/library/src_field.lean | 0ec0bd55416caeecdc4338093ac671c689d620a6 | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,371 | lean | namespace mth1001
namespace myreal
section comm_group
class comm_group (R : Type*) :=
(add : R → R → R)
(zero : R)
(neg : R → R)
(add_comm : ∀ a b : R, add a b = add b a)
(add_assoc : ∀ a b c : R, add (add a b) c = add a (add b c))
(add_zero : ∀ a : R, add a zero = a)
(add_inv : ∀ a : R, add a (neg a) = zero)
variables {R : Type*} [comm_group R]
instance : has_add R := ⟨comm_group.add⟩
instance : has_zero R := ⟨comm_group.zero⟩
instance : has_neg R := ⟨comm_group.neg⟩
def sub (x y : R) := x + (-y)
instance : has_sub R := ⟨sub⟩
end comm_group
class myfield (R : Type*) extends comm_group R:=
(mul : R → R → R)
(mul_comm : ∀ a b : R, mul a b = mul b a)
(mul_assoc : ∀ a b c : R, mul (mul a b) c = mul a (mul b c))
(one : R)
(mul_one : ∀ a : R, mul a one = a)
(inv : R → R)
(mul_inv : ∀ a : R, a ≠ 0 → mul a (inv a) = one)
(mul_add : ∀ a b c : R, mul a (b + c) = mul a b + mul a c)
(zero_ne_one : (0 : R) ≠ (one : R))
variables {R : Type} [myfield R]
instance : has_mul R := ⟨myfield.mul⟩
instance : has_one R := ⟨myfield.one⟩
instance : has_inv R := ⟨myfield.inv⟩
def of_nat : ℕ → R
| 0 := (0 : R)
| (nat.succ x) := (of_nat x) + 1
instance : has_coe ℕ R := ⟨of_nat⟩
lemma coe_nat_succ (n : ℕ) : ((nat.succ n) : R) = (n : R) + (1 : R) := rfl
end myreal
end mth1001 |
3bad93515018b856645181625550298b1e6c274e | 5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61 | /archi/arm.lean | 76d3a1f23e742d6bc4e16a01892c086137c16c83 | [] | no_license | mbrodersen/kremlin | f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec | d4665929ce9012e93a0b05fc7063b96256bab86f | refs/heads/master | 1,624,057,268,130 | 1,496,957,084,000 | 1,496,957,084,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,214 | lean | import ..flocq
/- Architecture-dependent parameters for ARM -/
namespace archi
open flocq
def ptr64 : bool := ff
def big_endian : bool := sorry
def align_int64 := 8
def align_float64 := 8
def splitlong := tt
lemma splitlong_ptr32 : splitlong = tt → ptr64 = ff := λ_, rfl
def default_pl_64 : bool × nan_pl 53 :=
(ff, word.repr (2^51))
def choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool :=
/- Choose second NaN if pl2 is sNaN but pl1 is qNan.
In all other cases, choose first NaN -/
pl1.unsigned.test_bit 51 && bnot (pl2.unsigned.test_bit 51)
def default_pl_32 : bool × nan_pl 24 :=
(ff, word.repr (2^22))
def choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool :=
/- Choose second NaN if pl2 is sNaN but pl1 is qNan.
In all other cases, choose first NaN -/
pl1.unsigned.test_bit 22 && bnot (pl2.unsigned.test_bit 22)
def float_of_single_preserves_sNaN := ff
/- Which ABI to use : either the standard ARM EABI with floats passed
in integer registers, or the "hardfloat" variant of the EABI
that uses FP registers instead. -/
inductive abi_kind | Softfloat | Hardfloat
constant abi : abi_kind
end archi |
e446ae6ae15f9f99092d8ad95e1c9456d7cdbcda | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/well_founded.lean | fb82de79a2a55b5895579985e112f4e2ed0f4bce | [
"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 | 9,929 | lean | /-
Copyright (c) 2020 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import tactic.by_contra
import data.set.image
/-!
# Well-founded relations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A relation is well-founded if it can be used for induction: for each `x`, `(∀ y, r y x → P y) → P x`
implies `P x`. Well-founded relations can be used for induction and recursion, including
construction of fixed points in the space of dependent functions `Π x : α , β x`.
The predicate `well_founded` is defined in the core library. In this file we prove some extra lemmas
and provide a few new definitions: `well_founded.min`, `well_founded.sup`, and `well_founded.succ`,
and an induction principle `well_founded.induction_bot`.
-/
variables {α : Type*}
namespace well_founded
protected theorem is_asymm {α : Sort*} {r : α → α → Prop} (h : well_founded r) : is_asymm α r :=
⟨h.asymmetric⟩
instance {α : Sort*} [has_well_founded α] : is_asymm α has_well_founded.r :=
has_well_founded.wf.is_asymm
protected theorem is_irrefl {α : Sort*} {r : α → α → Prop} (h : well_founded r) : is_irrefl α r :=
(@is_asymm.is_irrefl α r h.is_asymm)
instance {α : Sort*} [has_well_founded α] : is_irrefl α has_well_founded.r :=
is_asymm.is_irrefl
/-- If `r` is a well-founded relation, then any nonempty set has a minimal element
with respect to `r`. -/
theorem has_min {α} {r : α → α → Prop} (H : well_founded r)
(s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a
| ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, not_imp_not.1 $ λ hne hx, hne $
⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha
/-- A minimal element of a nonempty set in a well-founded order.
If you're working with a nonempty linear order, consider defining a
`conditionally_complete_linear_order_bot` instance via
`well_founded.conditionally_complete_linear_order_with_bot` and using `Inf` instead. -/
noncomputable def min {r : α → α → Prop} (H : well_founded r)
(s : set α) (h : s.nonempty) : α :=
classical.some (H.has_min s h)
theorem min_mem {r : α → α → Prop} (H : well_founded r)
(s : set α) (h : s.nonempty) : H.min s h ∈ s :=
let ⟨h, _⟩ := classical.some_spec (H.has_min s h) in h
theorem not_lt_min {r : α → α → Prop} (H : well_founded r)
(s : set α) (h : s.nonempty) {x} (hx : x ∈ s) : ¬ r x (H.min s h) :=
let ⟨_, h'⟩ := classical.some_spec (H.has_min s h) in h' _ hx
theorem well_founded_iff_has_min {r : α → α → Prop} : (well_founded r) ↔
∀ (s : set α), s.nonempty → ∃ m ∈ s, ∀ x ∈ s, ¬ r x m :=
begin
refine ⟨λ h, h.has_min, λ h, ⟨λ x, _⟩⟩,
by_contra hx,
obtain ⟨m, hm, hm'⟩ := h _ ⟨x, hx⟩,
refine hm ⟨_, λ y hy, _⟩,
by_contra hy',
exact hm' y hy' hy
end
open set
/-- The supremum of a bounded, well-founded order -/
protected noncomputable def sup {r : α → α → Prop} (wf : well_founded r) (s : set α)
(h : bounded r s) : α :=
wf.min { x | ∀a ∈ s, r a x } h
protected lemma lt_sup {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s)
{x} (hx : x ∈ s) : r x (wf.sup s h) :=
min_mem wf { x | ∀a ∈ s, r a x } h x hx
section
open_locale classical
/-- A successor of an element `x` in a well-founded order is a minimal element `y` such that
`x < y` if one exists. Otherwise it is `x` itself. -/
protected noncomputable def succ {r : α → α → Prop} (wf : well_founded r) (x : α) : α :=
if h : ∃y, r x y then wf.min { y | r x y } h else x
protected lemma lt_succ {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) :
r x (wf.succ x) :=
by { rw [well_founded.succ, dif_pos h], apply min_mem }
end
protected lemma lt_succ_iff {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y)
(y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x :=
begin
split,
{ intro h', have : ¬r x y,
{ intro hy, rw [well_founded.succ, dif_pos] at h',
exact wo.wf.not_lt_min _ h hy h' },
rcases trichotomous_of r x y with hy | hy | hy,
exfalso, exact this hy,
right, exact hy.symm,
left, exact hy },
rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h
end
section linear_order
variables {β : Type*} [linear_order β] (h : well_founded ((<) : β → β → Prop))
{γ : Type*} [partial_order γ]
theorem min_le {x : β} {s : set β} (hx : x ∈ s) (hne : s.nonempty := ⟨x, hx⟩) :
h.min s hne ≤ x :=
not_lt.1 $ h.not_lt_min _ _ hx
private theorem eq_strict_mono_iff_eq_range_aux {f g : β → γ} (hf : strict_mono f)
(hg : strict_mono g) (hfg : set.range f = set.range g) {b : β} (H : ∀ a < b, f a = g a) :
f b ≤ g b :=
begin
obtain ⟨c, hc⟩ : g b ∈ set.range f := by { rw hfg, exact set.mem_range_self b },
cases lt_or_le c b with hcb hbc,
{ rw [H c hcb] at hc,
rw hg.injective hc at hcb,
exact hcb.false.elim },
{ rw ←hc,
exact hf.monotone hbc }
end
include h
theorem eq_strict_mono_iff_eq_range {f g : β → γ} (hf : strict_mono f)
(hg : strict_mono g) : set.range f = set.range g ↔ f = g :=
⟨λ hfg, begin
funext a,
apply h.induction a,
exact λ b H, le_antisymm
(eq_strict_mono_iff_eq_range_aux hf hg hfg H)
(eq_strict_mono_iff_eq_range_aux hg hf hfg.symm (λ a hab, (H a hab).symm))
end, congr_arg _⟩
theorem self_le_of_strict_mono {f : β → β} (hf : strict_mono f) : ∀ n, n ≤ f n :=
by { by_contra' h₁, have h₂ := h.min_mem _ h₁, exact h.not_lt_min _ h₁ (hf h₂) h₂ }
end linear_order
end well_founded
namespace function
variables {β : Type*} (f : α → β)
section has_lt
variables [has_lt β] (h : well_founded ((<) : β → β → Prop))
/-- Given a function `f : α → β` where `β` carries a well-founded `<`, this is an element of `α`
whose image under `f` is minimal in the sense of `function.not_lt_argmin`. -/
noncomputable def argmin [nonempty α] : α :=
well_founded.min (inv_image.wf f h) set.univ set.univ_nonempty
lemma not_lt_argmin [nonempty α] (a : α) : ¬ f a < f (argmin f h) :=
well_founded.not_lt_min (inv_image.wf f h) _ _ (set.mem_univ a)
/-- Given a function `f : α → β` where `β` carries a well-founded `<`, and a non-empty subset `s`
of `α`, this is an element of `s` whose image under `f` is minimal in the sense of
`function.not_lt_argmin_on`. -/
noncomputable def argmin_on (s : set α) (hs : s.nonempty) : α :=
well_founded.min (inv_image.wf f h) s hs
@[simp] lemma argmin_on_mem (s : set α) (hs : s.nonempty) :
argmin_on f h s hs ∈ s :=
well_founded.min_mem _ _ _
@[simp] lemma not_lt_argmin_on (s : set α) {a : α} (ha : a ∈ s)
(hs : s.nonempty := set.nonempty_of_mem ha) :
¬ f a < f (argmin_on f h s hs) :=
well_founded.not_lt_min (inv_image.wf f h) s hs ha
end has_lt
section linear_order
variables [linear_order β] (h : well_founded ((<) : β → β → Prop))
@[simp] lemma argmin_le (a : α) [nonempty α] : f (argmin f h) ≤ f a :=
not_lt.mp $ not_lt_argmin f h a
@[simp] lemma argmin_on_le (s : set α) {a : α} (ha : a ∈ s)
(hs : s.nonempty := set.nonempty_of_mem ha) : f (argmin_on f h s hs) ≤ f a :=
not_lt.mp $ not_lt_argmin_on f h s ha hs
end linear_order
end function
section induction
/-- Let `r` be a relation on `α`, let `f : α → β` be a function, let `C : β → Prop`, and
let `bot : α`. This induction principle shows that `C (f bot)` holds, given that
* some `a` that is accessible by `r` satisfies `C (f a)`, and
* for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c`
satisfying `r c b` and `C (f c)`. -/
lemma acc.induction_bot' {α β} {r : α → α → Prop} {a bot : α} (ha : acc r a) {C : β → Prop}
{f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) : C (f a) → C (f bot) :=
@acc.rec_on _ _ (λ x, C (f x) → C (f bot)) _ ha $ λ x ac ih' hC,
(eq_or_ne (f x) (f bot)).elim (λ h, h ▸ hC)
(λ h, let ⟨y, hy₁, hy₂⟩ := ih x h hC in ih' y hy₁ hy₂)
/-- Let `r` be a relation on `α`, let `C : α → Prop` and let `bot : α`.
This induction principle shows that `C bot` holds, given that
* some `a` that is accessible by `r` satisfies `C a`, and
* for each `b ≠ bot` such that `C b` holds, there is `c` satisfying `r c b` and `C c`. -/
lemma acc.induction_bot {α} {r : α → α → Prop} {a bot : α} (ha : acc r a)
{C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot :=
ha.induction_bot' ih
/-- Let `r` be a well-founded relation on `α`, let `f : α → β` be a function,
let `C : β → Prop`, and let `bot : α`.
This induction principle shows that `C (f bot)` holds, given that
* some `a` satisfies `C (f a)`, and
* for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c`
satisfying `r c b` and `C (f c)`. -/
lemma well_founded.induction_bot' {α β} {r : α → α → Prop} (hwf : well_founded r) {a bot : α}
{C : β → Prop} {f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) :
C (f a) → C (f bot) :=
(hwf.apply a).induction_bot' ih
/-- Let `r` be a well-founded relation on `α`, let `C : α → Prop`, and let `bot : α`.
This induction principle shows that `C bot` holds, given that
* some `a` satisfies `C a`, and
* for each `b` that satisfies `C b`, there is `c` satisfying `r c b` and `C c`.
The naming is inspired by the fact that when `r` is transitive, it follows that `bot` is
the smallest element w.r.t. `r` that satisfies `C`. -/
lemma well_founded.induction_bot {α} {r : α → α → Prop} (hwf : well_founded r) {a bot : α}
{C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot :=
hwf.induction_bot' ih
end induction
|
ef56890677c6a875be51243bd3c745325f8ce088 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/linear_algebra/free_module/finite/rank.lean | 81b13a1f008980722352d91cc6948358fe3ddf5e | [
"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 | 4,975 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.free_module.rank
import linear_algebra.free_module.finite.basic
/-!
# Rank of finite free modules
This is a basic API for the rank of finite free modules.
-/
--TODO: `linear_algebra/finite_dimensional` should import this file, and a lot of results should
--be moved here.
universes u v w
variables (R : Type u) (M : Type v) (N : Type w)
open_locale tensor_product direct_sum big_operators cardinal
open cardinal finite_dimensional fintype
namespace module.free
section ring
variables [ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M]
variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N]
/-- The rank of a finite and free module is finite. -/
lemma rank_lt_aleph_0 : module.rank R M < ℵ₀ :=
begin
letI := nontrivial_of_invariant_basis_number R,
rw [← (choose_basis R M).mk_eq_dim'', lt_aleph_0_iff_fintype],
exact nonempty.intro infer_instance
end
/-- If `M` is finite and free, `finrank M = rank M`. -/
@[simp] lemma finrank_eq_rank : ↑(finrank R M) = module.rank R M :=
by { rw [finrank, cast_to_nat_of_lt_aleph_0 (rank_lt_aleph_0 R M)] }
/-- The finrank of a free module `M` over `R` is the cardinality of `choose_basis_index R M`. -/
lemma finrank_eq_card_choose_basis_index : finrank R M = @card (choose_basis_index R M)
(@choose_basis_index.fintype R M _ _ _ _ (nontrivial_of_invariant_basis_number R) _) :=
begin
letI := nontrivial_of_invariant_basis_number R,
simp [finrank, rank_eq_card_choose_basis_index]
end
/-- The finrank of `(ι →₀ R)` is `fintype.card ι`. -/
@[simp] lemma finrank_finsupp {ι : Type v} [fintype ι] : finrank R (ι →₀ R) = card ι :=
by { rw [finrank, rank_finsupp, ← mk_to_nat_eq_card, to_nat_lift] }
/-- The finrank of `(ι → R)` is `fintype.card ι`. -/
lemma finrank_pi {ι : Type v} [fintype ι] : finrank R (ι → R) = card ι :=
by simp [finrank]
/-- The finrank of the direct sum is the sum of the finranks. -/
@[simp] lemma finrank_direct_sum {ι : Type v} [fintype ι] (M : ι → Type w)
[Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)]
[Π (i : ι), module.finite R (M i)] : finrank R (⨁ i, M i) = ∑ i, finrank R (M i) :=
begin
letI := nontrivial_of_invariant_basis_number R,
simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_direct_sum,
← mk_sigma, mk_to_nat_eq_card, card_sigma],
end
/-- The finrank of `M × N` is `(finrank R M) + (finrank R N)`. -/
@[simp] lemma finrank_prod : finrank R (M × N) = (finrank R M) + (finrank R N) :=
by { simp [finrank, rank_lt_aleph_0 R M, rank_lt_aleph_0 R N] }
/-- The finrank of a finite product is the sum of the finranks. -/
--TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field.
lemma finrank_pi_fintype {ι : Type v} [fintype ι] {M : ι → Type w}
[Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)]
[Π (i : ι), module.finite R (M i)] : finrank R (Π i, M i) = ∑ i, finrank R (M i) :=
begin
letI := nontrivial_of_invariant_basis_number R,
simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_pi_fintype,
← mk_sigma, mk_to_nat_eq_card, card_sigma],
end
/-- If `m` and `n` are `fintype`, the finrank of `m × n` matrices is
`(fintype.card m) * (fintype.card n)`. -/
lemma finrank_matrix (m n : Type v) [fintype m] [fintype n] :
finrank R (matrix m n R) = (card m) * (card n) :=
by { simp [finrank] }
end ring
section comm_ring
variables [comm_ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M]
variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N]
/-- The finrank of `M →ₗ[R] N` is `(finrank R M) * (finrank R N)`. -/
--TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field.
lemma finrank_linear_hom : finrank R (M →ₗ[R] N) = (finrank R M) * (finrank R N) :=
begin
classical,
letI := nontrivial_of_invariant_basis_number R,
have h := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)),
let b := (matrix.std_basis _ _ _).map h.symm,
rw [finrank, dim_eq_card_basis b, ← mk_fintype, mk_to_nat_eq_card, finrank, finrank,
rank_eq_card_choose_basis_index, rank_eq_card_choose_basis_index, mk_to_nat_eq_card,
mk_to_nat_eq_card, card_prod, mul_comm]
end
/-- The finrank of `M ⊗[R] N` is `(finrank R M) * (finrank R N)`. -/
@[simp] lemma finrank_tensor_product (M : Type v) (N : Type w) [add_comm_group M] [module R M]
[module.free R M] [add_comm_group N] [module R N] [module.free R N] :
finrank R (M ⊗[R] N) = (finrank R M) * (finrank R N) :=
by { simp [finrank] }
end comm_ring
end module.free
|
6e9e1383c79bb582055d66a9cd8c0efbe026d653 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /doc/demo/tc.lean | e360d91ef69aa95b73d344658680a6793c21e2b0 | [
"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,719 | lean | import macros
definition reflexive {A : TypeU} (R : A → A → Bool) := ∀ x, R x x
definition transitive {A : TypeU} (R : A → A → Bool) := ∀ x y z, R x y → R y z → R x z
definition subrelation {A : TypeU} (R1 : A → A → Bool) (R2 : A → A → Bool) := ∀ x y, R1 x y → R2 x y
infix 50 ⊆ : subrelation
-- (tcls R) is the transitive closure of relation R
-- We define it as the intersection of all transitive relations containing R
definition tcls {A : TypeU} (R : A → A → Bool) (a b : A)
:= ∀ P, (reflexive P) → (transitive P) → (R ⊆ P) → P a b
notation 65 _⁺ : tcls -- use superscript + as notation for transitive closure
theorem tcls_trans {A : TypeU} {R : A → A → Bool} {a b c : A} (Hab : R⁺ a b) (Hbc : R⁺ b c) : R⁺ a c
:= take P, assume Hrefl Htrans Hsub,
let Pab : P a b := Hab P Hrefl Htrans Hsub,
Pbc : P b c := Hbc P Hrefl Htrans Hsub
in Htrans a b c Pab Pbc
theorem tcls_refl {A : TypeU} (R : A → A → Bool) : ∀ a, R⁺ a a
:= take a P, assume Hrefl Htrans Hsub,
Hrefl a
theorem tcls_sub {A : TypeU} (R : A → A → Bool) : R ⊆ R⁺
:= take a b,
assume Hab : R a b,
have R⁺ a b :
take P, assume Hrefl Htrans Hsub,
Hsub a b Hab
theorem tcls_step {A : TypeU} {R : A → A → Bool} {a b c : A} (H1 : R a b) (H2 : R⁺ b c) : R⁺ a c
:= take P, assume Hrefl Htrans Hsub,
Htrans a b c (Hsub a b H1) (H2 P Hrefl Htrans Hsub)
theorem tcls_smallest {A : TypeU} (R : A → A → Bool) : ∀ P, (reflexive P) → (transitive P) → (R ⊆ P) → (R⁺ ⊆ P)
:= take P, assume Hrefl Htrans Hsub,
take a b, assume H : R⁺ a b,
have P a b : H P Hrefl Htrans Hsub
|
b205698e7a90c908ef37d8507a59bb6ad31ba4bf | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/closed/cartesian.lean | 7772aafeadb2548bc1a2e2498b059e087f5fc693 | [
"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 | 14,744 | lean | /-
Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Edward Ayers, Thomas Read
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.preserves.shapes.binary_products
import category_theory.closed.monoidal
import category_theory.monoidal.of_has_finite_products
import category_theory.adjunction
import category_theory.adjunction.mates
import category_theory.epi_mono
/-!
# Cartesian closed categories
Given a category with finite products, the cartesian monoidal structure is provided by the local
instance `monoidal_of_has_finite_products`.
We define exponentiable objects to be closed objects with respect to this monoidal structure,
i.e. `(X × -)` is a left adjoint.
We say a category is cartesian closed if every object is exponentiable
(equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal).
Show that exponential forms a difunctor and define the exponential comparison morphisms.
## TODO
Some of the results here are true more generally for closed objects and
for closed monoidal categories, and these could be generalised.
-/
universes v u u₂
noncomputable theory
namespace category_theory
open category_theory category_theory.category category_theory.limits
local attribute [instance] monoidal_of_has_finite_products
/--
An object `X` is *exponentiable* if `(X × -)` is a left adjoint.
We define this as being `closed` in the cartesian monoidal structure.
-/
abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) :=
closed X
/--
If `X` and `Y` are exponentiable then `X ⨯ Y` is.
This isn't an instance because it's not usually how we want to construct exponentials, we'll usually
prove all objects are exponential uniformly.
-/
def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C}
(hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) :=
{ is_adj :=
begin
haveI := hX.is_adj,
haveI := hY.is_adj,
exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm
end }
/--
The terminal object is always exponentiable.
This isn't an instance because most of the time we'll prove cartesian closed for all objects
at once, rather than just for this one.
-/
def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] :
exponentiable ⊤_C :=
unit_closed
/--
A category `C` is cartesian closed if it has finite products and every object is exponentiable.
We define this as `monoidal_closed` with respect to the cartesian monoidal structure.
-/
abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] :=
monoidal_closed C
variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C}
section exp
variables [has_finite_products C] [exponentiable A]
/-- This is (-)^A. -/
def exp : C ⥤ C :=
(@closed.is_adj _ _ _ A _).right
/-- The adjunction between A ⨯ - and (-)^A. -/
def exp.adjunction : prod.functor.obj A ⊣ exp A :=
closed.is_adj.adj
/-- The evaluation natural transformation. -/
def ev : exp A ⋙ prod.functor.obj A ⟶ 𝟭 C :=
(exp.adjunction A).counit
/-- The coevaluation natural transformation. -/
def coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A :=
(exp.adjunction A).unit
@[simp] lemma exp_adjunction_counit : (exp.adjunction A).counit = ev A := rfl
@[simp] lemma exp_adjunction_unit : (exp.adjunction A).unit = coev A := rfl
@[simp, reassoc]
lemma ev_naturality {X Y : C} (f : X ⟶ Y) :
limits.prod.map (𝟙 A) ((exp A).map f) ≫ (ev A).app Y = (ev A).app X ≫ f :=
(ev A).naturality f
@[simp, reassoc]
lemma coev_naturality {X Y : C} (f : X ⟶ Y) :
f ≫ (coev A).app Y = (coev A).app X ≫ (exp A).map (limits.prod.map (𝟙 A) f) :=
(coev A).naturality f
notation A ` ⟹ `:20 B:20 := (exp A).obj B
notation B ` ^^ `:30 A:30 := (exp A).obj B
@[simp, reassoc] lemma ev_coev :
limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) :=
adjunction.left_triangle_components (exp.adjunction A)
@[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) :=
adjunction.right_triangle_components (exp.adjunction A)
instance : preserves_colimits (prod.functor.obj A) :=
(exp.adjunction A).left_adjoint_preserves_colimits
end exp
variables {A}
-- Wrap these in a namespace so we don't clash with the core versions.
namespace cartesian_closed
variables [has_finite_products C] [exponentiable A]
/-- Currying in a cartesian closed category. -/
def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) :=
(exp.adjunction A).hom_equiv _ _
/-- Uncurrying in a cartesian closed category. -/
def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) :=
((exp.adjunction A).hom_equiv _ _).symm
@[simp] lemma hom_equiv_apply_eq (f : A ⨯ Y ⟶ X) :
(exp.adjunction A).hom_equiv _ _ f = curry f := rfl
@[simp] lemma hom_equiv_symm_apply_eq (f : Y ⟶ A ⟹ X) :
((exp.adjunction A).hom_equiv _ _).symm f = uncurry f := rfl
end cartesian_closed
open cartesian_closed
variables [has_finite_products C] [exponentiable A]
@[reassoc]
lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) :
curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g :=
adjunction.hom_equiv_naturality_left _ _ _
@[reassoc]
lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') :
curry (f ≫ g) = curry f ≫ (exp _).map g :=
adjunction.hom_equiv_naturality_right _ _ _
@[reassoc]
lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') :
uncurry (f ≫ (exp _).map g) = uncurry f ≫ g :=
adjunction.hom_equiv_naturality_right_symm _ _ _
@[reassoc]
lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) :
uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g :=
adjunction.hom_equiv_naturality_left_symm _ _ _
@[simp]
lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).left_inv f
@[simp]
lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).right_inv f
lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
curry f = g ↔ f = uncurry g :=
adjunction.hom_equiv_apply_eq _ f g
lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
g = curry f ↔ uncurry g = f :=
adjunction.eq_hom_equiv_apply _ f g
-- I don't think these two should be simp.
lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X :=
adjunction.hom_equiv_counit _
lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g :=
adjunction.hom_equiv_unit _
lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X :=
by rw [uncurry_eq, prod.map_id_id, id_comp]
lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X :=
by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id }
lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) :=
(closed.is_adj.adj.hom_equiv _ _).injective
lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) :=
(closed.is_adj.adj.hom_equiv _ _).symm.injective
/--
Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`.
The typeclass argument is explicit: any instance can be used.
-/
def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X :=
yoneda.ext (⊤_ C ⟹ X) X
(λ Y f, (prod.left_unitor Y).inv ≫ uncurry f)
(λ Y f, curry ((prod.left_unitor Y).hom ≫ f))
(λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] )
(λ Z g, by simp)
(λ Z W f g, by rw [uncurry_natural_left, prod.left_unitor_inv_naturality_assoc f] )
/-- The internal element which points at the given morphism. -/
def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) :=
curry (limits.prod.fst ≫ f)
section pre
variables {B}
/-- Pre-compose an internal hom with an external hom. -/
def pre (f : B ⟶ A) [exponentiable B] : exp A ⟶ exp B :=
transfer_nat_trans_self (exp.adjunction _) (exp.adjunction _) (prod.functor.map f)
lemma prod_map_pre_app_comp_ev (f : B ⟶ A) [exponentiable B] (X : C) :
limits.prod.map (𝟙 B) ((pre f).app X) ≫ (ev B).app X =
limits.prod.map f (𝟙 (A ⟹ X)) ≫ (ev A).app X :=
transfer_nat_trans_self_counit _ _ (prod.functor.map f) X
lemma uncurry_pre (f : B ⟶ A) [exponentiable B] (X : C) :
uncurry ((pre f).app X) = limits.prod.map f (𝟙 _) ≫ (ev A).app X :=
begin
rw [uncurry_eq, prod_map_pre_app_comp_ev]
end
lemma coev_app_comp_pre_app (f : B ⟶ A) [exponentiable B] :
(coev A).app X ≫ (pre f).app (A ⨯ X) = (coev B).app X ≫ (exp B).map (limits.prod.map f (𝟙 _)) :=
unit_transfer_nat_trans_self _ _ (prod.functor.map f) X
@[simp]
lemma pre_id (A : C) [exponentiable A] : pre (𝟙 A) = 𝟙 _ :=
by simp [pre]
@[simp]
lemma pre_map {A₁ A₂ A₃ : C} [exponentiable A₁] [exponentiable A₂] [exponentiable A₃]
(f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) :
pre (f ≫ g) = pre g ≫ pre f :=
by rw [pre, pre, pre, transfer_nat_trans_self_comp, prod.functor.map_comp]
end pre
/-- The internal hom functor given by the cartesian closed structure. -/
def internal_hom [cartesian_closed C] : Cᵒᵖ ⥤ C ⥤ C :=
{ obj := λ X, exp X.unop,
map := λ X Y f, pre f.unop }
/-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/
@[simps]
def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I :=
{ hom := limits.prod.snd,
inv := t.to _,
hom_inv_id' :=
begin
have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _),
rw ← curry_eq_iff,
apply t.hom_ext,
rw [this, ← uncurry_natural_right, ← eq_curry_iff],
apply t.hom_ext,
end,
inv_hom_id' := t.hom_ext _ _ }
/-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/
def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I :=
limits.prod.braiding _ _ ≪≫ zero_mul t
/-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/
def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C :=
{ hom := default _,
inv := curry ((mul_zero t).hom ≫ t.to _),
hom_inv_id' :=
begin
rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv],
{ apply t.hom_ext },
{ apply_instance },
{ apply_instance }
end }
-- TODO: Generalise the below to its commutated variants.
-- TODO: Define a distributive category, so that zero_mul and friends can be derived from this.
/-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/
def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) :
(Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) :=
{ hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr),
inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)),
hom_inv_id' :=
begin
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry],
rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry],
end,
inv_hom_id' :=
begin
rw [← uncurry_natural_right, ←eq_curry_iff],
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id],
rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id],
end }
/--
If an initial object `I` exists in a CCC then it is a strict initial object,
i.e. any morphism to `I` is an iso.
This actually shows a slightly stronger version: any morphism to an initial object from an
exponentiable object is an isomorphism.
-/
lemma strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f :=
begin
haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _,
rw [zero_mul_hom, prod.lift_snd] at _inst,
haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩,
apply is_iso_of_mono_of_split_epi
end
instance to_initial_is_iso [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f :=
strict_initial initial_is_initial _
/-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/
lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) :=
⟨λ B g h _,
begin
haveI := strict_initial t g,
haveI := strict_initial t h,
exact eq_of_inv_eq_inv (t.hom_ext _ _)
end⟩
instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) :=
initial_mono B initial_is_initial
variables {D : Type u₂} [category.{v} D]
section functor
variables [has_finite_products D]
/--
Transport the property of being cartesian closed across an equivalence of categories.
Note we didn't require any coherence between the choice of finite products here, since we transport
along the `prod_comparison` isomorphism.
-/
def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D :=
{ closed := λ X,
{ is_adj :=
begin
haveI q : exponentiable (e.inverse.obj X) := infer_instance,
have : is_left_adjoint (prod.functor.obj (e.inverse.obj X)) := q.is_adj,
have : e.functor ⋙ prod.functor.obj X ⋙ e.inverse ≅ prod.functor.obj (e.inverse.obj X),
apply nat_iso.of_components _ _,
intro Y,
{ apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _,
apply prod.map_iso (iso.refl _) (e.unit_iso.app Y).symm },
{ intros Y Z g,
dsimp [prod_comparison],
simp [prod.comp_lift, ← e.inverse.map_comp, ← e.inverse.map_comp_assoc],
-- I wonder if it would be a good idea to make `map_comp` a simp lemma the other way round
dsimp, simp -- See note [dsimp, simp]
},
{ have : is_left_adjoint (e.functor ⋙ prod.functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_nat_iso this.symm,
have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_comp e.inverse _,
have : (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) ⋙ e.functor ≅
prod.functor.obj X,
{ apply iso_whisker_right e.counit_iso (prod.functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _,
change prod.functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod.functor.obj X,
apply iso_whisker_left (prod.functor.obj X) e.counit_iso, },
resetI,
apply adjunction.left_adjoint_of_nat_iso this },
end } }
end functor
end category_theory
|
4f1c6147dc7027df50245568b0a85d9cbd909159 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/category_theory/limits/shapes/regular_mono.lean | 20f3251599d36188a8d63619aeec9ca172986082 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,465 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.limits.preserves.basic
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.strong_epi
import category_theory.limits.shapes.pullbacks
/-!
# Definitions and basic properties of regular monomorphisms and epimorphisms.
A regular monomorphism is a morphism that is the equalizer of some parallel pair.
We give the constructions
* `split_mono → regular_mono` and
* `regular_mono → mono`
as well as the dual constructions for regular epimorphisms. Additionally, we give the
construction
* `regular_epi ⟶ strong_epi`.
-/
noncomputable theory
namespace category_theory
open category_theory.limits
universes v₁ u₁ u₂
variables {C : Type u₁} [category.{v₁} C]
variables {X Y : C}
/-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/
class regular_mono (f : X ⟶ Y) :=
(Z : C)
(left right : Y ⟶ Z)
(w : f ≫ left = f ≫ right)
(is_limit : is_limit (fork.of_ι f w))
attribute [reassoc] regular_mono.w
/-- Every regular monomorphism is a monomorphism. -/
@[priority 100]
instance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f :=
mono_of_is_limit_parallel_pair regular_mono.is_limit
instance equalizer_regular (g h : X ⟶ Y) [has_limit (parallel_pair g h)] :
regular_mono (equalizer.ι g h) :=
{ Z := Y,
left := g,
right := h,
w := equalizer.condition g h,
is_limit := fork.is_limit.mk _ (λ s, limit.lift _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) }
/-- Every split monomorphism is a regular monomorphism. -/
@[priority 100]
instance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f :=
{ Z := Y,
left := 𝟙 Y,
right := retraction f ≫ f,
w := by tidy,
is_limit := split_mono_equalizes f }
/-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and
`regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/
def regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y)
(h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) :
{l : W ⟶ X // l ≫ f = k} :=
fork.is_limit.lift' regular_mono.is_limit _ h
/--
The second leg of a pullback cone is a regular monomorphism if the right component is too.
See also `pullback.snd_of_mono` for the basic monomorphism version, and
`regular_of_is_pullback_fst_of_regular` for the flipped version.
-/
def regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}
{k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k)
(t : is_limit (pullback_cone.mk _ _ comm)) :
regular_mono g :=
{ Z := hr.Z,
left := k ≫ hr.left,
right := k ≫ hr.right,
w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w],
is_limit :=
begin
apply fork.is_limit.mk' _ _,
intro s,
have l₁ : (fork.ι s ≫ k) ≫ regular_mono.left = (fork.ι s ≫ k) ≫ regular_mono.right,
rw [category.assoc, s.condition, category.assoc],
obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁,
obtain ⟨p, hp₁, hp₂⟩ := pullback_cone.is_limit.lift' t _ _ hl,
refine ⟨p, hp₂, _⟩,
intros m w,
have z : m ≫ g = p ≫ g := w.trans hp₂.symm,
apply t.hom_ext,
apply (pullback_cone.mk f g comm).equalizer_ext,
{ erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] },
{ exact z },
end }
/--
The first leg of a pullback cone is a regular monomorphism if the left component is too.
See also `pullback.fst_of_mono` for the basic monomorphism version, and
`regular_of_is_pullback_snd_of_regular` for the flipped version.
-/
def regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}
{k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k)
(t : is_limit (pullback_cone.mk _ _ comm)) :
regular_mono f :=
regular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t)
/-- A regular monomorphism is an isomorphism if it is an epimorphism. -/
def is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f :=
@is_iso_limit_cone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_mono.is_limit e
/-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/
class regular_epi (f : X ⟶ Y) :=
(W : C)
(left right : W ⟶ X)
(w : left ≫ f = right ≫ f)
(is_colimit : is_colimit (cofork.of_π f w))
attribute [reassoc] regular_epi.w
/-- Every regular epimorphism is an epimorphism. -/
@[priority 100]
instance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f :=
epi_of_is_colimit_parallel_pair regular_epi.is_colimit
instance coequalizer_regular (g h : X ⟶ Y) [has_colimit (parallel_pair g h)] :
regular_epi (coequalizer.π g h) :=
{ W := X,
left := g,
right := h,
w := coequalizer.condition g h,
is_colimit := cofork.is_colimit.mk _ (λ s, colimit.desc _ s) (by simp)
(λ s m w, by { ext1, simp [←w] }) }
/-- Every split epimorphism is a regular epimorphism. -/
@[priority 100]
instance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f :=
{ W := X,
left := 𝟙 X,
right := f ≫ section_ f,
w := by tidy,
is_colimit := split_epi_coequalizes f }
/-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and
`regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/
def regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W)
(h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) :
{l : Y ⟶ W // f ≫ l = k} :=
cofork.is_colimit.desc' (regular_epi.is_colimit) _ h
/--
The second leg of a pushout cocone is a regular epimorphism if the right component is too.
See also `pushout.snd_of_epi` for the basic epimorphism version, and
`regular_of_is_pushout_fst_of_regular` for the flipped version.
-/
def regular_of_is_pushout_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :
regular_epi h :=
{ W := gr.W,
left := gr.left ≫ f,
right := gr.right ≫ f,
w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w],
is_colimit :=
begin
apply cofork.is_colimit.mk' _ _,
intro s,
have l₁ : gr.left ≫ f ≫ s.π = gr.right ≫ f ≫ s.π,
rw [← category.assoc, ← category.assoc, s.condition],
obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.π s) l₁,
obtain ⟨p, hp₁, hp₂⟩ := pushout_cocone.is_colimit.desc' t _ _ hl.symm,
refine ⟨p, hp₁, _⟩,
intros m w,
have z := w.trans hp₁.symm,
apply t.hom_ext,
apply (pushout_cocone.mk _ _ comm).coequalizer_ext,
{ exact z },
{ erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl },
end }
/--
The first leg of a pushout cocone is a regular epimorphism if the left component is too.
See also `pushout.fst_of_epi` for the basic epimorphism version, and
`regular_of_is_pushout_snd_of_regular` for the flipped version.
-/
def regular_of_is_pushout_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :
regular_epi k :=
regular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t)
/-- A regular epimorphism is an isomorphism if it is a monomorphism. -/
def is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f :=
@is_iso_limit_cocone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_epi.is_colimit m
@[priority 100]
instance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f :=
{ epi := by apply_instance,
has_lift :=
begin
introsI,
have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u,
{ apply (cancel_mono z).1,
simp only [category.assoc, h, regular_epi.w_assoc] },
obtain ⟨t, ht⟩ := regular_epi.desc' f u this,
exact arrow.has_lift.mk ⟨t, ht, (cancel_epi f).1
(by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩,
end }
end category_theory
|
fbc8d1df93d390ae1400657c6f8501136bf6ecaa | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/types/arrow.hlean | 91a892eb184c100338277399ca92db12e789ad5b | [
"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 | 5,118 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about arrow types (function spaces)
-/
import types.pi
open eq equiv is_equiv funext pi is_trunc unit
namespace pi
variables {A A' : Type} {B B' : Type} {C : A → B → Type} {D : A → Type}
{a a' a'' : A} {b b' b'' : B} {f g : A → B} {d : D a} {d' : D a'}
-- all lemmas here are special cases of the ones for pi-types
/- Functorial action -/
variables (f0 : A' → A) (f1 : B → B')
definition arrow_functor [unfold_full] : (A → B) → (A' → B') := pi_functor f0 (λa, f1)
/- Equivalences -/
definition is_equiv_arrow_functor [constructor]
[H0 : is_equiv f0] [H1 : is_equiv f1] : is_equiv (arrow_functor f0 f1) :=
is_equiv_pi_functor f0 (λa, f1)
definition arrow_equiv_arrow_rev [constructor] (f0 : A' ≃ A) (f1 : B ≃ B')
: (A → B) ≃ (A' → B') :=
equiv.mk _ (is_equiv_arrow_functor f0 f1)
definition arrow_equiv_arrow [constructor] (f0 : A ≃ A') (f1 : B ≃ B') : (A → B) ≃ (A' → B') :=
arrow_equiv_arrow_rev (equiv.symm f0) f1
variable (A)
definition arrow_equiv_arrow_right [constructor] (f1 : B ≃ B') : (A → B) ≃ (A → B') :=
arrow_equiv_arrow_rev equiv.refl f1
variables {A} (B)
definition arrow_equiv_arrow_left_rev [constructor] (f0 : A' ≃ A) : (A → B) ≃ (A' → B) :=
arrow_equiv_arrow_rev f0 equiv.refl
definition arrow_equiv_arrow_left [constructor] (f0 : A ≃ A') : (A → B) ≃ (A' → B) :=
arrow_equiv_arrow f0 equiv.refl
variables {B}
definition arrow_equiv_arrow_right' [constructor] (f1 : A → (B ≃ B')) : (A → B) ≃ (A → B') :=
pi_equiv_pi_right f1
/- Equivalence if one of the types is contractible -/
variables (A B)
definition arrow_equiv_of_is_contr_left [constructor] [H : is_contr A] : (A → B) ≃ B :=
!pi_equiv_of_is_contr_left
definition arrow_equiv_of_is_contr_right [constructor] [H : is_contr B] : (A → B) ≃ unit :=
!pi_equiv_of_is_contr_right
/- Interaction with other type constructors -/
-- most of these are in the file of the other type constructor
definition arrow_empty_left [constructor] : (empty → B) ≃ unit :=
!pi_empty_left
definition arrow_unit_left [constructor] : (unit → B) ≃ B :=
!arrow_equiv_of_is_contr_left
definition arrow_unit_right [constructor] : (A → unit) ≃ unit :=
!arrow_equiv_of_is_contr_right
variables {A B}
/- Transport -/
definition arrow_transport {B C : A → Type} (p : a = a') (f : B a → C a)
: (transport (λa, B a → C a) p f) ~ (λb, p ▸ f (p⁻¹ ▸ b)) :=
eq.rec_on p (λx, idp)
/- Pathovers -/
definition arrow_pathover {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b b idpo),
end
definition arrow_pathover_left {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b : B a), f b =[p] g (p ▸ b)) : f =[p] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b),
end
definition arrow_pathover_right {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b' : B a'), f (p⁻¹ ▸ b') =[p] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b),
end
definition arrow_pathover_constant_left {B : Type} {C : A → Type} {f : B → C a} {g : B → C a'}
{p : a = a'} (r : Π(b : B), f b =[p] g b) : f =[p] g :=
pi_pathover_constant r
definition arrow_pathover_constant_right' {B : A → Type} {C : Type}
{f : B a → C} {g : B a' → C} {p : a = a'}
(r : Π⦃b : B a⦄ ⦃b' : B a'⦄ (q : b =[p] b'), f b = g b') : f =[p] g :=
arrow_pathover (λb b' q, pathover_of_eq (r q))
definition arrow_pathover_constant_right {B : A → Type} {C : Type} {f : B a → C}
{g : B a' → C} {p : a = a'} (r : Π(b : B a), f b = g (p ▸ b)) : f =[p] g :=
arrow_pathover_left (λb, pathover_of_eq (r b))
/- a lemma used for the flattening lemma -/
definition apo011_arrow_pathover_constant_right {f : D a → A'} {g : D a' → A'} {p : a = a'}
{q : d =[p] d'} (r : Π(d : D a), f d = g (p ▸ d))
: eq_of_pathover (apo11 (arrow_pathover_constant_right r) q) = r d ⬝ ap g (tr_eq_of_pathover q)
:=
begin
induction q, esimp at r,
eapply homotopy.rec_on r, clear r, esimp, intro r, induction r, esimp,
esimp [arrow_pathover_constant_right, arrow_pathover_left],
rewrite [eq_of_homotopy_idp]
end
/-
The fact that the arrow type preserves truncation level is a direct consequence
of the fact that pi's preserve truncation level
-/
definition is_trunc_arrow (B : Type) (n : trunc_index) [H : is_trunc n B] : is_trunc n (A → B) :=
_
end pi
|
5f079e909422e159f1fb64243ee31daf0ccf3951 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/print_ax1.lean | 7e3deeadcedf57454c111cd2a551279f0f6e1230 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36 | lean | import data.nat.basic
print axioms
|
cefd01231f6c36b0e3ff68be3defc942bdd953e3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/affine_space/basis.lean | 2dbba32d1541827c5ff751efab6a0c6434dee1c7 | [
"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 | 11,123 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import linear_algebra.affine_space.independent
import linear_algebra.basis
/-!
# Affine bases and barycentric coordinates
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Suppose `P` is an affine space modelled on the module `V` over the ring `k`, and `p : ι → P` is an
affine-independent family of points spanning `P`. Given this data, each point `q : P` may be written
uniquely as an affine combination: `q = w₀ p₀ + w₁ p₁ + ⋯` for some (finitely-supported) weights
`wᵢ`. For each `i : ι`, we thus have an affine map `P →ᵃ[k] k`, namely `q ↦ wᵢ`. This family of
maps is known as the family of barycentric coordinates. It is defined in this file.
## The construction
Fixing `i : ι`, and allowing `j : ι` to range over the values `j ≠ i`, we obtain a basis `bᵢ` of `V`
defined by `bᵢ j = p j -ᵥ p i`. Let `fᵢ j : V →ₗ[k] k` be the corresponding dual basis and let
`fᵢ = ∑ j, fᵢ j : V →ₗ[k] k` be the corresponding "sum of all coordinates" form. Then the `i`th
barycentric coordinate of `q : P` is `1 - fᵢ (q -ᵥ p i)`.
## Main definitions
* `affine_basis`: a structure representing an affine basis of an affine space.
* `affine_basis.coord`: the map `P →ᵃ[k] k` corresponding to `i : ι`.
* `affine_basis.coord_apply_eq`: the behaviour of `affine_basis.coord i` on `p i`.
* `affine_basis.coord_apply_ne`: the behaviour of `affine_basis.coord i` on `p j` when `j ≠ i`.
* `affine_basis.coord_apply`: the behaviour of `affine_basis.coord i` on `p j` for general `j`.
* `affine_basis.coord_apply_combination`: the characterisation of `affine_basis.coord i` in terms
of affine combinations, i.e., `affine_basis.coord i (w₀ p₀ + w₁ p₁ + ⋯) = wᵢ`.
## TODO
* Construct the affine equivalence between `P` and `{ f : ι →₀ k | f.sum = 1 }`.
-/
open_locale affine big_operators
open set
universes u₁ u₂ u₃ u₄
/-- An affine basis is a family of affine-independent points whose span is the top subspace. -/
@[protect_proj]
structure affine_basis (ι : Type u₁) (k : Type u₂) {V : Type u₃} (P : Type u₄)
[add_comm_group V] [affine_space V P] [ring k] [module k V] :=
(to_fun : ι → P)
(ind' : affine_independent k to_fun)
(tot' : affine_span k (range to_fun) = ⊤)
variables {ι ι' k V P : Type*} [add_comm_group V] [affine_space V P]
namespace affine_basis
section ring
variables [ring k] [module k V] (b : affine_basis ι k P) {s : finset ι} {i j : ι} (e : ι ≃ ι')
/-- The unique point in a single-point space is the simplest example of an affine basis. -/
instance : inhabited (affine_basis punit k punit) :=
⟨⟨id, affine_independent_of_subsingleton k id, by simp⟩⟩
include V
instance fun_like : fun_like (affine_basis ι k P) ι (λ _, P) :=
{ coe := affine_basis.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr' }
@[ext]
lemma ext {b₁ b₂ : affine_basis ι k P} (h : (b₁ : ι → P) = b₂) : b₁ = b₂ := fun_like.coe_injective h
lemma ind : affine_independent k b := b.ind'
lemma tot : affine_span k (range b) = ⊤ := b.tot'
include b
protected lemma nonempty : nonempty ι :=
not_is_empty_iff.mp $ λ hι,
by simpa only [@range_eq_empty _ _ hι, affine_subspace.span_empty, bot_ne_top] using b.tot
/-- Composition of an affine basis and an equivalence of index types. -/
def reindex (e : ι ≃ ι') : affine_basis ι' k P :=
⟨b ∘ e.symm, b.ind.comp_embedding e.symm.to_embedding,
by { rw [e.symm.surjective.range_comp], exact b.3 }⟩
@[simp, norm_cast] lemma coe_reindex : ⇑(b.reindex e) = b ∘ e.symm := rfl
@[simp] lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') := rfl
@[simp] lemma reindex_refl : b.reindex (equiv.refl _) = b := ext rfl
/-- Given an affine basis for an affine space `P`, if we single out one member of the family, we
obtain a linear basis for the model space `V`.
The linear basis corresponding to the singled-out member `i : ι` is indexed by `{j : ι // j ≠ i}`
and its `j`th element is `b j -ᵥ b i`. (See `basis_of_apply`.) -/
noncomputable def basis_of (i : ι) : basis {j : ι // j ≠ i} k V :=
basis.mk ((affine_independent_iff_linear_independent_vsub k b i).mp b.ind)
begin
suffices : submodule.span k (range (λ (j : {x // x ≠ i}), b ↑j -ᵥ b i)) =
vector_span k (range b),
{ rw [this, ← direction_affine_span, b.tot, affine_subspace.direction_top], exact le_rfl },
conv_rhs { rw ← image_univ, },
rw vector_span_image_eq_span_vsub_set_right_ne k b (mem_univ i),
congr,
ext v,
simp,
end
@[simp] lemma basis_of_apply (i : ι) (j : {j : ι // j ≠ i}) :
b.basis_of i j = b ↑j -ᵥ b i :=
by simp [basis_of]
@[simp] lemma basis_of_reindex (i : ι') :
(b.reindex e).basis_of i =
(b.basis_of $ e.symm i).reindex (e.subtype_equiv $ λ _, e.eq_symm_apply.not) :=
by { ext j, simp }
/-- The `i`th barycentric coordinate of a point. -/
noncomputable def coord (i : ι) : P →ᵃ[k] k :=
{ to_fun := λ q, 1 - (b.basis_of i).sum_coords (q -ᵥ b i),
linear := -(b.basis_of i).sum_coords,
map_vadd' := λ q v, by rw [vadd_vsub_assoc, linear_map.map_add, vadd_eq_add, linear_map.neg_apply,
sub_add_eq_sub_sub_swap, add_comm, sub_eq_add_neg], }
@[simp] lemma linear_eq_sum_coords (i : ι) :
(b.coord i).linear = -(b.basis_of i).sum_coords :=
rfl
@[simp] lemma coord_reindex (i : ι') :
(b.reindex e).coord i = b.coord (e.symm i) :=
by { ext, classical, simp [affine_basis.coord] }
@[simp] lemma coord_apply_eq (i : ι) : b.coord i (b i) = 1 :=
by simp only [coord, basis.coe_sum_coords, linear_equiv.map_zero, linear_equiv.coe_coe,
sub_zero, affine_map.coe_mk, finsupp.sum_zero_index, vsub_self]
@[simp] lemma coord_apply_ne (h : i ≠ j) : b.coord i (b j) = 0 :=
by rw [coord, affine_map.coe_mk, ← subtype.coe_mk j h.symm, ← b.basis_of_apply,
basis.sum_coords_self_apply, sub_self]
lemma coord_apply [decidable_eq ι] (i j : ι) : b.coord i (b j) = if i = j then 1 else 0 :=
by cases eq_or_ne i j; simp [h]
@[simp] lemma coord_apply_combination_of_mem (hi : i ∈ s) {w : ι → k} (hw : s.sum w = 1) :
b.coord i (s.affine_combination k b w) = w i :=
begin
classical,
simp only [coord_apply, hi, finset.affine_combination_eq_linear_combination, if_true, mul_boole,
hw, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination b w hw],
end
@[simp] lemma coord_apply_combination_of_not_mem (hi : i ∉ s) {w : ι → k} (hw : s.sum w = 1) :
b.coord i (s.affine_combination k b w) = 0 :=
begin
classical,
simp only [coord_apply, hi, finset.affine_combination_eq_linear_combination, if_false, mul_boole,
hw, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination b w hw],
end
@[simp] lemma sum_coord_apply_eq_one [fintype ι] (q : P) :
∑ i, b.coord i q = 1 :=
begin
have hq : q ∈ affine_span k (range b), { rw b.tot, exact affine_subspace.mem_top k V q, },
obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq,
convert hw,
ext i,
exact b.coord_apply_combination_of_mem (finset.mem_univ i) hw,
end
@[simp] lemma affine_combination_coord_eq_self [fintype ι] (q : P) :
finset.univ.affine_combination k b (λ i, b.coord i q) = q :=
begin
have hq : q ∈ affine_span k (range b), { rw b.tot, exact affine_subspace.mem_top k V q, },
obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq,
congr,
ext i,
exact b.coord_apply_combination_of_mem (finset.mem_univ i) hw,
end
/-- A variant of `affine_basis.affine_combination_coord_eq_self` for the special case when the
affine space is a module so we can talk about linear combinations. -/
@[simp] lemma linear_combination_coord_eq_self [fintype ι] (b : affine_basis ι k V) (v : V) :
∑ i, b.coord i v • b i = v :=
begin
have hb := b.affine_combination_coord_eq_self v,
rwa finset.univ.affine_combination_eq_linear_combination _ _ (b.sum_coord_apply_eq_one v) at hb,
end
lemma ext_elem [finite ι] {q₁ q₂ : P} (h : ∀ i, b.coord i q₁ = b.coord i q₂) : q₁ = q₂ :=
begin
casesI nonempty_fintype ι,
rw [← b.affine_combination_coord_eq_self q₁, ← b.affine_combination_coord_eq_self q₂],
simp only [h],
end
@[simp] lemma coe_coord_of_subsingleton_eq_one [subsingleton ι] (i : ι) :
(b.coord i : P → k) = 1 :=
begin
ext q,
have hp : (range b).subsingleton,
{ rw ← image_univ,
apply subsingleton.image,
apply subsingleton_of_subsingleton, },
haveI := affine_subspace.subsingleton_of_subsingleton_span_eq_top hp b.tot,
let s : finset ι := {i},
have hi : i ∈ s, { simp, },
have hw : s.sum (function.const ι (1 : k)) = 1, { simp, },
have hq : q = s.affine_combination k b (function.const ι (1 : k)), { simp, },
rw [pi.one_apply, hq, b.coord_apply_combination_of_mem hi hw],
end
lemma surjective_coord [nontrivial ι] (i : ι) :
function.surjective $ b.coord i :=
begin
classical,
intros x,
obtain ⟨j, hij⟩ := exists_ne i,
let s : finset ι := {i, j},
have hi : i ∈ s, { simp, },
have hj : j ∈ s, { simp, },
let w : ι → k := λ j', if j' = i then x else 1-x,
have hw : s.sum w = 1, { simp [hij, finset.sum_ite, finset.filter_insert, finset.filter_eq'], },
use s.affine_combination k b w,
simp [b.coord_apply_combination_of_mem hi hw],
end
/-- Barycentric coordinates as an affine map. -/
noncomputable def coords : P →ᵃ[k] ι → k :=
{ to_fun := λ q i, b.coord i q,
linear :=
{ to_fun := λ v i, -(b.basis_of i).sum_coords v,
map_add' := λ v w, by { ext i, simp only [linear_map.map_add, pi.add_apply, neg_add], },
map_smul' := λ t v, by { ext i, simpa only [linear_map.map_smul, pi.smul_apply, smul_neg] } },
map_vadd' := λ p v, by
{ ext i,
simp only [linear_eq_sum_coords, linear_map.coe_mk, linear_map.neg_apply, pi.vadd_apply',
affine_map.map_vadd], }, }
@[simp] lemma coords_apply (q : P) (i : ι) :
b.coords q i = b.coord i q :=
rfl
end ring
section division_ring
variables [division_ring k] [module k V]
include V
@[simp] lemma coord_apply_centroid [char_zero k] (b : affine_basis ι k P) {s : finset ι} {i : ι}
(hi : i ∈ s) :
b.coord i (s.centroid k b) = (s.card : k) ⁻¹ :=
by rw [finset.centroid, b.coord_apply_combination_of_mem hi
(s.sum_centroid_weights_eq_one_of_nonempty _ ⟨i, hi⟩), finset.centroid_weights]
lemma exists_affine_subbasis {t : set P} (ht : affine_span k t = ⊤) :
∃ (s ⊆ t) (b : affine_basis ↥s k P), ⇑b = coe :=
begin
obtain ⟨s, hst, h_tot, h_ind⟩ := exists_affine_independent k V t,
refine ⟨s, hst, ⟨coe, h_ind, _⟩, rfl⟩,
rw [subtype.range_coe, h_tot, ht]
end
variables (k V P)
lemma exists_affine_basis : ∃ (s : set P) (b : affine_basis ↥s k P), ⇑b = coe :=
let ⟨s, _, hs⟩ := exists_affine_subbasis (affine_subspace.span_univ k V P) in ⟨s, hs⟩
end division_ring
end affine_basis
|
139850a3321b846435cac7837ada2d2f3b2334e6 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/simp_attr_eqns.lean | 26962658380d732328119d6402dfeb3573d1a94e | [
"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 | 948 | lean | open nat tactic
def g : nat → nat → nat :=
λ x y, x * y
def f : nat → nat
| 0 := 10
| (succ a) := g (f a) 2
lemma ex0 (b a : nat) : b = f a → f (succ (succ a)) = g (g b 2) 2 :=
begin
intro h,
simp [f],
guard_target g (g (f a) 2) 2 = g (g b 2) 2,
subst b
end
attribute [simp] f
lemma ex1 (b a : nat) : b = f a → f (succ a) = g b 2 :=
begin
intro h,
simp,
guard_target g (f a) 2 = g b 2,
subst b
end
lemma ex2 (b a : nat) : b = f a → f (succ (succ a)) = g (g b 2) 2 :=
begin
intro h,
simp,
guard_target g (g (f a) 2) 2 = g (g b 2) 2,
subst b
end
local attribute [-simp] f
lemma ex3 (b a : nat) : b = f a → f (succ a) = g b 2 :=
begin
intro h,
fail_if_success {simp},
subst b,
reflexivity
end
run_cmd mk_simp_attr `mysimp
attribute [mysimp] f
lemma ex4 (b a : nat) : b = f a → f (succ a) = g b 2 :=
begin
intro h,
simp with mysimp,
guard_target g (f a) 2 = g b 2,
subst b
end
|
6d7d4eb689c2d69680608dfc651cbfdd99574d5e | f00cc9c04d77f9621aa57d1406d35c522c3ff82c | /library/init/meta/coinductive_predicates.lean | 43de616af7fc981dc43bbee4be79e61606c13b07 | [
"Apache-2.0"
] | permissive | shonfeder/lean | 444c66a74676d74fb3ef682d88cd0f5c1bf928a5 | 24d5a1592d80cefe86552d96410c51bb07e6d411 | refs/heads/master | 1,619,338,440,905 | 1,512,842,340,000 | 1,512,842,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,190 | 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 (CMU)
-/
prelude
import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute
import init.meta.interactive
namespace name
def last_string : name → string
| anonymous := "[anonymous]"
| (mk_string s _) := s
| (mk_numeral _ n) := last_string n
end name
namespace expr
open expr
meta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=
e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none
meta def local_binder_info : expr → binder_info
| (local_const x n bi t) := bi
| e := binder_info.default
meta def to_implicit_binder : expr → expr
| (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d
| (lam n _ d b) := lam n binder_info.implicit d b
| (pi n _ d b) := pi n binder_info.implicit d b
| e := e
meta def get_app_fn_args_aux : list expr → expr → expr × list expr
| r (app f a) := get_app_fn_args_aux (a::r) f
| r e := (e, r)
meta def get_app_fn_args : expr → expr × list expr :=
get_app_fn_args_aux []
end expr
namespace tactic
open level expr tactic
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
meta def drop_pis : list expr → expr → tactic expr
| (list.cons v vs) (pi n bi d b) := do
t ← infer_type v,
guard (t =ₐ d),
drop_pis vs (b.instantiate_var v)
| [] e := return e
| _ _ := failed
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do
((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ const n $ ls.map param
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr
| [] := empty
| [e] := e
| (e :: es) := op e $ mk_op_lst es
meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true)
meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false)
meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[([h, h'], _)] ← induction e [],
elim_gen_prod n h' (hs ++ [h])
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[([h], _), ([h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
end tactic
section
universe u
@[user_attribute]
meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" }
lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) :
implies (Πa, p a) (Πa, q a) :=
assume h' a, h a (h' a)
lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) :
implies (p → p') (q → q') :=
assume h, h₁ ∘ h ∘ h₂
@[monotonicity]
lemma monotonicity.const (p : Prop) : implies p p := id
@[monotonicity]
lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial
@[monotonicity]
lemma monotonicity.false (p : Prop) : implies false p := false.elim
@[monotonicity]
lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) :
implies (∃a, p a) (∃a, q a) :=
exists_imp_exists h
@[monotonicity]
lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') :
implies (p ∧ q) (p' ∧ q') :=
and.imp hp hq
@[monotonicity]
lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') :
implies (p ∨ q) (p' ∨ q') :=
or.imp hp hq
@[monotonicity]
lemma monotonicity.not {p q : Prop} (h : implies p q) :
implies (¬ q) (¬ p) :=
mt h
end
namespace tactic
open expr tactic
/- TODO: use backchaining -/
private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do
intros,
(do
`(implies %%p %%q) ← target,
(do is_def_eq p q, eapplyc `monotone.const) <|>
(do
(expr.pi pn pbi pd pb) ← whnf p,
(expr.pi qn qbi qd qb) ← whnf q,
sort u ← infer_type pd,
(do is_def_eq pd qd,
let p' := expr.lam pn pbi pd pb,
let q' := expr.lam qn qbi qd qb,
eapply $ (const `monotonicity.pi [u] : expr) pd p' q') <|>
(do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q,
let p' := pb.lower_vars 0 1,
let q' := qb.lower_vars 0 1,
eapply $ (const `monotonicity.imp []: expr) pd p' qd q'))) <|>
first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|>
first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip),
all_goals mono_aux
meta def mono (e : expr) (hs : list expr) : tactic unit := do
t ← target,
t' ← infer_type e,
ns ← attribute.get_instances `monotonicity,
((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs),
exact (p e)
end tactic
/-
The coinductive predicate `pred`:
coinductive {u} pred (A) : a → Prop
| r : ∀A b, pred A p
where
`u` is a list of universe parameters
`A` is a list of global parameters
`pred` is a list predicates to be defined
`a` are the indices for each `pred`
`r` is a list of introduction rules for each `pred`
`b` is a list of parameters for each rule in `r` and `pred`
`p` is are the instances of `a` using `A` and `b`
`pred` is compiled to the following defintions:
inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop
| r : ∀a [f], b[pred/pred'] → pred.functional a [f] p
lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] :
∀p, pred.functional A pred₁ p → pred.functional A pred₂ p
def {u} pred_i (A) (a) : Prop :=
∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a
lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] :
∀a, C_i a → pred_i A a
lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a
lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a
lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a
lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a)
[Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a
lemma {u} pred.r (A) (b) : pred_i A p
-/
namespace tactic
open level expr tactic
namespace add_coinductive_predicate
/- private -/ meta structure coind_rule : Type :=
(orig_nm : name)
(func_nm : name)
(type : expr)
(loc_type : expr)
(args : list expr)
(loc_args : list expr)
(concl : expr)
(insts : list expr)
/- private -/ meta structure coind_pred : Type :=
(u_names : list name)
(params : list expr)
(pd_name : name)
(type : expr)
(intros : list coind_rule)
(locals : list expr)
(f₁ f₂ : expr)
(u_f : level)
namespace coind_pred
meta def u_params (pd : coind_pred) : list level :=
pd.u_names.map param
meta def f₁_l (pd : coind_pred) : expr :=
pd.f₁.app_of_list pd.locals
meta def f₂_l (pd : coind_pred) : expr :=
pd.f₂.app_of_list pd.locals
meta def pred (pd : coind_pred) : expr :=
const pd.pd_name pd.u_params
meta def func (pd : coind_pred) : expr :=
const (pd.pd_name ++ "functional") pd.u_params
meta def func_g (pd : coind_pred) : expr :=
pd.func.app_of_list $ pd.params
meta def pred_g (pd : coind_pred) : expr :=
pd.pred.app_of_list $ pd.params
meta def impl_locals (pd : coind_pred) : list expr :=
pd.locals.map to_implicit_binder
meta def impl_params (pd : coind_pred) : list expr :=
pd.params.map to_implicit_binder
meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr :=
(imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals
meta def corec_functional (pd : coind_pred) : expr :=
const (pd.pd_name ++ "corec_functional") pd.u_params
meta def mono (pd : coind_pred) : expr :=
const (pd.func.const_name ++ "mono") pd.u_params
meta def rec' (pd : coind_pred) : tactic expr :=
do let c := pd.func.const_name ++ "rec",
env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params)
-- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false
meta def construct (pd : coind_pred) : expr :=
const (pd.pd_name ++ "construct") pd.u_params
meta def destruct (pd : coind_pred) : expr :=
const (pd.pd_name ++ "destruct") pd.u_params
meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr :=
add_theorem_by n pd.u_names type tac
end coind_pred
end add_coinductive_predicate
open add_coinductive_predicate
/- compact_relation bs as_ps: Product a relation of the form:
R := λ as, ∃ bs, Λ_i a_i = p_i[bs]
This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and
hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/
private meta def compact_relation :
list expr → list (expr × expr) → list expr × list (expr × expr)
| [] ps := ([], ps)
| (list.cons b bs) ps :=
match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with
| (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps)
| (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in
compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p)))
end
meta def add_coinductive_predicate
(u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do
let params_names := params.map local_pp_name,
let u_params := u_names.map param,
pre_info ← preds.mmap (λ⟨c, is⟩, do
(ls, t) ← mk_local_pis c.local_type,
(is_def_eq t `(Prop) <|>
fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++
"coinductive predicates are supported.")),
let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string,
f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type,
f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type,
return (ls, (f₁, f₂))),
let fs := pre_info.map prod.snd,
let fs₁ := fs.map prod.fst,
let fs₂ := fs.map prod.snd,
pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do
sort u_f ← infer_type f₁ >>= infer_type,
let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params,
intros ← is.mmap (λi, do
(args, t') ← mk_local_pis i.local_type,
(name.mk_string sub p) ← return i.local_uniq_name,
let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩,
e.replace_with (pred_g c) f) e,
let t' := t'.replace_with (pred_g c) f₂,
return { tactic.add_coinductive_predicate.coind_rule .
orig_nm := i.local_uniq_name,
func_nm := (p ++ "functional") ++ sub,
type := i.local_type,
loc_type := t'.pis loc_args,
concl := t',
loc_args := loc_args,
args := args,
insts := t'.get_app_args }),
return { tactic.add_coinductive_predicate.coind_pred .
pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f,
intros := intros, locals := ls, params := params, u_names := u_names }),
/- Introduce all functionals -/
pds.mmap' (λpd:coind_pred, do
let func_f₁ := pd.func_g.app_of_list $ fs₁,
let func_f₂ := pd.func_g.app_of_list $ fs₂,
/- Define functional for `pd` as inductive predicate -/
func_intros ← pd.intros.mmap (λr:coind_rule, do
let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type,
return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)),
add_inductive pd.func.const_name u_names
(params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)),
/- Prove monotonicity rule -/
mono_params ← pds.mmap (λpd, do
h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂,
return [pd.f₁, pd.f₂, h]),
pd.add_theorem (pd.func.const_name ++ "mono")
((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join)
(do
ps ← intro_lst $ params.map expr.local_pp_name,
fs ← pds.mmap (λpd, do
[f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h],
-- the type of h' reduces to h
let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $
(((const `implies [] : expr)
(f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $
(ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv),
return (f₂, h')),
m ← pd.rec',
eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work?
func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do
bs ← intros,
ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all},
params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m),
params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|>
fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))),
pds.mmap' (λpd, do
let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁,
/- define final predicate -/
pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $
mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals],
add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $
pred_body.lambdas $ params ++ pd.locals,
/- prove `corec_functional` rule -/
hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd),
pd.add_theorem (pd.pred.const_name ++ "corec_functional")
((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs)
(do
intro_lst $ params.map local_pp_name,
fs ← intro_lst $ fs₁.map local_pp_name,
hs ← intro_lst $ hs.map local_pp_name,
ls ← intro_lst $ pd.locals.map local_pp_name,
h ← intro `h,
whnf_target,
fs.mmap' existsi,
hs.mmap' (λf, econstructor >> exact f),
exact h)),
let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g,
/- prove `destruct` rules -/
pds.enum.mmap' (λ⟨n, pd⟩, do
let destruct := pd.le pd.pred_g (func_f pd),
pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do
ps ← intro_lst $ params.map local_pp_name,
ls ← intro_lst $ pd.locals.map local_pp_name,
h ← intro `h,
(fs, h) ← elim_gen_prod pds.length h [],
(hs, h) ← elim_gen_prod pds.length h [],
eapply $ pd.mono.app_of_list ps,
pds.mmap' (λpd:coind_pred, focus1 $ do
eapply $ pd.corec_functional,
focus $ hs.map exact),
some h' ← return $ hs.nth n,
eapply h',
exact h)),
/- prove `construct` rules -/
pds.mmap' (λpd,
pd.add_theorem (pd.pred.const_name ++ "construct")
((pd.le (func_f pd) pd.pred_g).pis params) (do
ps ← intro_lst $ params.map local_pp_name,
let func_pred_g := λpd:coind_pred,
pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps),
eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g,
pds.mmap' (λpd:coind_pred, solve1 $ do
eapply $ pd.mono.app_of_list ps,
pds.mmap' (λpd, solve1 $ eapply $ pd.destruct.app_of_list ps)))),
/- prove `cases_on` rules -/
pds.mmap' (λpd, do
let C := pd.f₁.to_implicit_binder,
h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals,
rules ← pd.intros.mmap (λr:coind_rule, do
mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args),
cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on")
((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules)
(do
ps ← intro_lst $ params.map local_pp_name,
C ← intro `C,
ls ← intro_lst $ pd.locals.map local_pp_name,
h ← intro `h,
rules ← intro_lst $ rules.map local_pp_name,
func_rec ← pd.rec',
eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules,
eapply $ pd.destruct,
exact h),
set_basic_attribute `elab_as_eliminator cases_on.const_name),
/- prove `corec_on` rules -/
pds.mmap' (λpd, do
rules ← pds.mmap (λpd, do
intros ← pd.intros.mmap (λr, do
let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts,
eqs ← eqs.mmap (λ⟨l, i⟩, do
sort u ← infer_type l.local_type,
return $ (const `eq [u] : expr) l.local_type i l),
match bs, eqs with
| [], [] := return ((0, 0), mk_true)
| _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type
| _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs)
end),
let shape := intros.map prod.fst,
let intros := intros.map prod.snd,
prod.mk shape <$>
mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string)
(((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)),
let shape := rules.map prod.fst,
let rules := rules.map prod.snd,
h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals,
pd.add_theorem (pd.pred.const_name ++ "corec_on")
((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules)
(do
ps ← intro_lst $ params.map local_pp_name,
fs ← intro_lst $ fs₁.map local_pp_name,
ls ← intro_lst $ pd.locals.map local_pp_name,
h ← intro `h,
rules ← intro_lst $ rules.map local_pp_name,
eapply $ pd.corec_functional.app_of_list $ ps ++ fs,
(pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do
ls ← intro_lst $ pd.locals.map local_pp_name,
h' ← intro `h,
h' ← note `h' none $ hr.app_of_list ls h',
match s.length with
| 0 := induction h' >> skip -- h' : false
| (n+1) := do
hs ← elim_gen_sum n h',
(hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do
(as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [],
if n_eqs > 0 then do
(eqs, eq') ← elim_gen_prod (n_eqs - 1) h [],
(eqs ++ [eq']).mmap' subst
else skip,
eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs),
iterate assumption)
end),
exact h)),
/- prove constructors -/
pds.mmap' (λpd, pd.intros.mmap' (λr,
pd.add_theorem r.orig_nm (r.type.pis params) $ do
ps ← intro_lst $ params.map local_pp_name,
bs ← intros,
eapply $ pd.construct,
exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)),
pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name),
try triv -- we setup a trivial goal for the tactic framework
open lean.parser
open interactive
@[user_command]
meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do
decl ← inductive_decl.parse meta_info,
add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros),
decl.decls.mmap' $ λ d, do {
get_env >>= λ env, set_env $ env.add_namespace d.name,
meta_info.attrs.apply d.name,
d.attrs.apply d.name,
some doc_string ← pure meta_info.doc_string | skip,
add_doc_string d.name doc_string
}
/-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from
the quantifiers in the current goal.
Current version: do not support mutual inductive rules (i.e. only a since C -/
meta def coinduction (rule : expr) : tactic unit := focus1 $
do
ctxts' ← intros,
-- TODO: why do we need to fix the type here?
ctxts ← ctxts'.mmap (λv,
local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v),
mvars ← apply_core rule {approx := ff, new_goals := new_goals.all},
-- analyse relation
g ← list.head <$> get_goals,
(list.cons _ m_is) ← return $ mvars.drop_while (λv, v ≠ g),
tgt ← target,
(is, ty) ← mk_local_pis tgt,
-- construct coinduction predicate
(bs, eqs) ← compact_relation ctxts <$>
((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m)),
solve1 (do
eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars),
rel ← mk_exists_lst bs eqs,
exact (rel.lambdas is)),
-- prove predicate
solve1 (do
target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis
bs.mmap existsi,
iterate econstructor),
-- clean up remaining coinduction steps
all_goals (do
ctxts'.reverse.mmap clear,
target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis
is ← intro_lst $ is.map expr.local_pp_name,
h ← intro1,
(_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [],
(match eqs with
| [] := clear h
| (e::eqs) := do
(hs, h) ← elim_gen_prod eqs.length h [],
(h::(hs.reverse)).mmap' subst
end))
namespace interactive
open interactive interactive.types expr lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def coinduction (corec_name : parse ident)
(revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do
rule ← mk_const corec_name,
locals ← mmap tactic.get_local $ revert.get_or_else [],
revert_lst locals,
tactic.coinduction rule,
skip
end interactive
end tactic
|
7208d97a6f23af361e30adffef446f8d78e06679 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /data/polynomial.lean | e99292495a00f2bc0a3dcab82b7ddc96bef6fb0d | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 41,236 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker
Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring.
-/
import data.finsupp algebra.euclidean_domain
/-- `polynomial α` is the type of univariate polynomials over `α`.
Polynomials should be seen as (semi-)rings with the additional the constructor `X`. `C` is the
embedding from `α`. -/
def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α
open finsupp finset lattice
namespace polynomial
universe u
variables {α : Type u} {a b : α} {m n : ℕ}
variables [decidable_eq α]
section comm_semiring
variables [comm_semiring α] {p q : polynomial α}
instance : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun
instance : has_zero (polynomial α) := finsupp.has_zero
instance : has_one (polynomial α) := finsupp.has_one
instance : has_add (polynomial α) := finsupp.has_add
instance : has_mul (polynomial α) := finsupp.has_mul
instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring
instance : decidable_eq (polynomial α) := finsupp.decidable_eq
local attribute [instance] finsupp.to_comm_semiring
@[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl
/-- `C a` is the constant polynomial `a`. -/
def C (a : α) : polynomial α := single 0 a
/-- `X` is the polynomial variable (aka indeterminant). -/
def X : polynomial α := single 1 1
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : polynomial α) : with_bot ℕ := p.support.sup some
def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) :=
inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf)
/-- `nat_degree p` forces `degree p` to ℕ, by fixing the zero polnomial to the 0 degree. -/
def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0
lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n
| 0 := by simp; refl
| (n+1) :=
calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one]
... = (C a * X^n) * X : by rw [single_eq_C_mul_X]
... = C a * X^(n+1) : by simp [pow_add, mul_assoc]
@[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α)
(h_C : ∀a, M (C a))
(h_add : ∀p q, M p → M q → M (p + q))
(h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) :
M p :=
have ∀{n:ℕ} {a}, M (C a * X^n),
begin
assume n a,
induction n with n ih,
{ simp [h_C] },
{ exact h_monomial _ _ ih }
end,
finsupp.induction p
(suffices M (C 0), by simpa [C],
h_C 0)
(assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X],
h_add _ _ this hp)
@[simp] lemma zero_apply (n : ℕ) : (0 : polynomial α) n = 0 := rfl
@[simp] lemma one_apply_zero (n : ℕ) : (1 : polynomial α) 0 = 1 := rfl
@[simp] lemma add_apply (p q : polynomial α) (n : ℕ) : (p + q) n = p n + q n :=
finsupp.add_apply
lemma C_apply : (C a : ℕ → α) n = ite (0 = n) a 0 := rfl
@[simp] lemma C_apply_zero : (C a : ℕ → α) 0 = a := rfl
@[simp] lemma X_apply_one : (X : polynomial α) 1 = 1 := rfl
@[simp] lemma C_0 : C (0 : α) = 0 := by simp [C]; refl
@[simp] lemma C_1 : C (1 : α) = 1 := rfl
@[simp] lemma C_mul_C : C a * C b = C (a * b) :=
by simp [C, single_mul_single]
@[simp] lemma C_mul_apply (p : polynomial α) : (C a * p) n = a * p n :=
begin
conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, sum_apply] },
rw [mul_def, C, sum_single_index],
{ simp [single_apply, finsupp.mul_sum],
apply sum_congr rfl,
assume i hi, by_cases i = n; simp [h] },
simp
end
@[simp] lemma X_pow_apply (n i : ℕ) : (X ^ n : polynomial α) i = (if n = i then 1 else 0) :=
suffices (single n 1 : polynomial α) i = (if n = i then 1 else 0),
by rw [single_eq_C_mul_X] at this; simpa,
single_apply
section eval
variable {x : α}
/-- `eval x p` is the evaluation of the polynomial `p` at `x` -/
def eval (x : α) (p : polynomial α) : α :=
p.sum (λ e a, a * x ^ e)
@[simp] lemma eval_C : (C a).eval x = a :=
by simp [C, eval, sum_single_index]
@[simp] lemma eval_X : X.eval x = x :=
by simp [X, eval, sum_single_index]
@[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x :=
finsupp.sum_add_index (by simp) (by simp [add_mul])
@[simp] lemma eval_one : (1 : polynomial α).eval x = 1 :=
by rw [← C_1, eval_C]
@[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x :=
begin
dunfold eval,
rw [mul_def, finsupp.sum_mul _ p],
simp [finsupp.mul_sum _ q, sum_sum_index, sum_single_index, add_mul, pow_add],
exact sum_congr rfl (assume i hi, sum_congr rfl $ assume j hj, by ac_refl)
end
/-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/
def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0
instance : decidable (is_root p a) := by unfold is_root; apply_instance
@[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl
lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} :
is_root q a → is_root (p * q) a :=
by simp [is_root.def, eval_mul] {contextual := tt}
lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) :
is_root p a → is_root (p * q) a :=
by simp [is_root.def, eval_mul] {contextual := tt}
end eval
/-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/
def leading_coeff (p : polynomial α) : α := p (nat_degree p)
/-- a polynomial is `monic` if its leading coefficient is 1 -/
def monic (p : polynomial α) := leading_coeff p = (1 : α)
lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl
instance monic.decidable : decidable (monic p) :=
by unfold monic; apply_instance
@[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl
@[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) :=
show sup (ite (a = 0) ∅ {0}) some = 0,
by rw [if_neg ha]; refl
lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) :=
by by_cases h : a = 0; simp [h]; exact le_refl _
lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) :=
by rw [← C_1]; exact degree_C_le
lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h;
exact support_eq_empty.1 (max_eq_none.1 h),
λ h, h.symm ▸ rfl⟩
lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) :=
let ⟨n, hn⟩ :=
classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in
have hn : degree p = some n := not_not.1 hn,
by rw [nat_degree, hn]; refl
lemma nat_degree_eq_of_degree_eq (h : degree p = degree q) : nat_degree p = nat_degree q :=
by unfold nat_degree; rw h
@[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 :=
begin
by_cases ha : a = 0,
{ have : C a = 0, { simp [ha] },
rw [nat_degree, degree_eq_bot.2 this],
refl },
{ rw [nat_degree, degree_C ha], refl }
end
@[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n :=
by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl
lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n :=
if h : a = 0 then by simp [h] else le_of_eq (degree_monomial n h)
lemma le_degree_of_ne_zero (h : p n ≠ 0) : (n : with_bot ℕ) ≤ degree p :=
show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ),
from finset.le_sup ((finsupp.mem_support_iff _ _).2 h)
lemma eq_zero_of_degree_lt (h : degree p < n) : p n = 0 :=
not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h))
lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 :=
mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h)))
lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (p 0) :=
begin
ext n,
cases n,
{ refl },
{ have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)),
rw [C_apply, if_neg (nat.succ_ne_zero _).symm, eq_zero_of_degree_lt this] }
end
lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) :=
calc degree (p + q) = ((p + q).support).sup some : rfl
... ≤ (p.support ∪ q.support).sup some : sup_mono support_add
... = p.support.sup some ⊔ q.support.sup some : sup_union
... = _ : with_bot.sup_eq_max _ _
@[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl
@[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 :=
⟨λ h, by_contradiction $ λ hp, mt (mem_support_iff _ _).1
(not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)),
by simp {contextual := tt}⟩
lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q :=
le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $
begin
have hq0 : q ≠ 0, { rintro rfl, exact not_lt_bot h },
rw degree_eq_nat_degree hq0 at *,
refine le_degree_of_ne_zero _,
rw [add_apply, eq_zero_of_degree_lt h, zero_add],
exact mt leading_coeff_eq_zero.1 hq0
end
lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) :
degree (p + q) = max p.degree q.degree :=
le_antisymm (degree_add_le _ _) $
match lt_trichotomy (degree p) (degree q) with
| or.inl hlt :=
by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _
| or.inr (or.inl heq) :=
have hq : q ≠ 0 := assume hq,
have hp : p = 0, by simpa [hq, degree_eq_bot] using heq,
by simpa [hp, hq] using h,
le_of_not_gt $
assume hlt : max (degree p) (degree q) > degree (p + q),
h $ show leading_coeff p + leading_coeff q = 0,
begin
rw [heq, max_self, degree_eq_nat_degree hq] at hlt,
rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← add_apply],
exact eq_zero_of_degree_lt hlt,
end
| or.inr (or.inr hlt) :=
by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _
end
lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p :=
sup_mono (erase_subset _ _)
lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p :=
lt_of_le_of_ne (degree_erase_le _ _) $
(degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h)
lemma degree_sum_le {β : Type*} [decidable_eq β] (s : finset β) (f : β → polynomial α) :
degree (s.sum f) ≤ s.sup (degree ∘ f) :=
finset.induction_on s (by simp [finsupp.support_zero]) $
assume a s has ih,
calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) :
by rw sum_insert has; exact degree_add_le _ _
... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih
lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q :=
calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (p i * a) * X ^ (i + j)))) :
by simp [single_eq_C_mul_X.symm]; exact degree_sum_le _ _
... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (p i * q j) * X ^ (i + j)))) :
finset.sup_mono_fun (assume i hi, degree_sum_le _ _)
... ≤ degree p + degree q :
begin
refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, _)),
by_cases hpq : p a * q b = 0,
{ simp [hpq] },
{ rw [degree_monomial _ hpq, with_bot.coe_add],
rw mem_support_iff at ha hb,
exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) }
end
lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p)
| 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le
| (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) :
by rw pow_succ; exact degree_mul_le _ _
... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _)
@[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a :=
begin
by_cases ha : a = 0,
{ simp [ha] },
{ rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X],
exact finsupp.single_eq_same }
end
@[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a :=
suffices leading_coeff (C a * X^0) = a, by simpa,
leading_coeff_monomial a 0
@[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^1) = 1, by simpa,
leading_coeff_monomial 1 1
@[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^0) = 1, by simpa,
leading_coeff_monomial 1 0
@[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _
lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) :
leading_coeff (p + q) = leading_coeff q :=
have hq0 : q ≠ 0 := ne_zero_of_degree_gt h,
have hpq0 : p + q ≠ 0 := ne_zero_of_degree_gt
(show degree p < degree (p + q), by rwa degree_add_eq_of_degree_lt h),
have h : nat_degree (p + q) = nat_degree q := option.some_inj.1 $
show (nat_degree (p + q) : with_bot ℕ) = nat_degree q,
by rw [← degree_eq_nat_degree hq0, ← degree_eq_nat_degree hpq0];
exact degree_add_eq_of_degree_lt h,
begin
unfold leading_coeff,
rw [h, add_apply, eq_zero_of_degree_lt, zero_add],
rwa ← degree_eq_nat_degree hq0
end
lemma leading_coeff_add_of_degree_eq (h : degree p = degree q)
(hlc : leading_coeff p + leading_coeff q ≠ 0) :
leading_coeff (p + q) = leading_coeff p + leading_coeff q :=
if hp0 : p = 0 then by simp [hp0]
else
have hpq0 : p + q ≠ 0 := λ hpq0,
by rw [leading_coeff, leading_coeff, nat_degree, nat_degree, h,
← add_apply, hpq0, zero_apply] at hlc;
exact hlc rfl,
have hpq : nat_degree (p + q) = nat_degree p := option.some_inj.1
$ show (nat_degree (p + q) : with_bot ℕ) = nat_degree p,
by rw [← degree_eq_nat_degree hp0, ← degree_eq_nat_degree hpq0,
degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self],
by rw [leading_coeff, add_apply, hpq, leading_coeff, nat_degree_eq_of_degree_eq h];
refl
@[simp] lemma mul_apply_degree_add_degree (p q : polynomial α) :
(p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q :=
begin
by_cases hpl : leading_coeff p = 0,
{ rw [hpl, zero_mul, leading_coeff_eq_zero.1 hpl, zero_mul, zero_apply] },
by_cases hql : leading_coeff q = 0,
{ rw [hql, mul_zero, leading_coeff_eq_zero.1 hql, mul_zero, zero_apply] },
calc p.sum (λ a b, sum q (λ a₂ b₂, single (a + a₂) (p a * b₂))) (nat_degree p + nat_degree q) =
p.sum (λ a b, sum q (λ a₂ b₂, C (p a * b₂) * X^(a + a₂))) (nat_degree p + nat_degree q) :
begin
apply congr_fun _ _,
congr, ext i a,
congr, ext j b,
apply single_eq_C_mul_X
end
... = sum (finset.singleton (nat_degree p))
(λ a, sum q (λ a₂ b₂, C (p a * b₂) * X^(a + a₂)) (nat_degree p + nat_degree q)) :
begin
rw [sum_apply, finsupp.sum],
refine eq.symm (sum_subset (λ n hn, (mem_support_iff _ _).2
((mem_singleton.1 hn).symm ▸ hpl)) (λ n hnp hn, _)),
rw [← @sum_const_zero _ _ q.support, finsupp.sum_apply, finsupp.sum],
refine finset.sum_congr rfl (λ m hm, _),
have : n + m ≠ nat_degree p + nat_degree q := (ne_of_lt $ add_lt_add_of_lt_of_le
(lt_of_le_of_ne
(le_of_not_gt (λ h,
have degree p < n :=
by rw degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hpl);
exact with_bot.some_lt_some.2 h,
mt (mem_support_iff _ _).1 (not_not.2 (eq_zero_of_degree_lt this)) hnp))
(mt mem_singleton.2 hn))
(le_of_not_gt $ λ h,
have degree q < m :=
by rw degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hql);
exact with_bot.some_lt_some.2 h,
mt eq_zero_of_degree_lt ((mem_support_iff _ _).1 hm) this)),
simp [this]
end
... = (finset.singleton (nat_degree q)).sum
(λ a, (C (p (nat_degree p) * q a) * X^(nat_degree p + a)) (nat_degree p + nat_degree q)) :
begin
rw [sum_singleton, sum_apply, finsupp.sum],
refine eq.symm (sum_subset (λ n hn, (mem_support_iff _ _).2
((mem_singleton.1 hn).symm ▸ hql)) (λ n hnq hn, _)),
have : nat_degree p + n ≠ nat_degree p + nat_degree q :=
mt add_left_cancel (mt mem_singleton.2 hn),
simp [this]
end
... = leading_coeff p * leading_coeff q :
by simp [leading_coeff]
end
lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
degree (p * q) = degree p + degree q :=
have hp : p ≠ 0 := by refine mt _ h; simp {contextual := tt},
have hq : q ≠ 0 := by refine mt _ h; by simp {contextual := tt},
le_antisymm (degree_mul_le _ _)
begin
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq],
refine le_degree_of_ne_zero _,
rwa mul_apply_degree_add_degree
end
lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
nat_degree (p * q) = nat_degree p + nat_degree q :=
have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h),
have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h),
have hpq : p * q ≠ 0 := λ hpq, by rw [← mul_apply_degree_add_degree, hpq, zero_apply] at h;
exact h rfl,
option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q,
by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq])
lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
leading_coeff (p * q) = leading_coeff p * leading_coeff q :=
begin
unfold leading_coeff,
rw [nat_degree_mul_eq' h, mul_apply_degree_add_degree],
refl
end
lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 →
leading_coeff (p ^ n) = leading_coeff p ^ n :=
nat.rec_on n (by simp) $
λ n ih h,
have h₁ : leading_coeff p ^ n ≠ 0 :=
λ h₁, by simpa [h₁, pow_succ] using h,
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← ih h₁] at h,
by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁]
lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 →
degree (p ^ n) = add_monoid.smul n (degree p)
| 0 := λ h, by rw [pow_zero, ← C_1] at *;
rw [degree_C h, add_monoid.zero_smul]
| (n+1) := λ h,
have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁,
by simpa [h₁, pow_succ] using h,
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← leading_coeff_pow' h₁] at h,
by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁]
end comm_semiring
section comm_ring
variables [comm_ring α] {p q : polynomial α}
instance : comm_ring (polynomial α) := finsupp.to_comm_ring
instance : has_scalar α (polynomial α) := finsupp.to_has_scalar
instance : module α (polynomial α) := finsupp.to_module
instance {x : α} : is_ring_hom (eval x) := ⟨λ x y, eval_add, λ x y, eval_mul, eval_C⟩
@[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p :=
by unfold degree; rw support_neg
@[simp] lemma neg_apply (p : polynomial α) (n : ℕ) : (-p) n = -p n := neg_apply
@[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x :=
is_ring_hom.map_neg _
@[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x :=
is_ring_hom.map_sub _
lemma degree_sub_lt (hd : degree p = degree q)
(hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) :
degree (p - q) < degree p :=
have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p :=
finsupp.single_add_erase,
have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q :=
finsupp.single_add_erase,
have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd,
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0),
calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) :
by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]}
... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q))
: degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _
... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩
lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0
| h := begin
rw [h, monic.def, leading_coeff_zero] at hq,
rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp,
exact hp rfl
end
lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) :
degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p :=
have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2,
have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) *
leading_coeff q ≠ 0,
by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one],
if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0
then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2))
else
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq,
have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1
(by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0];
exact h.1),
degree_sub_lt
(by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2,
degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt])
h.2
(by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one])
def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α},
monic q → polynomial α × polynomial α
| p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then
let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in
have wf : _ := div_wf_lemma h hq,
let dm := div_mod_by_monic_aux (p - z * q) hq in
⟨z + dm.1, dm.2⟩
else ⟨0, p⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/
def div_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0
/-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/
def mod_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).2 else p
infixl ` /ₘ ` : 70 := div_by_monic
infixl ` %ₘ ` : 70 := mod_by_monic
lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q)
(hq0 : q ≠ 0), degree (p %ₘ q) < degree q
| p := λ q hq hq0,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq,
have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q :=
degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q)
hq hq0,
begin
unfold mod_by_monic at this ⊢,
unfold div_mod_by_monic_aux,
rw dif_pos hq at this ⊢,
rw if_pos h,
exact this
end
else
or.cases_on (not_and_distrib.1 h) begin
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h],
exact lt_of_not_ge,
end
begin
assume hp,
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, not_not.1 hp],
exact lt_of_le_of_ne bot_le
(ne.symm (mt degree_eq_bot.1 hq0)),
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q),
p %ₘ q = p - q * (p /ₘ q)
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma h hq,
have ih : _ := mod_by_monic_eq_sub_mul_div
(p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq,
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_pos h],
rw [mod_by_monic, dif_pos hq] at ih,
refine ih.trans _,
simp [mul_add, add_mul, mul_comm, hq, h, div_by_monic]
end
else
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h],
simp
end
using_well_founded {dec_tac := tactic.assumption}
lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) :
(∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) :=
by rw [monic.def, leading_coeff_zero] at h;
exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero],
λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩
lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) :
p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq)
@[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 :=
begin
unfold mod_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 :=
begin
unfold div_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
begin
unfold mod_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
begin
unfold div_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq
lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq
lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q :=
⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold mod_by_monic div_mod_by_monic_aux; simp *⟩
lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q :=
⟨λ h, by have := mod_by_monic_add_div p hq;
rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold div_by_monic div_mod_by_monic_aux; simp *⟩
lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) :
degree q + degree (p /ₘ q) = degree p :=
if hq0 : q = 0 then
have ∀ (p : polynomial α), p = 0,
from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _,
by rw [this (p /ₘ q), this p, this q]; refl
else
have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt],
have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero],
have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) :=
calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0
... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe];
exact nat.le_add_right _ _,
calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc)
... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm
... = _ : congr_arg _ (mod_by_monic_add_div _ hq)
lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p :=
if hp0 : p = 0 then by simp [hp0]
else if hq : monic q then
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if h : degree q ≤ degree p
then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))];
exact with_bot.coe_le_coe.2 (nat.le_add_left _ _)
else
by unfold div_by_monic div_mod_by_monic_aux;
simp [dif_pos hq, h]
else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le
lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q)
(hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p :=
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if hpq : degree p < degree q
then begin
rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0],
exact with_bot.bot_lt_some _
end
else begin
rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)],
exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left
(with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q))
end
lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p :=
⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add];
exact dvd_mul_right _ _,
λ h, if hq0 : q = 0 then by rw hq0 at hq;
exact (subsingleton_of_monic_zero hq).1 _ _
else
let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in
by_contradiction (λ hpq0,
have hmod : p %ₘ q = q * (r - p /ₘ q) :=
by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr],
have degree (q * (r - p /ₘ q)) < degree q :=
hmod ▸ degree_mod_by_monic_lt _ hq hq0,
have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 :=
λ h, hpq0 $ leading_coeff_eq_zero.1
(by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]),
have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul],
by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this;
exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩
end comm_ring
section nonzero_comm_ring
variables [nonzero_comm_ring α] {p q : polynomial α}
instance : nonzero_comm_ring (polynomial α) :=
{ zero_ne_one := λ (h : (0 : polynomial α) = 1),
@zero_ne_one α _ $
calc (0 : α) = eval 0 0 : eval_zero.symm
... = eval 0 1 : congr_arg _ h
... = 1 : eval_C,
..polynomial.comm_ring }
@[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) :=
degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm)
@[simp] lemma degree_X : degree (X : polynomial α) = 1 :=
begin
unfold X degree single finsupp.support,
rw if_neg (zero_ne_one).symm,
refl
end
@[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 :=
begin
rw [sub_eq_add_neg, add_comm, ← @degree_X α],
by_cases ha : a = 0,
{ simp [ha] },
exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial)
end
@[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) :=
by simp [monic, zero_ne_one]
lemma ne_zero_of_monic (h : monic p) : p ≠ 0 :=
λ h₁, @not_monic_zero α _ _ (h₁ ▸ h)
lemma monic_X_sub_C (a : α) : monic (X - C a) :=
have degree (-C a) < degree (X : polynomial α) :=
if ha : a = 0 then by simp [ha]; exact dec_trivial else by simp [degree_C ha]; exact dec_trivial,
by unfold monic;
rw [sub_eq_add_neg, add_comm, leading_coeff_add_of_degree_lt this, leading_coeff_X]
lemma root_X_sub_C : is_root (X - C a) b ↔ a = b :=
by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm]
@[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) :=
have h : (p %ₘ (X - C a)).eval a = p.eval a :=
by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul,
eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero],
have degree (p %ₘ (X - C a)) < 1 :=
degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸
ne_zero_of_monic (monic_X_sub_C _)),
have degree (p %ₘ (X - C a)) ≤ 0 :=
begin
cases (degree (p %ₘ (X - C a))),
{ exact bot_le },
{ exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) }
end,
begin
rw [eq_C_of_degree_le_zero this, eval_C] at h,
rw [eq_C_of_degree_le_zero this, h]
end
lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a :=
⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul],
λ h : p.eval a = 0,
by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)};
rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩
end nonzero_comm_ring
section integral_domain
variables [integral_domain α] {p q : polynomial α}
@[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q :=
if hp0 : p = 0 then by simp [hp0]
else if hq0 : q = 0 then by simp [hq0]
else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(mt leading_coeff_eq_zero.1 hq0)
@[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) :
degree (p ^ n) = add_monoid.smul n (degree p) :=
by induction n; simp [*, pow_succ, succ_smul]
@[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) =
leading_coeff p * leading_coeff q :=
begin
by_cases hp : p = 0,
{ simp [hp] },
{ by_cases hq : q = 0,
{ simp [hq] },
{ rw [leading_coeff_mul'],
exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } }
end
@[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) :
leading_coeff (p ^ n) = leading_coeff p ^ n :=
by induction n; simp [*, pow_succ]
instance : integral_domain (polynomial α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b,
rw [leading_coeff_zero, eq_comm] at this,
rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
exact eq_zero_or_eq_zero_of_mul_eq_zero this
end,
..polynomial.nonzero_comm_ring }
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
by rw [is_root, eval_mul] at h;
exact eq_zero_or_eq_zero_of_mul_eq_zero h
lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p :=
lt_of_not_ge $ λ hlt, begin
have := eq_C_of_degree_le_zero hlt,
rw [is_root, this, eval_C] at h,
exact hp (ext (λ n, show p n = 0, from
nat.cases_on n h (λ _, eq_zero_of_degree_lt (lt_of_le_of_lt hlt
(with_bot.coe_lt_coe.2 (nat.succ_pos _)))))),
end
lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) :=
if hp : p = 0 then by simp [hp]
else by rw [degree_mul_eq, degree_eq_nat_degree hp,
degree_eq_nat_degree hq];
exact with_bot.coe_le_coe.2 (nat.le_add_right _ _)
lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0),
∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by have := mul_div_by_monic_eq_iff_is_root.2 hx;
simp * at *,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 :
with_bot.coe_le_coe.2 $ finset.card_insert_le _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add' (le_refl (1 : with_bot ℕ)) htd,
begin
assume y,
rw [mem_insert, htr, eq_comm, ← root_X_sub_C],
conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx},
exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _),
root_or_root_of_root_mul⟩
end⟩
else
⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by clear exists_finset_roots; finish⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a finset containing all the roots of `p` -/
noncomputable def roots (p : polynomial α) : finset α :=
if h : p = 0 then ∅ else classical.some (exists_finset_roots h)
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_finset_roots hp0)).1
end
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _
end integral_domain
section field
variables [field α] {p q : polynomial α}
instance : vector_space α (polynomial α) :=
{ ..finsupp.to_module }
lemma monic_mul_leading_coeff_inv (h : p ≠ 0) :
monic (p * C (leading_coeff p)⁻¹) :=
by rw [monic, leading_coeff_mul, leading_coeff_C,
mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)]
lemma degree_mul_leading_coeff_inv (h : p ≠ 0) :
degree (p * C (leading_coeff p)⁻¹) = degree p :=
have h₁ : (leading_coeff p)⁻¹ ≠ 0 :=
inv_ne_zero (mt leading_coeff_eq_zero.1 h),
by rw [degree_mul_eq, degree_C h₁, add_zero]
def div (p q : polynomial α) :=
C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹))
def mod (p q : polynomial α) :=
p %ₘ (q * C (leading_coeff q)⁻¹)
private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) :
q * div p q + mod p q = p :=
if h : q = 0 then by simp [h, mod_by_monic, div, mod]
else begin
conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)},
rw [div, mod, add_comm, mul_assoc]
end
private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) :
degree (mod p q) < degree q :=
degree_mul_leading_coeff_inv hq ▸
degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq)
(mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C;
exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq))))
instance : has_div (polynomial α) := ⟨div⟩
instance : has_mod (polynomial α) := ⟨mod⟩
lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl
lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl
lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q :=
show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp [monic.def.1 hq]
lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q :=
show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)),
by simp [monic.def.1 hq]
lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) :=
mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _
lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a :=
div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root
instance : euclidean_domain (polynomial α) :=
{ quotient := (/),
remainder := (%),
r := _,
r_well_founded := degree_lt_wf,
quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux,
remainder_lt := λ p q hq, remainder_lt_aux _ hq,
mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) }
lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q :=
⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0,
λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p :=
not_le_of_gt $ by rwa degree_mul_leading_coeff_inv hq0,
begin
rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)],
unfold div_mod_by_monic_aux,
simp [this]
end⟩
lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q :=
⟨λ h, by have := euclidean_domain.div_add_mod p q;
rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this,
λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹),
by rwa degree_mul_leading_coeff_inv hq0,
have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0,
by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩
lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) :
degree q + degree (p / q) = degree p :=
have degree (p % q) < degree (q * (p / q)) :=
calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0
... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)),
by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm,
degree_add_eq_of_degree_lt this, degree_mul_eq]}
end field
end polynomial
|
2bc684511d8de18dcd340d0b1a7136fb5e045159 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/file.lean | c4154c9d8326ad64797ce24969c88df611bb7dce | [
"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 | 90 | lean | def main : IO Unit :=
do contents ← IO.readTextFile "file.lean";
IO.println contents
|
770b0cee5b0101cac35eb34078c6022b1c390607 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/Elab/App.lean | 62510283c00f5eb220664d1ccd999999de3766d4 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 31,625 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.FindMVar
import Lean.Elab.Term
import Lean.Elab.Binders
namespace Lean
namespace Elab
namespace Term
open Meta
/--
Auxiliary inductive datatype for combining unelaborated syntax
and already elaborated expressions. It is used to elaborate applications. -/
inductive Arg
| stx (val : Syntax)
| expr (val : Expr)
instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩
instance Arg.hasToString : HasToString Arg :=
⟨fun arg => match arg with
| Arg.stx val => toString val
| Arg.expr val => toString val⟩
/-- Named arguments created using the notation `(x := val)` -/
structure NamedArg :=
(name : Name) (val : Arg)
instance NamedArg.hasToString : HasToString NamedArg :=
⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩
instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩
/--
Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument
with the same name. -/
def addNamedArg (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do
when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $
throwError ("argument '" ++ toString namedArg.name ++ "' was already set");
pure $ namedArgs.push namedArg
def synthesizeAppInstMVars (instMVars : Array MVarId) : TermElabM Unit :=
instMVars.forM $ fun mvarId =>
unlessM (synthesizeInstMVarCore mvarId) $
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do
argType ← inferType arg;
ensureHasTypeAux expectedType argType arg f
private def elabArg (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr :=
match arg with
| Arg.expr val => ensureArgType f val expectedType
| Arg.stx val => do
val ← elabTerm val expectedType;
ensureArgType f val expectedType
private def mkArrow (d b : Expr) : TermElabM Expr := do
n ← mkFreshAnonymousName;
pure $ Lean.mkForall n BinderInfo.default d b
/-
Relevant definitions:
```
class CoeFun (α : Sort u) (γ : α → outParam (Sort v))
abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a
``` -/
private def tryCoeFun (α : Expr) (a : Expr) : TermElabM Expr := do
v ← mkFreshLevelMVar;
type ← mkArrow α (mkSort v);
γ ← mkFreshExprMVar type;
u ← getLevel α;
let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ];
mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic;
let mvarId := mvar.mvarId!;
synthesized ←
catch (withoutMacroStackAtErr $ synthesizeInstMVarCore mvarId)
(fun ex =>
match ex with
| Exception.error _ msg => throwError $ "function expected" ++ Format.line ++ msg
| _ => throwError "function expected");
if synthesized then
pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar]
else
throwError "function expected"
/-- Auxiliary structure used to elaborate function application arguments. -/
structure ElabAppArgsCtx :=
(ref : Syntax)
(args : Array Arg)
(expectedType? : Option Expr)
(explicit : Bool) -- if true, all arguments are treated as explicit
(argIdx : Nat := 0) -- position of next explicit argument to be processed
(namedArgs : Array NamedArg) -- remaining named arguments to be processed
(instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed
(typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed
(toSetErrorCtx : Array MVarId := #[]) -- metavariables that we need the set the error context using the application being built
(foundExplicit : Bool := false) -- true if an explicit argument has already been processed
/- Auxiliary function for retrieving the resulting type of a function application.
See `propagateExpectedType`. -/
private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr
| i, namedArgs, type@(Expr.forallE n d b c) =>
match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => getForallBody i (namedArgs.eraseIdx idx) b
| none =>
if !c.binderInfo.isExplicit then
getForallBody i namedArgs b
else if i > 0 then
getForallBody (i-1) namedArgs b
else if d.isAutoParam || d.isOptParam then
getForallBody i namedArgs b
else
some type
| i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none
private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool :=
(type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome
private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool :=
(type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone
/-
Auxiliary method for propagating the expected type. We call it as soon as we find the first explict
argument. The goal is to propagate the expected type in applications of functions such as
```lean
HasAdd.add {α : Type u} : α → α → α
List.cons {α : Type u} : α → List α → List α
```
This is particularly useful when there applicable coercions. For example,
assume we have a coercion from `Nat` to `Int`, and we have
`(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function,
the elaborator will fail to elaborate
```
List.cons x []
```
First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`.
Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the
resultant type `List Nat` which is **not** definitionally equal to `List Int`.
We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example).
This method infers that the resultant type is `List ?α` and unifies it with `List Int`.
Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the
term
```
@List.cons Int (coe x) (@List.nil Int)
```
is produced.
The method will do nothing if
1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`)
2- The resultant type does not contain any type metavariable.
3- The resultant type contains a nontype metavariable.
We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in
the Hindley&Milner fragment.
For example, consider the following definitions
```
def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m)
```
Now, consider
```
def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 :=
foo x1 x2 = foo y1 y2
```
When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`.
If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`,
by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since
`bv 64` is **not** definitionally equal to `bv 32`.
-/
private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit :=
withRef ctx.ref $
unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do
match ctx.expectedType? with
| none => pure ()
| some expectedType =>
let numRemainingArgs := ctx.args.size - ctx.argIdx;
match getForallBody numRemainingArgs ctx.namedArgs eType with
| none => pure ()
| some eTypeBody =>
unless eTypeBody.hasLooseBVars $
when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do
_ ← isDefEq expectedType eTypeBody;
pure ()
private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool :=
if h : ctx.argIdx < ctx.args.size then
match ctx.args.get ⟨ctx.argIdx, h⟩ with
| Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true
| _ => false
else
false
/- Elaborate function application arguments. -/
private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr
| ctx, e, eType => withRef ctx.ref do
let finalize : Unit → TermElabM Expr := fun _ => do {
-- all user explicit arguments have been consumed
trace `Elab.app.finalize $ fun _ => e;
match ctx.expectedType? with
| none => pure ()
| some expectedType => do {
-- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it.
_ ← isDefEq expectedType eType;
pure ()
};
synthesizeAppInstMVars ctx.instMVars;
ctx.toSetErrorCtx.forM fun mvarId => registerMVarErrorContext mvarId ctx.ref e;
pure e
};
eType ← whnfForall eType;
match eType with
| Expr.forallE n d b c =>
match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => do
let arg := ctx.namedArgs.get! idx;
let namedArgs := ctx.namedArgs.eraseIdx idx;
argElab ← elabArg e arg.val d;
propagateExpectedType ctx eType;
elabAppArgsAux { ctx with foundExplicit := true, namedArgs := namedArgs } (mkApp e argElab) (b.instantiate1 argElab)
| none =>
let processExplictArg : Unit → TermElabM Expr := fun _ => do {
propagateExpectedType ctx eType;
let ctx := { ctx with foundExplicit := true };
if h : ctx.argIdx < ctx.args.size then do
argElab ← elabArg e (ctx.args.get ⟨ctx.argIdx, h⟩) d;
elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1 } (mkApp e argElab) (b.instantiate1 argElab)
else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with
| false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal)
| false, _, some (Expr.const tacticDecl _ _) => do
env ← getEnv;
match evalSyntaxConstant env tacticDecl with
| Except.error err => throwError err
| Except.ok tacticSyntax => do
tacticBlock ← `(by { $(tacticSyntax.getArgs)* });
-- tacticBlock does not have any position information.
-- So, we use ctx.ref
let tacticBlock := tacticBlock.copyInfo ctx.ref;
let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type`
argElab ← elabArg e (Arg.stx tacticBlock) d;
elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab)
| false, _, some _ =>
throwError "invalid autoParam, argument must be a constant"
| _, _, _ =>
if ctx.namedArgs.isEmpty then
finalize ()
else
throwError ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name))
};
match c.binderInfo with
| BinderInfo.implicit =>
if ctx.explicit then
processExplictArg ()
else do
a ← mkFreshExprMVar d;
typeMVars ← condM (isTypeFormer a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars);
elabAppArgsAux { ctx with typeMVars := typeMVars, toSetErrorCtx := ctx.toSetErrorCtx.push a.mvarId! } (mkApp e a) (b.instantiate1 a)
| BinderInfo.instImplicit =>
if ctx.explicit && nextArgIsHole ctx then do
/- Recall that if '@' has been used, and the argument is '_', then we still use
type class resolution -/
a ← mkFreshExprMVar d MetavarKind.synthetic;
elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a)
else if ctx.explicit then
processExplictArg ()
else do
a ← mkFreshExprMVar d MetavarKind.synthetic;
elabAppArgsAux { ctx with instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a)
| _ =>
processExplictArg ()
| _ =>
if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then
finalize ()
else do
e ← tryCoeFun eType e;
eType ← inferType e;
elabAppArgsAux ctx e eType
private def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do
fType ← inferType f;
fType ← instantiateMVars fType;
trace `Elab.app.args $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType;
unless (namedArgs.isEmpty && args.isEmpty) $
tryPostponeIfMVar fType;
ref ← getRef;
elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType
/-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/
inductive LValResolution
| projFn (baseStructName : Name) (structName : Name) (fieldName : Name)
| projIdx (structName : Name) (idx : Nat)
| const (baseStructName : Name) (structName : Name) (constName : Name)
| localRec (baseName : Name) (fullName : Name) (fvar : Expr)
| getOp (fullName : Name) (idx : Syntax)
private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α :=
throwError $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType
/-- `findMethod? env S fName`.
1- If `env` contains `S ++ fName`, return `(S, S++fName)`
2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o
3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/
private partial def findMethod? (env : Environment) : Name → Name → Option (Name × Name)
| structName, fieldName =>
let fullName := structName ++ fieldName;
match env.find? fullName with
| some _ => some (structName, fullName)
| none =>
let fullNamePrv := mkPrivateName env fullName;
match env.find? fullNamePrv with
| some _ => some (structName, fullNamePrv)
| none =>
if isStructureLike env structName then
(getParentStructures env structName).findSome? fun parentStructName => findMethod? parentStructName fieldName
else
none
private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution :=
match eType.getAppFn, lval with
| Expr.const structName _ _, LVal.fieldIdx idx => do
when (idx == 0) $
throwError "invalid projection, index must be greater than 0";
env ← getEnv;
unless (isStructureLike env structName) $
throwLValError e eType "invalid projection, structure expected";
let fieldNames := getStructureFields env structName;
if h : idx - 1 < fieldNames.size then
if isStructure env structName then
pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩)
else
/- `structName` was declared using `inductive` command.
So, we don't projection functions for it. Thus, we use `Expr.proj` -/
pure $ LValResolution.projIdx structName (idx - 1)
else
throwLValError e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)")
| Expr.const structName _ _, LVal.fieldName fieldName => do
env ← getEnv;
let searchEnv : Unit → TermElabM LValResolution := fun _ => do {
match findMethod? env structName fieldName with
| some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName
| none => throwLValError e eType $
"invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ (structName ++ fieldName) ++ "'"
};
-- search local context first, then environment
let searchCtx : Unit → TermElabM LValResolution := fun _ => do {
let fullName := structName ++ fieldName;
currNamespace ← getCurrNamespace;
let localName := fullName.replacePrefix currNamespace Name.anonymous;
lctx ← getLCtx;
match lctx.findFromUserName? localName with
| some localDecl =>
if localDecl.binderInfo == BinderInfo.auxDecl then
/- LVal notation is being used to make a "local" recursive call. -/
pure $ LValResolution.localRec structName fullName localDecl.toExpr
else
searchEnv ()
| none => searchEnv ()
};
if isStructure env structName then
match findField? env structName fieldName with
| some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName
| none => searchCtx ()
else
searchCtx ()
| Expr.const structName _ _, LVal.getOp idx => do
env ← getEnv;
let fullName := mkNameStr structName "getOp";
match env.find? fullName with
| some _ => pure $ LValResolution.getOp fullName idx
| none => throwLValError e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'"
| _, LVal.getOp idx =>
throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant"
| _, _ =>
throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant"
private partial def resolveLValLoop (e : Expr) (lval : LVal) : Expr → Array Exception → TermElabM LValResolution
| eType, previousExceptions => do
eType ← whnfCore eType;
tryPostponeIfMVar eType;
catch
(resolveLValAux e eType lval)
(fun ex =>
match ex with
| Exception.error _ _ => do
eType? ← unfoldDefinition? eType;
match eType? with
| some eType => resolveLValLoop eType (previousExceptions.push ex)
| none => do
previousExceptions.forM $ fun ex => logException ex;
throw ex
| Exception.internal _ => throw ex)
private def resolveLVal (e : Expr) (lval : LVal) : TermElabM LValResolution := do
eType ← inferType e;
resolveLValLoop e lval eType #[]
private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do
env ← getEnv;
match getPathToBaseStructure? env baseStructName structName with
| none => throwError "failed to access field in parent structure"
| some path =>
path.foldlM
(fun e projFunName => do
projFn ← mkConst projFunName;
elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] #[] none false)
e
/- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter
which takes an element of type `(C ...)` where `C` is `baseName`.
`fullName` is the name of the resolved "field" access function. It is used for reporting errors -/
private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg)
| i, namedArgs, Expr.forallE n d b c =>
if !c.binderInfo.isExplicit then
addLValArg i namedArgs b
else
/- If there is named argument with name `n`, then we should skip. -/
match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => do
let namedArgs := namedArgs.eraseIdx idx;
addLValArg i namedArgs b
| none => do
if d.consumeMData.isAppOf baseName then
pure $ args.insertAt i (Arg.expr e)
else if i < args.size then
addLValArg (i+1) namedArgs b
else
throwError $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'"
| _, _, fType =>
throwError $
"invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)"
private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool)
: Expr → List LVal → TermElabM Expr
| f, [] => elabAppArgs f namedArgs args expectedType? explicit
| f, lval::lvals => do
lvalRes ← resolveLVal f lval;
match lvalRes with
| LValResolution.projIdx structName idx =>
let f := mkProj structName idx f;
elabAppLValsAux f lvals
| LValResolution.projFn baseStructName structName fieldName => do
f ← mkBaseProjections baseStructName structName f;
projFn ← mkConst (baseStructName ++ fieldName);
if lvals.isEmpty then do
namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f };
elabAppArgs projFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] none false;
elabAppLValsAux f lvals
| LValResolution.const baseStructName structName constName => do
f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f;
projFn ← mkConst constName;
if lvals.isEmpty then do
projFnType ← inferType projFn;
args ← addLValArg baseStructName constName f args 0 namedArgs projFnType;
elabAppArgs projFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs projFn #[] #[Arg.expr f] none false;
elabAppLValsAux f lvals
| LValResolution.localRec baseName fullName fvar =>
if lvals.isEmpty then do
fvarType ← inferType fvar;
args ← addLValArg baseName fullName f args 0 namedArgs fvarType;
elabAppArgs fvar namedArgs args expectedType? explicit
else do
f ← elabAppArgs fvar #[] #[Arg.expr f] none false;
elabAppLValsAux f lvals
| LValResolution.getOp fullName idx => do
getOpFn ← mkConst fullName;
if lvals.isEmpty then do
namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f };
namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx };
elabAppArgs getOpFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false;
elabAppLValsAux f lvals
private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do
when (!lvals.isEmpty && explicit) $ throwError "invalid use of field notation with `@` modifier";
elabAppLValsAux namedArgs args expectedType? explicit f lvals
def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do
lvls.foldrM
(fun stx lvls => do
lvl ← elabLevel stx;
pure (lvl::lvls))
[]
/-
Interaction between `errToSorry` and `observing`.
- The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true).
- When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator.
The `observing x` executes `x` and returns a `TermElabResult`.
`observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't
if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution
because it would not be clear to decide what the "main" error message for the alternative is. When the result contains
a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many
error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`.
Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols.
Important: we rely on the property that after `errToSorry` is set to
false, no elaboration function executed by `x` will reset it to
`true`.
-/
private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal)
(namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult)
: TermElabM (Array TermElabResult) :=
match fIdent with
| Syntax.ident _ _ n preresolved => do
funLVals ← withRef fIdent $ resolveName n preresolved fExplicitUnivs;
-- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`.
adaptReader (fun (ctx : Context) => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) $
funLVals.foldlM
(fun acc ⟨f, fields⟩ => do
let lvals' := fields.map LVal.fieldName;
s ← observing $ elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit;
pure $ acc.push s)
acc
| _ => throwUnsupportedSyntax
private partial def elabAppFn : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult)
| f, lvals, namedArgs, args, expectedType?, explicit, acc =>
if f.getKind == choiceKind then
-- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`.
adaptReader (fun (ctx : Context) => { ctx with errToSorry := false }) $
f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc
else match_syntax f with
| `($(e).$idx:fieldIdx) =>
let idx := idx.isFieldIdx?.get!;
elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc
| `($(e).$field:ident) =>
let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n));
elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc
| `($e[$idx]) =>
elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc
| `($id:ident@$t:term) =>
throwError "unexpected occurrence of named pattern"
| `($id:ident) => do
elabAppFnId id [] lvals namedArgs args expectedType? explicit acc
| `($id:ident.{$us*}) => do
us ← elabExplicitUnivs us.getSepElems;
elabAppFnId id us lvals namedArgs args expectedType? explicit acc
| `(@$id:ident) =>
elabAppFn id lvals namedArgs args expectedType? true acc
| `(@$id:ident.{$us*}) =>
elabAppFn (f.getArg 1) lvals namedArgs args expectedType? true acc
| `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@`
| `(_) => throwError "placeholders '_' cannot be used where a function is expected"
| _ => do
s ← observing $ do {
f ← elabTerm f none;
elabAppLVals f lvals namedArgs args expectedType? explicit
};
pure $ acc.push s
private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult :=
candidates.filter $ fun c => match c with
| EStateM.Result.ok _ _ => true
| _ => false
private def toMessageData (ex : Exception) : TermElabM MessageData := do
pos ← getRefPos;
match ex.getRef.getPos with
| none => pure ex.toMessageData
| some exPos =>
if pos == exPos then
pure ex.toMessageData
else do
fileMap ← getFileMap;
let exPosition := fileMap.toPosition exPos;
pure $ toString exPosition.line ++ ":" ++ toString exPosition.column ++ " " ++ ex.toMessageData
private def mergeFailures {α} (failures : Array TermElabResult) : TermElabM α := do
msgs ← failures.mapM $ fun failure =>
match failure with
| EStateM.Result.ok _ _ => unreachable!
| EStateM.Result.error ex _ => toMessageData ex;
throwError ("overloaded, errors " ++ MessageData.ofArray msgs)
private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do
/- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned,
then we should postpone until `?m` is assigned.
Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned,
then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`.
We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/
candidates ← elabAppFn f [] namedArgs args expectedType? false #[];
if candidates.size == 1 then
applyResult $ candidates.get! 0
else
let successes := getSuccess candidates;
if successes.size == 1 then
applyResult $ successes.get! 0
else if successes.size > 1 then do
env ← getEnv;
lctx ← getLCtx;
mctx ← getMCtx;
opts ← getOptions;
let msgs : Array MessageData := successes.map $ fun success => match success with
| EStateM.Result.ok e s => MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } e
| _ => unreachable!;
throwErrorAt f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs)
else
withRef f $ mergeFailures candidates
partial def expandApp (stx : Syntax) (pattern := false) : TermElabM (Syntax × Array NamedArg × Array Arg × Bool) := do
let f := stx.getArg 0;
let args := (stx.getArg 1).getArgs;
let (args, ellipsis) :=
if args.back.isOfKind `Lean.Parser.Term.ellipsis then
(args.pop, true)
else
(args, false);
unless (pattern || !ellipsis) $
throwErrorAt args.back "'..' is only allowed in patterns";
(namedArgs, args) ← args.foldlM
(fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do
let (namedArgs, args) := acc;
if stx.getKind == `Lean.Parser.Term.namedArgument then do
-- tparser! try ("(" >> ident >> " := ") >> termParser >> ")"
let name := (stx.getArg 1).getId.eraseMacroScopes;
let val := stx.getArg 3;
namedArgs ← addNamedArg namedArgs { name := name, val := Arg.stx val };
pure (namedArgs, args)
else if stx.getKind == `Lean.Parser.Term.ellipsis then do
throwErrorAt stx "unexpected '..'"
else
pure (namedArgs, args.push $ Arg.stx stx))
(#[], #[]);
pure (f, namedArgs, args, ellipsis)
@[builtinTermElab app] def elabApp : TermElab :=
fun stx expectedType? => do
(f, namedArgs, args, _) ← expandApp stx;
elabAppAux f namedArgs args expectedType?
def elabAtom : TermElab :=
fun stx expectedType? => elabAppAux stx #[] #[] expectedType?
@[builtinTermElab ident] def elabIdent : TermElab := elabAtom
@[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom
@[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom
@[builtinTermElab explicit] def elabExplicit : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@`
| `(@$id:ident.{$us*}) => elabAtom stx expectedType?
| `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas
| `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas
| _ => throwUnsupportedSyntax
@[builtinTermElab choice] def elabChoice : TermElab := elabAtom
@[builtinTermElab proj] def elabProj : TermElab := elabAtom
@[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom
/- A raw identiier is not a valid term,
but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/
@[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.app;
pure ()
end Term
end Elab
end Lean
|
ad375ba94311d2d6f97d3fb5fb6512bbda225b87 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/algebra/opposites.lean | 1779a8e89fd8531b4cd968ca7a91d2d51daf459c | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 5,758 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Opposites.
-/
import data.opposite
namespace opposite
universes u
variables (α : Type u)
instance [has_add α] : has_add (opposite α) :=
{ add := λ x y, op (unop x + unop y) }
instance [add_semigroup α] : add_semigroup (opposite α) :=
{ add_assoc := λ x y z, unop_inj $ add_assoc (unop x) (unop y) (unop z),
.. opposite.has_add α }
instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) :=
{ add_left_cancel := λ x y z H, unop_inj $ add_left_cancel $ op_inj H,
.. opposite.add_semigroup α }
instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) :=
{ add_right_cancel := λ x y z H, unop_inj $ add_right_cancel $ op_inj H,
.. opposite.add_semigroup α }
instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) :=
{ add_comm := λ x y, unop_inj $ add_comm (unop x) (unop y),
.. opposite.add_semigroup α }
instance [has_zero α] : has_zero (opposite α) :=
{ zero := op 0 }
instance [add_monoid α] : add_monoid (opposite α) :=
{ zero_add := λ x, unop_inj $ zero_add $ unop x,
add_zero := λ x, unop_inj $ add_zero $ unop x,
.. opposite.add_semigroup α, .. opposite.has_zero α }
instance [add_comm_monoid α] : add_comm_monoid (opposite α) :=
{ .. opposite.add_monoid α, .. opposite.add_comm_semigroup α }
instance [has_neg α] : has_neg (opposite α) :=
{ neg := λ x, op $ -(unop x) }
instance [add_group α] : add_group (opposite α) :=
{ add_left_neg := λ x, unop_inj $ add_left_neg $ unop x,
.. opposite.add_monoid α, .. opposite.has_neg α }
instance [add_comm_group α] : add_comm_group (opposite α) :=
{ .. opposite.add_group α, .. opposite.add_comm_monoid α }
instance [has_mul α] : has_mul (opposite α) :=
{ mul := λ x y, op (unop y * unop x) }
instance [semigroup α] : semigroup (opposite α) :=
{ mul_assoc := λ x y z, unop_inj $ eq.symm $ mul_assoc (unop z) (unop y) (unop x),
.. opposite.has_mul α }
instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) :=
{ mul_left_cancel := λ x y z H, unop_inj $ mul_right_cancel $ op_inj H,
.. opposite.semigroup α }
instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) :=
{ mul_right_cancel := λ x y z H, unop_inj $ mul_left_cancel $ op_inj H,
.. opposite.semigroup α }
instance [comm_semigroup α] : comm_semigroup (opposite α) :=
{ mul_comm := λ x y, unop_inj $ mul_comm (unop y) (unop x),
.. opposite.semigroup α }
instance [has_one α] : has_one (opposite α) :=
{ one := op 1 }
instance [monoid α] : monoid (opposite α) :=
{ one_mul := λ x, unop_inj $ mul_one $ unop x,
mul_one := λ x, unop_inj $ one_mul $ unop x,
.. opposite.semigroup α, .. opposite.has_one α }
instance [comm_monoid α] : comm_monoid (opposite α) :=
{ .. opposite.monoid α, .. opposite.comm_semigroup α }
instance [has_inv α] : has_inv (opposite α) :=
{ inv := λ x, op $ (unop x)⁻¹ }
instance [group α] : group (opposite α) :=
{ mul_left_inv := λ x, unop_inj $ mul_inv_self $ unop x,
.. opposite.monoid α, .. opposite.has_inv α }
instance [comm_group α] : comm_group (opposite α) :=
{ .. opposite.group α, .. opposite.comm_monoid α }
instance [distrib α] : distrib (opposite α) :=
{ left_distrib := λ x y z, unop_inj $ add_mul (unop y) (unop z) (unop x),
right_distrib := λ x y z, unop_inj $ mul_add (unop z) (unop x) (unop y),
.. opposite.has_add α, .. opposite.has_mul α }
instance [semiring α] : semiring (opposite α) :=
{ zero_mul := λ x, unop_inj $ mul_zero $ unop x,
mul_zero := λ x, unop_inj $ zero_mul $ unop x,
.. opposite.add_comm_monoid α, .. opposite.monoid α, .. opposite.distrib α }
instance [ring α] : ring (opposite α) :=
{ .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α }
instance [comm_ring α] : comm_ring (opposite α) :=
{ .. opposite.ring α, .. opposite.comm_semigroup α }
instance [zero_ne_one_class α] : zero_ne_one_class (opposite α) :=
{ zero_ne_one := λ h, zero_ne_one $ op_inj h,
.. opposite.has_zero α, .. opposite.has_one α }
instance [integral_domain α] : integral_domain (opposite α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)),
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_inj H)
(λ hy, or.inr $ unop_inj $ hy) (λ hx, or.inl $ unop_inj $ hx),
.. opposite.comm_ring α, .. opposite.zero_ne_one_class α }
instance [field α] : field (opposite α) :=
{ mul_inv_cancel := λ x hx, unop_inj $ inv_mul_cancel $ λ hx', hx $ unop_inj hx',
inv_zero := unop_inj inv_zero,
.. opposite.comm_ring α, .. opposite.zero_ne_one_class α, .. opposite.has_inv α }
@[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl
@[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl
@[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl
@[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl
variable {α}
@[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl
@[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl
@[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl
@[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl
@[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl
@[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl
@[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl
@[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl
end opposite
|
d8cd80252342a56fea6b3c7983cf219cb5e49e58 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/analysis/normed_space/bounded_linear_maps.lean | a69531882b4a3b4310081d7faec9cf411375aed5 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 19,516 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
Continuous linear functions -- functions between normed vector spaces which are bounded and linear.
-/
import algebra.field
import analysis.normed_space.operator_norm analysis.normed_space.multilinear
noncomputable theory
open_locale classical filter
open filter (tendsto)
open metric
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space 𝕜 G]
set_option class.instance_max_depth 70
/-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the
inequality `∥ f x ∥ ≤ M * ∥ x ∥` for some positive constant `M`. -/
structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F)
extends is_linear_map 𝕜 f : Prop :=
(bound : ∃ M, 0 < M ∧ ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥)
lemma is_linear_map.with_bound
{f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) :
is_bounded_linear_map 𝕜 f :=
⟨ hf, classical.by_cases
(assume : M ≤ 0, ⟨1, zero_lt_one, assume x,
le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩)
(assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩
/-- A continuous linear map satisfies `is_bounded_linear_map` -/
lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f :=
{ bound := f.bound,
..f.to_linear_map }
namespace is_bounded_linear_map
/-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/
def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F :=
(is_linear_map.mk' _ h.to_is_linear_map)
/-- Construct a continuous linear map from is_bounded_linear_map -/
def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F :=
{ cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC,
..to_linear_map f hf}
lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) :=
(0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl]
lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) :=
linear_map.id.is_linear.with_bound 1 $ by simp [le_refl]
lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) :=
begin
refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λx, _),
rw one_mul,
exact le_max_left _ _
end
lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) :=
begin
refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λx, _),
rw one_mul,
exact le_max_right _ _
end
variables { f g : E → F }
lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (λ e, c • f e) :=
let ⟨hlf, M, hMp, hM⟩ := hf in
(c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x,
calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x)
... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _)
... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm
lemma neg (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (λ e, -f e) :=
begin
rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp },
exact smul (-1) hf
end
lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) :
is_bounded_linear_map 𝕜 (λ e, f e + g e) :=
let ⟨hlf, Mf, hMfp, hMf⟩ := hf in
let ⟨hlg, Mg, hMgp, hMg⟩ := hg in
(hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x,
calc ∥f x + g x∥ ≤ Mf * ∥x∥ + Mg * ∥x∥ : norm_add_le_of_le (hMf x) (hMg x)
... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul
lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) :
is_bounded_linear_map 𝕜 (λ e, f e - g e) := add hf (neg hg)
lemma comp {g : F → G}
(hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (g ∘ f) :=
(hg.to_continuous_linear_map.comp hf.to_continuous_linear_map).is_bounded_linear_map
lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : f →_{x} (f x) :=
let ⟨hf, M, hMp, hM⟩ := hf in
tendsto_iff_norm_tendsto_zero.2 $
squeeze_zero (assume e, norm_nonneg _)
(assume e,
calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl
... ≤ M * ∥e - x∥ : hM (e - x))
(suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa,
tendsto_const_nhds.mul (lim_norm _))
lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λ _, hf.tendsto _
lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) :
(f →_{0} 0) :=
(hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0
section
open asymptotics filter
theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) :
is_O f (λ x, x) l :=
let ⟨M, hMp, hM⟩ := h.bound in
⟨M, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩
theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g)
{f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l :=
(hg.is_O_id ⊤).comp_tendsto le_top
theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f)
(l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l :=
is_O_comp h l
end
end is_bounded_linear_map
section
set_option class.instance_max_depth 240
variables {ι : Type*} [decidable_eq ι] [fintype ι]
/-- Taking the cartesian product of two continuous linear maps is a bounded linear operation. -/
lemma is_bounded_linear_map_prod_iso :
is_bounded_linear_map 𝕜 (λ(p : (E →L[𝕜] F) × (E →L[𝕜] G)), (p.1.prod p.2 : (E →L[𝕜] (F × G)))) :=
begin
refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ 1 (λp, _),
simp only [norm, one_mul],
refine continuous_linear_map.op_norm_le_bound _ (le_trans (norm_nonneg _) (le_max_left _ _)) (λu, _),
simp only [norm, continuous_linear_map.prod, max_le_iff],
split,
{ calc ∥p.1 u∥ ≤ ∥p.1∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _
... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ :
mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) },
{ calc ∥p.2 u∥ ≤ ∥p.2∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _
... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ :
mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _) }
end
/-- Taking the cartesian product of two continuous multilinear maps is a bounded linear operation. -/
lemma is_bounded_linear_map_prod_multilinear
{E : ι → Type*} [∀i, normed_group (E i)] [∀i, normed_space 𝕜 (E i)] :
is_bounded_linear_map 𝕜
(λ p : (continuous_multilinear_map 𝕜 E F) × (continuous_multilinear_map 𝕜 E G), p.1.prod p.2) :=
{ add := λ p₁ p₂, by { ext1 m, refl },
smul := λ c p, by { ext1 m, refl },
bound := ⟨1, zero_lt_one, λ p, begin
rw one_mul,
apply continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λ m, _),
rw [continuous_multilinear_map.prod_apply, norm_prod_le_iff],
split,
{ exact le_trans (p.1.le_op_norm m)
(mul_le_mul_of_nonneg_right (norm_fst_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) },
{ exact le_trans (p.2.le_op_norm m)
(mul_le_mul_of_nonneg_right (norm_snd_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) },
end⟩ }
/-- Given a fixed continuous linear map `g`, associating to a continuous multilinear map `f` the
continuous multilinear map `f (g m₁, ..., g mₙ)` is a bounded linear operation. -/
lemma is_bounded_linear_map_continuous_multilinear_map_comp_linear (g : G →L[𝕜] E) :
is_bounded_linear_map 𝕜 (λ f : continuous_multilinear_map 𝕜 (λ (i : ι), E) F,
f.comp_continuous_linear_map 𝕜 E g) :=
begin
refine is_linear_map.with_bound ⟨λ f₁ f₂, by { ext m, refl }, λ c f, by { ext m, refl }⟩
(∥g∥ ^ (fintype.card ι)) (λ f, _),
apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _),
{ apply_rules [mul_nonneg', pow_nonneg, norm_nonneg, norm_nonneg] },
calc ∥f (g ∘ m)∥ ≤
∥f∥ * finset.univ.prod (λ (i : ι), ∥g (m i)∥) : f.le_op_norm _
... ≤ ∥f∥ * finset.univ.prod (λ (i : ι), ∥g∥ * ∥m i∥) : begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
exact finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, g.le_op_norm _)
end
... = ∥g∥ ^ fintype.card ι * ∥f∥ * finset.univ.prod (λ (i : ι), ∥m i∥) :
by { simp [finset.prod_mul_distrib, finset.card_univ], ring }
end
end
section bilinear_map
variable (𝕜)
/-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and
continuous. -/
structure is_bounded_bilinear_map (f : E × F → G) : Prop :=
(add_left : ∀(x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y))
(smul_left : ∀(c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x,y))
(add_right : ∀(x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂))
(smul_right : ∀(c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y))
(bound : ∃C>0, ∀(x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥)
variable {𝕜}
variable {f : E × F → G}
protected lemma is_bounded_bilinear_map.is_O (h : is_bounded_bilinear_map 𝕜 f) :
asymptotics.is_O f (λ p : E × F, ∥p.1∥ * ∥p.2∥) ⊤ :=
let ⟨C, Cpos, hC⟩ := h.bound in
⟨C, filter.eventually_of_forall ⊤ $ λ ⟨x, y⟩, by simpa [mul_assoc] using hC x y⟩
lemma is_bounded_bilinear_map.is_O_comp {α : Type*} (H : is_bounded_bilinear_map 𝕜 f)
{g : α → E} {h : α → F} {l : filter α} :
asymptotics.is_O (λ x, f (g x, h x)) (λ x, ∥g x∥ * ∥h x∥) l :=
H.is_O.comp_tendsto le_top
protected lemma is_bounded_bilinear_map.is_O' (h : is_bounded_bilinear_map 𝕜 f) :
asymptotics.is_O f (λ p : E × F, ∥p∥ * ∥p∥) ⊤ :=
h.is_O.trans (asymptotics.is_O_fst_prod'.norm_norm.mul asymptotics.is_O_snd_prod'.norm_norm)
lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} :
f (x - y, z) = f (x, z) - f(y, z) :=
calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp [sub_eq_add_neg]
... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left]
... = f (x, z) - f (y, z) : by simp [sub_eq_add_neg]
lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} :
f (x, y - z) = f (x, y) - f (x, z) :=
calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp [sub_eq_add_neg]
... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right]
... = f (x, y) - f (x, z) : by simp [sub_eq_add_neg]
lemma is_bounded_bilinear_map.is_bounded_linear_map_left (h : is_bounded_bilinear_map 𝕜 f) (y : F) :
is_bounded_linear_map 𝕜 (λ x, f (x, y)) :=
{ add := λ x x', h.add_left _ _ _,
smul := λ c x, h.smul_left _ _ _,
bound := begin
rcases h.bound with ⟨C, C_pos, hC⟩,
refine ⟨C * (∥y∥ + 1), mul_pos' C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ x, _⟩,
have : ∥y∥ ≤ ∥y∥ + 1, by simp [zero_le_one],
calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y
... ≤ C * ∥x∥ * (∥y∥ + 1) :
by apply_rules [norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos, mul_nonneg']
... = C * (∥y∥ + 1) * ∥x∥ : by ring
end }
lemma is_bounded_bilinear_map.is_bounded_linear_map_right (h : is_bounded_bilinear_map 𝕜 f) (x : E) :
is_bounded_linear_map 𝕜 (λ y, f (x, y)) :=
{ add := λ y y', h.add_right _ _ _,
smul := λ c y, h.smul_right _ _ _,
bound := begin
rcases h.bound with ⟨C, C_pos, hC⟩,
refine ⟨C * (∥x∥ + 1), mul_pos' C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ y, _⟩,
have : ∥x∥ ≤ ∥x∥ + 1, by simp [zero_le_one],
calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y
... ≤ C * (∥x∥ + 1) * ∥y∥ :
by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, mul_le_mul_of_nonneg_left,
le_of_lt C_pos]
end }
lemma is_bounded_bilinear_map_smul :
is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × E), p.1 • p.2) :=
{ add_left := add_smul,
smul_left := λc x y, by simp [smul_smul],
add_right := smul_add,
smul_right := λc x y, by simp [smul_smul, mul_comm],
bound := ⟨1, zero_lt_one, λx y, by simp [norm_smul]⟩ }
lemma is_bounded_bilinear_map_mul :
is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) :=
is_bounded_bilinear_map_smul
lemma is_bounded_bilinear_map_comp :
is_bounded_bilinear_map 𝕜 (λ(p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) :=
{ add_left := λx₁ x₂ y, begin
ext z,
change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z),
rw y.map_add
end,
smul_left := λc x y, begin
ext z,
change y (c • (x z)) = c • y (x z),
rw continuous_linear_map.map_smul
end,
add_right := λx y₁ y₂, rfl,
smul_right := λc x y, rfl,
bound := ⟨1, zero_lt_one, λx y, calc
∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥
≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _
... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ }
lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : continuous_linear_map 𝕜 F G) :
is_bounded_linear_map 𝕜 (λ(f : E →L[𝕜] F), continuous_linear_map.comp g f) :=
is_bounded_bilinear_map_comp.is_bounded_linear_map_left _
lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : continuous_linear_map 𝕜 E F) :
is_bounded_linear_map 𝕜 (λ(g : F →L[𝕜] G), continuous_linear_map.comp g f) :=
is_bounded_bilinear_map_comp.is_bounded_linear_map_right _
lemma is_bounded_bilinear_map_apply :
is_bounded_bilinear_map 𝕜 (λp : (E →L[𝕜] F) × E, p.1 p.2) :=
{ add_left := by simp,
smul_left := by simp,
add_right := by simp,
smul_right := by simp,
bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ }
/-- The function `continuous_linear_map.smul_right`, associating to a continuous linear map
`f : E → 𝕜` and a scalar `c : F` the tensor product `f ⊗ c` as a continuous linear map from `E` to
`F`, is a bounded bilinear map. -/
lemma is_bounded_bilinear_map_smul_right :
is_bounded_bilinear_map 𝕜
(λp, (continuous_linear_map.smul_right : (E →L[𝕜] 𝕜) → F → (E →L[𝕜] F)) p.1 p.2) :=
{ add_left := λm₁ m₂ f, by { ext z, simp [add_smul] },
smul_left := λc m f, by { ext z, simp [mul_smul] },
add_right := λm f₁ f₂, by { ext z, simp [smul_add] },
smul_right := λc m f, by { ext z, simp [smul_smul, mul_comm] },
bound := ⟨1, zero_lt_one, λm f, by simp⟩ }
/-- The composition of a continuous linear map with a continuous multilinear map is a bounded
bilinear operation. -/
lemma is_bounded_bilinear_map_comp_multilinear {ι : Type*} {E : ι → Type*}
[decidable_eq ι] [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space 𝕜 (E i)] :
is_bounded_bilinear_map 𝕜 (λ p : (F →L[𝕜] G) × (continuous_multilinear_map 𝕜 E F),
p.1.comp_continuous_multilinear_map p.2) :=
{ add_left := λ g₁ g₂ f, by { ext m, refl },
smul_left := λ c g f, by { ext m, refl },
add_right := λ g f₁ f₂, by { ext m, simp },
smul_right := λ c g f, by { ext m, simp },
bound := ⟨1, zero_lt_one, λ g f, begin
apply continuous_multilinear_map.op_norm_le_bound _ _ (λm, _),
{ apply_rules [mul_nonneg, zero_le_one, norm_nonneg, norm_nonneg] },
calc ∥g (f m)∥ ≤ ∥g∥ * ∥f m∥ : g.le_op_norm _
... ≤ ∥g∥ * (∥f∥ * finset.univ.prod (λ (i : ι), ∥m i∥)) :
mul_le_mul_of_nonneg_left (f.le_op_norm _) (norm_nonneg _)
... = 1 * ∥g∥ * ∥f∥ * finset.univ.prod (λ (i : ι), ∥m i∥) : by ring
end⟩ }
/-- Definition of the derivative of a bilinear map `f`, given at a point `p` by
`q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product.
We define this function here a bounded linear map from `E × F` to `G`. The fact that this
is indeed the derivative of `f` is proved in `is_bounded_bilinear_map.has_fderiv_at` in
`fderiv.lean`-/
def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) :
(E × F) →ₗ[𝕜] G :=
{ to_fun := λq, f (p.1, q.2) + f (q.1, p.2),
add := λq₁ q₂, begin
change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) =
f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)),
simp [h.add_left, h.add_right], abel
end,
smul := λc q, begin
change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)),
simp [h.smul_left, h.smul_right, smul_add]
end }
/-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map
from `E × F` to `G`. -/
def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →L[𝕜] G :=
(h.linear_deriv p).mk_continuous_of_exists_bound $ begin
rcases h.bound with ⟨C, Cpos, hC⟩,
refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λq, _⟩,
calc ∥f (p.1, q.2) + f (q.1, p.2)∥
≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _)
... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin
apply add_le_add,
exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)),
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos),
end
... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring
end
@[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) :
h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl
set_option class.instance_max_depth 100
/-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at
`p` is itself a bounded linear map. -/
lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (λp : E × F, h.deriv p) :=
begin
rcases h.bound with ⟨C, Cpos, hC⟩,
refine is_linear_map.with_bound ⟨λp₁ p₂, _, λc p, _⟩ (C + C) (λp, _),
{ ext q,
simp [h.add_left, h.add_right], abel },
{ ext q,
simp [h.smul_left, h.smul_right, smul_add] },
{ refine continuous_linear_map.op_norm_le_bound _
(mul_nonneg (add_nonneg (le_of_lt Cpos) (le_of_lt Cpos)) (norm_nonneg _)) (λq, _),
calc ∥f (p.1, q.2) + f (q.1, p.2)∥
≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _)
... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg,
le_of_lt Cpos, le_refl, le_max_left, le_max_right, mul_nonneg, norm_nonneg, norm_nonneg,
norm_nonneg]
... = (C + C) * ∥p∥ * ∥q∥ : by ring },
end
end bilinear_map
|
5679fb9459b0e30bb585d2e46e23fa924a9b7621 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/elabissues/leaky_tmp_metavars.lean | e9c30be21e98d5345dd81534a068e864007e2b09 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,523 | lean | /-
Here is an artificial example where temporary metavariables created by typeclass resolution
would otherwise leak into nested typeclass resolution unless we catch it.
-/
class Foo (α : Type) : Type := (x : Unit)
class Bar (α : Type) : Type := (x : Unit)
class HasParam (α : Type) [Bar α] : Type := (x : Unit)
instance FooToBar (α : Type) [Foo α] : Bar α := {x:=()}
-- Note: there is an implicit `FooToBar` inside the second argument of the return type.
instance HasParamInst (α : Type) [h : Foo α] : HasParam α := {x:=()}
class Top : Type := (x : Unit)
-- Note: `AllFoo` is a weird, universal instance.
instance AllFoo (α : Type) : Foo α := {x:=()}
/-
When the subgoal `[@HasParam α (@FooToBar α (AllFoo α))]` is triggerred, `α` is not known.
This happens for two reasons:
1. The return type `Top` does not include `α`.
2. The universal `AllFoo α` instance obviates the need to take a building-block class as argument.
Thus we would be tempted to call nested typeclass resolution on `Foo <tmp-mvar>`.
-/
instance Bad (α : Type) [HasParam α] : Top := Top.mk ()
def foo [Top] : Unit := ()
set_option pp.all true
set_option trace.class_instances true
set_option trace.type_context.complete_instance true
#check @foo _
/-
[class_instances] class-instance resolution trace
[class_instances] (0) ?x_0 : Top := @Bad ?x_1 ?x_2
[class_instances] (1) ?x_2 : @HasParam ?x_1 (@FooToBar ?x_1 (AllFoo ?x_1)) := @HasParamInst ?x_3 ?x_4
[type_context.complete_instance] would have synthed: Foo ?x_3
-/
|
48db406eab15ebac2ad0dd2d54f0eacbb84664e8 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/factorization/prime_pow.lean | b315f2b22bedac6839b7fc00db52805d025ea81c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 6,425 | lean | /-
Copyright (c) 2022 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import algebra.is_prime_pow
import data.nat.factorization.basic
/-!
# Prime powers and factorizations
This file deals with factorizations of prime powers.
-/
variables {R : Type*} [comm_monoid_with_zero R] (n p : R) (k : ℕ)
lemma is_prime_pow.min_fac_pow_factorization_eq {n : ℕ} (hn : is_prime_pow n) :
n.min_fac ^ n.factorization n.min_fac = n :=
begin
obtain ⟨p, k, hp, hk, rfl⟩ := hn,
rw ←nat.prime_iff at hp,
rw [hp.pow_min_fac hk.ne', hp.factorization_pow, finsupp.single_eq_same],
end
lemma is_prime_pow_of_min_fac_pow_factorization_eq {n : ℕ}
(h : n.min_fac ^ n.factorization n.min_fac = n) (hn : n ≠ 1) :
is_prime_pow n :=
begin
rcases eq_or_ne n 0 with rfl | hn',
{ simpa using h },
refine ⟨_, _, (nat.min_fac_prime hn).prime, _, h⟩,
rw [pos_iff_ne_zero, ←finsupp.mem_support_iff, nat.factor_iff_mem_factorization,
nat.mem_factors_iff_dvd hn' (nat.min_fac_prime hn)],
apply nat.min_fac_dvd
end
lemma is_prime_pow_iff_min_fac_pow_factorization_eq {n : ℕ} (hn : n ≠ 1) :
is_prime_pow n ↔ n.min_fac ^ n.factorization n.min_fac = n :=
⟨λ h, h.min_fac_pow_factorization_eq, λ h, is_prime_pow_of_min_fac_pow_factorization_eq h hn⟩
lemma is_prime_pow_iff_factorization_eq_single {n : ℕ} :
is_prime_pow n ↔ ∃ p k : ℕ, 0 < k ∧ n.factorization = finsupp.single p k :=
begin
rw is_prime_pow_nat_iff,
refine exists₂_congr (λ p k, _),
split,
{ rintros ⟨hp, hk, hn⟩,
exact ⟨hk, by rw [←hn, nat.prime.factorization_pow hp]⟩ },
{ rintros ⟨hk, hn⟩,
have hn0 : n ≠ 0,
{ rintro rfl,
simpa only [finsupp.single_eq_zero, eq_comm, nat.factorization_zero, hk.ne'] using hn },
rw nat.eq_pow_of_factorization_eq_single hn0 hn,
exact ⟨nat.prime_of_mem_factorization
(by simp [hn, hk.ne'] : p ∈ n.factorization.support), hk, rfl⟩ }
end
lemma is_prime_pow_iff_card_support_factorization_eq_one {n : ℕ} :
is_prime_pow n ↔ n.factorization.support.card = 1 :=
by simp_rw [is_prime_pow_iff_factorization_eq_single, finsupp.card_support_eq_one', exists_prop,
pos_iff_ne_zero]
lemma is_prime_pow.exists_ord_compl_eq_one {n : ℕ} (h : is_prime_pow n) :
∃ p : ℕ, p.prime ∧ ord_compl[p] n = 1 :=
begin
rcases eq_or_ne n 0 with rfl | hn0, { cases not_is_prime_pow_zero h },
rcases is_prime_pow_iff_factorization_eq_single.mp h with ⟨p, k, hk0, h1⟩,
rcases em' p.prime with pp | pp,
{ refine absurd _ hk0.ne', simp [←nat.factorization_eq_zero_of_non_prime n pp, h1] },
refine ⟨p, pp, _⟩,
refine nat.eq_of_factorization_eq (nat.ord_compl_pos p hn0).ne' (by simp) (λ q, _),
rw [nat.factorization_ord_compl n p, h1],
simp,
end
lemma exists_ord_compl_eq_one_iff_is_prime_pow {n : ℕ} (hn : n ≠ 1) :
is_prime_pow n ↔ ∃ p : ℕ, p.prime ∧ ord_compl[p] n = 1 :=
begin
refine ⟨λ h, is_prime_pow.exists_ord_compl_eq_one h, λ h, _⟩,
rcases h with ⟨p, pp, h⟩,
rw is_prime_pow_nat_iff,
rw [←nat.eq_of_dvd_of_div_eq_one (nat.ord_proj_dvd n p) h] at ⊢ hn,
refine ⟨p, n.factorization p, pp, _, by simp⟩,
contrapose! hn,
simp [le_zero_iff.1 hn],
end
/-- An equivalent definition for prime powers: `n` is a prime power iff there is a unique prime
dividing it. -/
lemma is_prime_pow_iff_unique_prime_dvd {n : ℕ} :
is_prime_pow n ↔ ∃! p : ℕ, p.prime ∧ p ∣ n :=
begin
rw is_prime_pow_nat_iff,
split,
{ rintro ⟨p, k, hp, hk, rfl⟩,
refine ⟨p, ⟨hp, dvd_pow_self _ hk.ne'⟩, _⟩,
rintro q ⟨hq, hq'⟩,
exact (nat.prime_dvd_prime_iff_eq hq hp).1 (hq.dvd_of_dvd_pow hq') },
rintro ⟨p, ⟨hp, hn⟩, hq⟩,
rcases eq_or_ne n 0 with rfl | hn₀,
{ cases (hq 2 ⟨nat.prime_two, dvd_zero 2⟩).trans (hq 3 ⟨nat.prime_three, dvd_zero 3⟩).symm },
refine ⟨p, n.factorization p, hp, hp.factorization_pos_of_dvd hn₀ hn, _⟩,
simp only [and_imp] at hq,
apply nat.dvd_antisymm (nat.ord_proj_dvd _ _),
-- We need to show n ∣ p ^ n.factorization p
apply nat.dvd_of_factors_subperm hn₀,
rw [hp.factors_pow, list.subperm_ext_iff],
intros q hq',
rw nat.mem_factors hn₀ at hq',
cases hq _ hq'.1 hq'.2,
simp,
end
lemma is_prime_pow_pow_iff {n k : ℕ} (hk : k ≠ 0) :
is_prime_pow (n ^ k) ↔ is_prime_pow n :=
begin
simp only [is_prime_pow_iff_unique_prime_dvd],
apply exists_unique_congr,
simp only [and.congr_right_iff],
intros p hp,
exact ⟨hp.dvd_of_dvd_pow, λ t, t.trans (dvd_pow_self _ hk)⟩,
end
lemma nat.coprime.is_prime_pow_dvd_mul {n a b : ℕ} (hab : nat.coprime a b) (hn : is_prime_pow n) :
n ∣ a * b ↔ n ∣ a ∨ n ∣ b :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [nat.coprime_zero_left] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
rcases eq_or_ne b 0 with rfl | hb,
{ simp only [nat.coprime_zero_right] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
refine ⟨_, λ h, or.elim h (λ i, i.trans (dvd_mul_right _ _)) (λ i, i.trans (dvd_mul_left _ _))⟩,
obtain ⟨p, k, hp, hk, rfl⟩ := (is_prime_pow_nat_iff _).1 hn,
simp only [hp.pow_dvd_iff_le_factorization (mul_ne_zero ha hb),
nat.factorization_mul ha hb, hp.pow_dvd_iff_le_factorization ha,
hp.pow_dvd_iff_le_factorization hb, pi.add_apply, finsupp.coe_add],
have : a.factorization p = 0 ∨ b.factorization p = 0,
{ rw [←finsupp.not_mem_support_iff, ←finsupp.not_mem_support_iff, ←not_and_distrib,
←finset.mem_inter],
exact λ t, (nat.factorization_disjoint_of_coprime hab).le_bot t },
cases this;
simp [this, imp_or_distrib],
end
lemma nat.mul_divisors_filter_prime_pow {a b : ℕ} (hab : a.coprime b) :
(a * b).divisors.filter is_prime_pow = (a.divisors ∪ b.divisors).filter is_prime_pow :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [nat.coprime_zero_left] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
rcases eq_or_ne b 0 with rfl | hb,
{ simp only [nat.coprime_zero_right] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
ext n,
simp only [ha, hb, finset.mem_union, finset.mem_filter, nat.mul_eq_zero, and_true, ne.def,
and.congr_left_iff, not_false_iff, nat.mem_divisors, or_self],
apply hab.is_prime_pow_dvd_mul,
end
|
1566049a47a9b6faddb7cdcafa904b50e90243c9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/convex/caratheodory_auto.lean | a9185d01db23d8f7572ded5ceed0a6f077d3d08c | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,643 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.convex.basic
import Mathlib.linear_algebra.finite_dimensional
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Carathéodory's convexity theorem
This file is devoted to proving Carathéodory's convexity theorem:
The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`.
## Main results:
* `convex_hull_eq_union`: Carathéodory's convexity theorem
## Implementation details
This theorem was formalized as part of the Sphere Eversion project.
## Tags
convex hull, caratheodory
-/
namespace caratheodory
/--
If `x` is in the convex hull of some finset `t` with strictly more than `findim + 1` elements,
then it is in the union of the convex hulls of the finsets `t.erase y` for `y ∈ t`.
-/
theorem mem_convex_hull_erase {E : Type u} [add_comm_group E] [vector_space ℝ E]
[finite_dimensional ℝ E] [DecidableEq E] {t : finset E}
(h : finite_dimensional.findim ℝ E + 1 < finset.card t) {x : E} (m : x ∈ convex_hull ↑t) :
∃ (y : ↥↑t), x ∈ convex_hull ↑(finset.erase t ↑y) :=
sorry
/--
The convex hull of a finset `t` with `findim ℝ E + 1 < t.card` is equal to
the union of the convex hulls of the finsets `t.erase x` for `x ∈ t`.
-/
theorem step {E : Type u} [add_comm_group E] [vector_space ℝ E] [finite_dimensional ℝ E]
[DecidableEq E] (t : finset E) (h : finite_dimensional.findim ℝ E + 1 < finset.card t) :
convex_hull ↑t = set.Union fun (x : ↥↑t) => convex_hull ↑(finset.erase t ↑x) :=
sorry
/--
The convex hull of a finset `t` with `findim ℝ E + 1 < t.card` is contained in
the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ findim ℝ E + 1`.
-/
theorem shrink' {E : Type u} [add_comm_group E] [vector_space ℝ E] [finite_dimensional ℝ E]
(t : finset E) (k : ℕ) (h : finset.card t = finite_dimensional.findim ℝ E + 1 + k) :
convex_hull ↑t ⊆
set.Union
fun (t' : finset E) =>
set.Union
fun (w : t' ⊆ t) =>
set.Union
fun (b : finset.card t' ≤ finite_dimensional.findim ℝ E + 1) => convex_hull ↑t' :=
sorry
/--
The convex hull of any finset `t` is contained in
the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ findim ℝ E + 1`.
-/
theorem shrink {E : Type u} [add_comm_group E] [vector_space ℝ E] [finite_dimensional ℝ E]
(t : finset E) :
convex_hull ↑t ⊆
set.Union
fun (t' : finset E) =>
set.Union
fun (w : t' ⊆ t) =>
set.Union
fun (b : finset.card t' ≤ finite_dimensional.findim ℝ E + 1) => convex_hull ↑t' :=
sorry
end caratheodory
/--
One inclusion of Carathéodory's convexity theorem.
The convex hull of a set `s` in ℝᵈ is contained in
the union of the convex hulls of the (d+1)-tuples in `s`.
-/
theorem convex_hull_subset_union {E : Type u} [add_comm_group E] [vector_space ℝ E]
[finite_dimensional ℝ E] (s : set E) :
convex_hull s ⊆
set.Union
fun (t : finset E) =>
set.Union
fun (w : ↑t ⊆ s) =>
set.Union
fun (b : finset.card t ≤ finite_dimensional.findim ℝ E + 1) => convex_hull ↑t :=
sorry
/--
Carathéodory's convexity theorem.
The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`.
-/
theorem convex_hull_eq_union {E : Type u} [add_comm_group E] [vector_space ℝ E]
[finite_dimensional ℝ E] (s : set E) :
convex_hull s =
set.Union
fun (t : finset E) =>
set.Union
fun (w : ↑t ⊆ s) =>
set.Union
fun (b : finset.card t ≤ finite_dimensional.findim ℝ E + 1) => convex_hull ↑t :=
sorry
/--
A more explicit formulation of Carathéodory's convexity theorem,
writing an element of a convex hull as the center of mass
of an explicit `finset` with cardinality at most `dim + 1`.
-/
theorem eq_center_mass_card_le_dim_succ_of_mem_convex_hull {E : Type u} [add_comm_group E]
[vector_space ℝ E] [finite_dimensional ℝ E] {s : set E} {x : E} (h : x ∈ convex_hull s) :
∃ (t : finset E),
∃ (w : ↑t ⊆ s),
∃ (b : finset.card t ≤ finite_dimensional.findim ℝ E + 1),
∃ (f : E → ℝ),
(∀ (y : E), y ∈ t → 0 ≤ f y) ∧ finset.sum t f = 1 ∧ finset.center_mass t f id = x :=
sorry
/--
A variation on Carathéodory's convexity theorem,
writing an element of a convex hull as a center of mass
of an explicit `finset` with cardinality at most `dim + 1`,
where all coefficients in the center of mass formula
are strictly positive.
(This is proved using `eq_center_mass_card_le_dim_succ_of_mem_convex_hull`,
and discarding any elements of the set with coefficient zero.)
-/
theorem eq_pos_center_mass_card_le_dim_succ_of_mem_convex_hull {E : Type u} [add_comm_group E]
[vector_space ℝ E] [finite_dimensional ℝ E] {s : set E} {x : E} (h : x ∈ convex_hull s) :
∃ (t : finset E),
∃ (w : ↑t ⊆ s),
∃ (b : finset.card t ≤ finite_dimensional.findim ℝ E + 1),
∃ (f : E → ℝ),
(∀ (y : E), y ∈ t → 0 < f y) ∧ finset.sum t f = 1 ∧ finset.center_mass t f id = x :=
sorry
end Mathlib |
89e822a33089cacb224a716651f5d60031b2cb0b | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /tests/lean/run/simp_coe.lean | b1f132668032e26a3265b2db704e7d1e7b84e253 | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 367 | lean | example (p : Prop) (h : p) : tt → p :=
begin
simp [true_implies_iff], assumption
end
local attribute [semireducible] coe_sort_bool
example (p : Prop) (h : p) : tt → p :=
begin
fail_if_success {simp},
intro, assumption
end
local attribute [reducible] coe_sort_bool
example (p : Prop) (h : p) : tt → p :=
begin
simp [true_implies_iff], assumption
end
|
878c6fadbcc084c910b66b0dbc14fa22adc63115 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/lean/invalidNamedArgs.lean | 521f985f070abc8de6d2d910abfa433cee667ce6 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 197 | lean | #lang lean4
def ex1 (xs : List Nat) : Nat :=
xs.foldl (b := 0) fun sum x => sum + x
def f (a : Nat) (flag := true) : Nat :=
a + if flag then 1 else 0
def g (a : Nat) : Nat :=
f a (flg := false)
|
7907af26ad8797003e3da5468c68f4e4875d8369 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch3/ex0601.lean | b4043b42a3c8566ec3a703fe9d59b640db57b4a6 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,036 | lean | open classical
variables p q r : Prop
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
iff.intro
(assume h : p ∧ (q ∨ r),
have hp : p, from h.left,
or.elim (h.right)
(assume hq : q,
show (p ∧ q) ∨ (p ∧ r), from or.inl ⟨hp, hq⟩)
(assume hr : r,
show (p ∧ q) ∨ (p ∧ r), from or.inr ⟨hp, hr⟩))
(assume h : (p ∧ q) ∨ (p ∧ r),
or.elim h
(assume hpq : p ∧ q,
have hp : p, from hpq.left,
have hq : q, from hpq.right,
show p ∧ (q ∨ r), from ⟨hp, or.inl hq⟩)
(assume hpr : p ∧ r,
have hp : p, from hpr.left,
have hr : r, from hpr.right,
show p ∧ (q ∨ r), from ⟨hp, or.inr hr⟩))
-- an example that requires classical reasoning
example : ¬(p ∧ ¬q) → (p → q) :=
assume h : ¬(p ∧ ¬q),
assume hp : p,
show q, from
or.elim (em q)
(assume hq : q, hq)
(assume hnq : ¬q, absurd (and.intro hp hnq) h)
|
b02ca12ea3519107e240d241439b74ec2873bb6e | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/analysis/hofer.lean | 260f8e8e786b904f7cece27f220509289e887531 | [
"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 | 4,539 | lean | /-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import analysis.specific_limits
/-!
# Hofer's lemma
This is an elementary lemma about complete metric spaces. It is motivated by an
application to the bubbling-off analysis for holomorphic curves in symplectic topology.
We are *very* far away from having these applications, but the proof here is a nice
example of a proof needing to construct a sequence by induction in the middle of the proof.
## References:
* H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres*
-/
open_locale classical topological_space big_operators
open filter finset
local notation `d` := dist
lemma hofer {X: Type*} [metric_space X] [complete_space X]
(x : X) (ε : ℝ) (ε_pos : 0 < ε)
{ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ y, 0 ≤ ϕ y) :
∃ (ε' > 0) (x' : X), ε' ≤ ε ∧
d x' x ≤ 2*ε ∧
ε * ϕ(x) ≤ ε' * ϕ x' ∧
∀ y, d x' y ≤ ε' → ϕ y ≤ 2*ϕ x' :=
begin
by_contradiction H,
have reformulation : ∀ x' (k : ℕ), ε * ϕ x ≤ ε / 2 ^ k * ϕ x' ↔ 2^k * ϕ x ≤ ϕ x',
{ intros x' k,
rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left ε_pos, mul_comm],
exact pow_pos (by norm_num) k, },
-- Now let's specialize to `ε/2^k`
replace H : ∀ k : ℕ, ∀ x', d x' x ≤ 2 * ε ∧ 2^k * ϕ x ≤ ϕ x' → ∃ y, d x' y ≤ ε/2^k ∧ 2 * ϕ x' < ϕ y,
{ intros k x',
push_neg at H,
simpa [reformulation] using
H (ε/2^k) (by simp [ε_pos, two_pos]) x' (by simp [ε_pos, two_pos, one_le_two]) },
clear reformulation,
haveI : nonempty X := ⟨x⟩,
choose! F hF using H, -- Use the axiom of choice
-- Now define u by induction starting at x, with u_{n+1} = F(n, u_n)
let u : ℕ → X := λ n, nat.rec_on n x F,
-- The properties of F translate to properties of u
have hu :
∀ n,
d (u n) x ≤ 2 * ε ∧ 2^n * ϕ x ≤ ϕ (u n) →
d (u n) (u $ n + 1) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u $ n + 1),
{ intro n,
exact hF n (u n) },
clear hF,
-- Key properties of u, to be proven by induction
have key : ∀ n, d (u n) (u (n + 1)) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u (n + 1)),
{ intro n,
induction n using nat.case_strong_induction_on with n IH,
{ specialize hu 0,
simp [show u 0 = x, from rfl, le_refl] at *,
exact hu (by linarith) },
have A : d (u (n+1)) x ≤ 2 * ε,
{ rw [dist_comm],
let r := range (n+1), -- range (n+1) = {0, ..., n}
calc
d (u 0) (u (n + 1))
≤ ∑ i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1)
... ≤ ∑ i in r, ε/2^i : sum_le_sum (λ i i_in, (IH i $ nat.lt_succ_iff.mp $
finset.mem_range.mp i_in).1)
... = ∑ i in r, (1/2)^i*ε : by { congr' with i, field_simp }
... = (∑ i in r, (1/2)^i)*ε : finset.sum_mul.symm
... ≤ 2*ε : mul_le_mul_of_nonneg_right (sum_geometric_two_le _)
(le_of_lt ε_pos), },
have B : 2^(n+1) * ϕ x ≤ ϕ (u (n + 1)),
{ apply le_of_lt,
exact geom_lt (by norm_num) (λ m hm, (IH _ hm).2), },
exact hu (n+1) ⟨A, B⟩, },
cases forall_and_distrib.mp key with key₁ key₂,
clear hu key,
-- Hence u is Cauchy
have cauchy_u : cauchy_seq u,
{ apply cauchy_seq_of_le_geometric _ ε (by norm_num : 1/(2:ℝ) < 1),
intro n,
convert key₁ n,
simp },
-- So u converges to some y
obtain ⟨y, limy⟩ : ∃ y, tendsto u at_top (𝓝 y),
from complete_space.complete cauchy_u,
-- And ϕ ∘ u goes to +∞
have lim_top : tendsto (ϕ ∘ u) at_top at_top,
{ let v := λ n, (ϕ ∘ u) (n+1),
suffices : tendsto v at_top at_top,
by rwa tendsto_add_at_top_iff_nat at this,
have hv₀ : 0 < v 0,
{ have : 0 ≤ ϕ (u 0) := nonneg x,
calc 0 ≤ 2 * ϕ (u 0) : by linarith
... < ϕ (u (0 + 1)) : key₂ 0 },
apply tendsto_at_top_of_geom_lt hv₀ (by norm_num : (1 : ℝ) < 2),
exact λ n, key₂ (n+1) },
-- But ϕ ∘ u also needs to go to ϕ(y)
have lim : tendsto (ϕ ∘ u) at_top (𝓝 (ϕ y)),
from tendsto.comp cont.continuous_at limy,
-- So we have our contradiction!
exact not_tendsto_at_top_of_tendsto_nhds lim lim_top,
end
|
e676e96544c907b7f4f3b07f2e394eb1a720b259 | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /src/Lean/Meta/Closure.lean | 70a54ebf2d4e4af2738242c66f2f58ab2e29f594 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,446 | 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 Std.ShareCommon
import Lean.MetavarContext
import Lean.Environment
import Lean.Util.FoldConsts
import Lean.Meta.Basic
import Lean.Meta.Check
/-
This module provides functions for "closing" open terms and
creating auxiliary definitions. Here, we say a term is "open" if
it contains free/meta-variables.
The "closure" is performed by lambda abstracting the
free/meta-variables. Recall that in dependent type theory
lambda abstracting a let-variable may produce type incorrect terms.
For example, given the context
```lean
(n : Nat := 20)
(x : Vector α n)
(y : Vector α 20)
```
the term `x = y` is correct. However, its closure using lambda abstractions
is not.
```lean
fun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y
```
A previous version of this module would address this issue by
always use let-expressions to abstract let-vars. In the example above,
it would produce
```lean
let n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y
```
This approach produces correct result, but produces unsatisfactory
results when we want to create auxiliary definitions.
For example, consider the context
```lean
(x : Nat)
(y : Nat := fact x)
```
and the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`.
The previous version of this module would compute the auxiliary definition
```lean
def aux := fun (x : Nat) => let y : Nat := fact x; h (g y)
```
and would return the term `aux x` as a substitute for `h (g y)`.
This is correct, but we will re-evaluate `fact x` whenever we use `aux`.
In this module, we produce
```lean
def aux := fun (y : Nat) => h (g y)
```
Note that in this particular case, it is safe to lambda abstract the let-varible `y`.
This module uses the following approach to decide whether it is safe or not to lambda
abstract a let-variable.
1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking
if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`.
We say a let-variable is zeta expanded when we replace it with its value.
2) We use the `MetaM` type checker `check` to type check the expression we want to close,
and the type of the binders.
3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it.
Remark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the
`let` inside the lambdas. The idea is to make sure the auxiliary definition does not have
an interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in
the type of one of the lambdas, we simply zeta-expand it there.
As a final example consider the context
```lean
(x_1 : Nat)
(x_2 : Nat)
(x_3 : Nat)
(x : Nat := fact (10 + x_1 + x_2 + x_3))
(ty : Type := Nat → Nat)
(f : ty := fun x => x)
(n : Nat := 20)
(z : f 10)
```
and we use this module to compute an auxiliary definition for the term
```lean
(let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10)
```
we obtain
```lean
def aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat :=
let n : Nat := 20;
(let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10)
```
BTW, this module also provides the `zeta : Bool` flag. When set to true, it
expands all let-variables occurring in the target expression.
-/
namespace Lean.Meta
namespace Closure
structure ToProcessElement where
fvarId : FVarId
newFVarId : FVarId
deriving Inhabited
structure Context where
zeta : Bool
structure State where
visitedLevel : LevelMap Level := {}
visitedExpr : ExprStructMap Expr := {}
levelParams : Array Name := #[]
nextLevelIdx : Nat := 1
levelArgs : Array Level := #[]
newLocalDecls : Array LocalDecl := #[]
newLocalDeclsForMVars : Array LocalDecl := #[]
newLetDecls : Array LocalDecl := #[]
nextExprIdx : Nat := 1
exprMVarArgs : Array Expr := #[]
exprFVarArgs : Array Expr := #[]
toProcess : Array ToProcessElement := #[]
abbrev ClosureM := ReaderT Context $ StateRefT State MetaM
@[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do
if !u.hasMVar && !u.hasParam then
pure u
else
let s ← get
match s.visitedLevel.find? u with
| some v => pure v
| none => do
let v ← f u
modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }
pure v
@[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do
if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then
pure e
else
let s ← get
match s.visitedExpr.find? e with
| some r => pure r
| none =>
let r ← f e
modify fun s => { s with visitedExpr := s.visitedExpr.insert e r }
pure r
def mkNewLevelParam (u : Level) : ClosureM Level := do
let s ← get
let p := (`u).appendIndexAfter s.nextLevelIdx
modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u }
pure $ mkLevelParam p
partial def collectLevelAux : Level → ClosureM Level
| u@(Level.succ v _) => return u.updateSucc! (← visitLevel collectLevelAux v)
| u@(Level.max v w _) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)
| u@(Level.imax v w _) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)
| u@(Level.mvar mvarId _) => mkNewLevelParam u
| u@(Level.param _ _) => mkNewLevelParam u
| u@(Level.zero _) => pure u
def collectLevel (u : Level) : ClosureM Level := do
-- u ← instantiateLevelMVars u
visitLevel collectLevelAux u
def preprocess (e : Expr) : ClosureM Expr := do
let e ← instantiateMVars e
let ctx ← read
-- If we are not zeta-expanding let-decls, then we use `check` to find
-- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.
if !ctx.zeta then
check e
pure e
/--
Remark: This method does not guarantee unique user names.
The correctness of the procedure does not rely on unique user names.
Recall that the pretty printer takes care of unintended collisions. -/
def mkNextUserName : ClosureM Name := do
let s ← get
let n := (`_x).appendIndexAfter s.nextExprIdx
modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 }
pure n
def pushToProcess (elem : ToProcessElement) : ClosureM Unit :=
modify fun s => { s with toProcess := s.toProcess.push elem }
partial def collectExprAux (e : Expr) : ClosureM Expr := do
let collect (e : Expr) := visitExpr collectExprAux e
match e with
| Expr.proj _ _ s _ => return e.updateProj! (← collect s)
| Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b)
| Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b)
| Expr.app f a _ => return e.updateApp! (← collect f) (← collect a)
| Expr.mdata _ b _ => return e.updateMData! (← collect b)
| Expr.sort u _ => return e.updateSort! (← collectLevel u)
| Expr.const c us _ => return e.updateConst! (← us.mapM collectLevel)
| Expr.mvar mvarId _ =>
let mvarDecl ← getMVarDecl mvarId
let type ← preprocess mvarDecl.type
let type ← collect type
let newFVarId ← mkFreshFVarId
let userName ← mkNextUserName
modify fun s => { s with
newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ LocalDecl.cdecl arbitrary newFVarId userName type BinderInfo.default,
exprMVarArgs := s.exprMVarArgs.push e
}
return mkFVar newFVarId
| Expr.fvar fvarId _ =>
match (← read).zeta, (← getLocalDecl fvarId).value? with
| true, some value => collect (← preprocess value)
| _, _ =>
let newFVarId ← mkFreshFVarId
pushToProcess ⟨fvarId, newFVarId⟩
return mkFVar newFVarId
| e => pure e
def collectExpr (e : Expr) : ClosureM Expr := do
let e ← preprocess e
visitExpr collectExprAux e
partial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)
: ToProcessElement × Array ToProcessElement :=
if h : i < toProcess.size then
let elem' := toProcess.get ⟨i, h⟩
if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then
pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem'
else
pickNextToProcessAux lctx (i+1) toProcess elem
else
(elem, toProcess)
def pickNextToProcess? : ClosureM (Option ToProcessElement) := do
let lctx ← getLCtx
let s ← get
if s.toProcess.isEmpty then
pure none
else
modifyGet fun s =>
let elem := s.toProcess.back
let toProcess := s.toProcess.pop
let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem
(some elem, { s with toProcess := toProcess })
def pushFVarArg (e : Expr) : ClosureM Unit :=
modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e }
def pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do
let type ← collectExpr type
modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl arbitrary newFVarId userName type bi }
partial def process : ClosureM Unit := do
match (← pickNextToProcess?) with
| none => pure ()
| some ⟨fvarId, newFVarId⟩ =>
let localDecl ← getLocalDecl fvarId
match localDecl with
| LocalDecl.cdecl _ _ userName type bi =>
pushLocalDecl newFVarId userName type bi
pushFVarArg (mkFVar fvarId)
process
| LocalDecl.ldecl _ _ userName type val _ =>
let zetaFVarIds ← getZetaFVarIds
if !zetaFVarIds.contains fvarId then
/- Non-dependent let-decl
Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it
during type checking (see `check` at `collectExpr`).
Our type checker may zeta-expand declarations that are not needed, but this
check is conservative, and seems to work well in practice. -/
pushLocalDecl newFVarId userName type
pushFVarArg (mkFVar fvarId)
process
else
/- Dependent let-decl -/
let type ← collectExpr type
let val ← collectExpr val
modify fun s => { s with newLetDecls := s.newLetDecls.push <| LocalDecl.ldecl arbitrary newFVarId userName type val false }
/- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId
at `newLocalDecls` -/
modify fun s => { s with newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl newFVarId val) }
process
@[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr :=
let xs := decls.map LocalDecl.toExpr
let b := b.abstract xs
decls.size.foldRev (init := b) fun i b =>
let decl := decls[i]
match decl with
| LocalDecl.cdecl _ _ n ty bi =>
let ty := ty.abstractRange i xs
if isLambda then
Lean.mkLambda n bi ty b
else
Lean.mkForall n bi ty b
| LocalDecl.ldecl _ _ n ty val nonDep =>
if b.hasLooseBVar 0 then
let ty := ty.abstractRange i xs
let val := val.abstractRange i xs
mkLet n ty val b nonDep
else
b.lowerLooseBVars 1 1
def mkLambda (decls : Array LocalDecl) (b : Expr) : Expr :=
mkBinding true decls b
def mkForall (decls : Array LocalDecl) (b : Expr) : Expr :=
mkBinding false decls b
structure MkValueTypeClosureResult where
levelParams : Array Name
type : Expr
value : Expr
levelArgs : Array Level
exprArgs : Array Expr
def mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do
resetZetaFVarIds
withTrackingZeta do
let type ← collectExpr type
let value ← collectExpr value
process
pure (type, value)
def mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do
let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {}
let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars
let newLetDecls := s.newLetDecls.reverse
let type := mkForall newLocalDecls (mkForall newLetDecls type)
let value := mkLambda newLocalDecls (mkLambda newLetDecls value)
pure {
type := type,
value := value,
levelParams := s.levelParams,
levelArgs := s.levelArgs,
exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs
}
end Closure
/--
Create an auxiliary definition with the given name, type and value.
The parameters `type` and `value` may contain free and meta variables.
A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is
returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,
and `t_j`s are free and meta variables `type` and `value` depend on. -/
def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do
trace[Meta.debug]! "{name} : {type} := {value}"
let result ← Closure.mkValueTypeClosure type value zeta
let env ← getEnv
let decl := Declaration.defnDecl {
name := name,
levelParams := result.levelParams.toList,
type := result.type,
value := result.value,
hints := ReducibilityHints.regular (getMaxHeight env result.value + 1),
safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe
}
trace[Meta.debug]! "{name} : {result.type} := {result.value}"
addDecl decl
if compile then
compileDecl decl
pure $ mkAppN (mkConst name result.levelArgs.toList) result.exprArgs
/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/
def mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do
let type ← inferType value
let type := type.headBeta
mkAuxDefinition name type value
end Lean.Meta
|
c12000215d1a68ea160ca9f0a358a272392fc393 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/server/init_exit.lean | 1b2e8fa8e5b743d006fef2c04615b38207d0894a | [
"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 | 460 | lean | import Lean.Data.Lsp
open IO Lean Lsp
def main : IO Unit := do
Ipc.runWith (←IO.appPath) #["--server"] do
let hIn ← Ipc.stdin
hIn.write (←FS.readBinFile "init_vscode_1_47_2.log")
hIn.flush
let initResp ← Ipc.readResponseAs 0 InitializeResult
let regWatchReq ← Ipc.readRequestAs "client/registerCapability" Json
Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩
Ipc.shutdown 1
discard Ipc.waitForExit
|
b8f8b425d3d970a417635ef8d3e7cb5081836908 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/filtered.lean | c96e06336fc39d781377e3e826bd03374317ea40 | [
"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 | 27,326 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison
-/
import category_theory.fin_category
import category_theory.limits.cones
import category_theory.adjunction.basic
import category_theory.category.preorder
import order.bounded_order
/-!
# Filtered categories
A category is filtered if every finite diagram admits a cocone.
We give a simple characterisation of this condition as
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
Filtered colimits are often better behaved than arbitrary colimits.
See `category_theory/limits/types` for some details.
Filtered categories are nice because colimits indexed by filtered categories tend to be
easier to describe than general colimits (and more often preserved by functors).
In this file we show that any functor from a finite category to a filtered category admits a cocone:
* `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)`
More generally,
for any finite collection of objects and morphisms between them in a filtered category
(even if not closed under composition) there exists some object `Z` receiving maps from all of them,
so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute.
This formulation is often more useful in practice and is available via `sup_exists`,
which takes a finset of objects, and an indexed family (indexed by source and target)
of finsets of morphisms.
Furthermore, we give special support for two diagram categories: The `bowtie` and the `tulip`.
This is because these shapes show up in the proofs that forgetful functors of algebraic categories
(e.g. `Mon`, `CommRing`, ...) preserve filtered colimits.
All of the above API, except for the `bowtie` and the `tulip`, is also provided for cofiltered
categories.
## See also
In `category_theory.limits.filtered_colimit_commutes_finite_limit` we show that filtered colimits
commute with finite limits.
-/
open function
universes v v₁ u u₁-- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
variables (C : Type u) [category.{v} C]
/--
A category `is_filtered_or_empty` if
1. for every pair of objects there exists another object "to the right", and
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal.
-/
class is_filtered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h)
/--
A category `is_filtered` if
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.)
-/
class is_filtered extends is_filtered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_filtered_or_empty_of_semilattice_sup
(α : Type u) [semilattice_sup α] : is_filtered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_filtered_of_semilattice_sup_nonempty
(α : Type u) [semilattice_sup α] [nonempty α] : is_filtered α := {}
@[priority 100]
instance is_filtered_or_empty_of_directed_le (α : Type u) [preorder α] [is_directed α (≤)] :
is_filtered_or_empty α :=
{ cocone_objs := λ X Y, let ⟨Z, h1, h2⟩ := exists_ge_ge X Y in
⟨Z, hom_of_le h1, hom_of_le h2, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, by simp⟩ }
@[priority 100]
instance is_filtered_of_directed_le_nonempty (α : Type u) [preorder α] [is_directed α (≤)]
[nonempty α] :
is_filtered α := {}
-- Sanity checks
example (α : Type u) [semilattice_sup α] [order_bot α] : is_filtered α := by apply_instance
example (α : Type u) [semilattice_sup α] [order_top α] : is_filtered α := by apply_instance
namespace is_filtered
variables {C} [is_filtered C]
/--
`max j j'` is an arbitrary choice of object to the right of both `j` and `j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def max (j j' : C) : C :=
(is_filtered_or_empty.cocone_objs j j').some
/--
`left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def left_to_max (j j' : C) : j ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some
/--
`right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C :=
(is_filtered_or_empty.cocone_maps f f').some
/--
`coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some
/--
`coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
-/
@[simp, reassoc]
lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a filtered category has an object "to the right".
-/
lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use max X S',
rintros Y mY,
obtain rfl|h := eq_or_ne Y X,
{ exact ⟨left_to_max _ _⟩, },
{ exact ⟨(w' (finset.mem_of_mem_insert_of_ne mY h)).some ≫ right_to_max _ _⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`,
such that the triangles commute: `f ≫ T Y = T X`, for `f : X ⟶ Y` in the `finset`.
-/
lemma sup_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := sup_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩,
intros X' Y' mX' mY' f' mf',
rw [←category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply coeq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' _,
apply finset.mem_of_mem_insert_of_ne mf',
contrapose! h,
obtain ⟨rfl, h⟩ := h,
rw [heq_iff_eq, psigma.mk.inj_iff] at h,
exact ⟨rfl, h.1.symm⟩ }, },
end
/--
An arbitrary choice of object "to the right"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def sup : C :=
(sup_exists O H).some
/--
The morphisms to `sup O H`.
-/
noncomputable
def to_sup {X : C} (m : X ∈ O) :
X ⟶ sup O H :=
(sup_exists O H).some_spec.some m
/--
The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute.
-/
lemma to_sup_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
f ≫ to_sup O H mY = to_sup O H mX :=
(sup_exists O H).some_spec.some_spec mX mY mf
variables {J : Type v} [small_category J] [fin_category J]
/--
If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cocone over `F`.
-/
lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := sup_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.comp_id],
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`.
-/
noncomputable def cocone (F : J ⥤ C) : cocone F :=
(cocone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered.
-/
lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D :=
{ cocone_objs := λ X Y,
⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨_, h.hom_equiv _ _ (coeq_hom _ _),
by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩,
nonempty := is_filtered.nonempty.map R.obj }
/-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/
lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D :=
of_right_adjoint (adjunction.of_right_adjoint R)
/-- Being filtered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_filtered D :=
of_right_adjoint h.symm.to_adjunction
section special_shapes
/--
`max₃ j₁ j₂ j₃` is an arbitrary choice of object to the right of `j₁`, `j₂` and `j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def max₃ (j₁ j₂ j₃ : C) : C := max (max j₁ j₂) j₃
/--
`first_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₁` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def first_to_max₃ (j₁ j₂ j₃ : C) : j₁ ⟶ max₃ j₁ j₂ j₃ :=
left_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃
/--
`second_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₂` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def second_to_max₃ (j₁ j₂ j₃ : C) : j₂ ⟶ max₃ j₁ j₂ j₃ :=
right_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃
/--
`third_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₃` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def third_to_max₃ (j₁ j₂ j₃ : C) : j₃ ⟶ max₃ j₁ j₂ j₃ :=
right_to_max (max j₁ j₂) j₃
/--
`coeq₃ f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of object
which admits a morphism `coeq₃_hom f g h : j₂ ⟶ coeq₃ f g h` such that
`coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃` are satisfied.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : C :=
coeq (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h))
(coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h))
/--
`coeq₃_hom f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of morphism
`j₂ ⟶ coeq₃ f g h` such that `coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃`
are satisfied. Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq₃_hom {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : j₂ ⟶ coeq₃ f g h :=
coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h) ≫
coeq_hom (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h))
(coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h))
lemma coeq₃_condition₁ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
f ≫ coeq₃_hom f g h = g ≫ coeq₃_hom f g h :=
begin
dsimp [coeq₃_hom],
slice_lhs 1 2 { rw coeq_condition f g },
simp only [category.assoc],
end
lemma coeq₃_condition₂ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
g ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h :=
begin
dsimp [coeq₃_hom],
slice_lhs 2 4 { rw [← category.assoc, coeq_condition _ _] },
slice_rhs 2 4 { rw [← category.assoc, coeq_condition _ _] },
slice_lhs 1 3 { rw [← category.assoc, coeq_condition _ _] },
simp only [category.assoc],
end
lemma coeq₃_condition₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
f ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h :=
eq.trans (coeq₃_condition₁ f g h) (coeq₃_condition₂ f g h)
/--
Given a "bowtie" of morphisms
```
j₁ j₂
|\ /|
| \/ |
| /\ |
|/ \∣
vv vv
k₁ k₂
```
in a filtered category, we can construct an object `s` and two morphisms from `k₁` and `k₂` to `s`,
making the resulting squares commute.
-/
lemma bowtie {j₁ j₂ k₁ k₂ : C}
(f₁ : j₁ ⟶ k₁) (g₁ : j₁ ⟶ k₂) (f₂ : j₂ ⟶ k₁) (g₂ : j₂ ⟶ k₂) :
∃ (s : C) (α : k₁ ⟶ s) (β : k₂ ⟶ s), f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = g₂ ≫ β :=
begin
let sa := max k₁ k₂,
let sb := coeq (f₁ ≫ left_to_max _ _) (g₁ ≫ right_to_max _ _),
let sc := coeq (f₂ ≫ left_to_max _ _) (g₂ ≫ right_to_max _ _),
let sd := max sb sc,
let s := coeq ((coeq_hom _ _ : sa ⟶ sb) ≫ left_to_max _ _)
((coeq_hom _ _ : sa ⟶ sc) ≫ right_to_max _ _),
use s,
fsplit,
exact left_to_max k₁ k₂ ≫ coeq_hom _ _ ≫ left_to_max sb sc ≫ coeq_hom _ _,
fsplit,
exact right_to_max k₁ k₂ ≫ coeq_hom _ _ ≫ right_to_max sb sc ≫ coeq_hom _ _,
fsplit,
{ slice_lhs 1 3 { rw [←category.assoc, coeq_condition], },
slice_lhs 3 5 { rw [←category.assoc, coeq_condition], },
simp only [category.assoc], },
{ slice_lhs 3 5 { rw [←category.assoc, coeq_condition], },
slice_lhs 1 3 { rw [←category.assoc, coeq_condition], },
simp only [category.assoc], }
end
/--
Given a "tulip" of morphisms
```
j₁ j₂ j₃
|\ / \ / |
| \ / \ / |
| vv vv |
\ k₁ k₂ /
\ /
\ /
\ /
\ /
v v
l
```
in a filtered category, we can construct an object `s` and three morphisms from `k₁`, `k₂` and `l`
to `s`, making the resulting sqaures commute.
-/
lemma tulip {j₁ j₂ j₃ k₁ k₂ l : C} (f₁ : j₁ ⟶ k₁) (f₂ : j₂ ⟶ k₁) (f₃ : j₂ ⟶ k₂) (f₄ : j₃ ⟶ k₂)
(g₁ : j₁ ⟶ l) (g₂ : j₃ ⟶ l) :
∃ (s : C) (α : k₁ ⟶ s) (β : l ⟶ s) (γ : k₂ ⟶ s),
f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = f₃ ≫ γ ∧ f₄ ≫ γ = g₂ ≫ β :=
begin
let sa := max₃ k₁ l k₂,
let sb := coeq (f₁ ≫ first_to_max₃ k₁ l k₂) (g₁ ≫ second_to_max₃ k₁ l k₂),
let sc := coeq (f₂ ≫ first_to_max₃ k₁ l k₂) (f₃ ≫ third_to_max₃ k₁ l k₂),
let sd := coeq (f₄ ≫ third_to_max₃ k₁ l k₂) (g₂ ≫ second_to_max₃ k₁ l k₂),
let se := max₃ sb sc sd,
let sf := coeq₃ (coeq_hom _ _ ≫ first_to_max₃ sb sc sd)
(coeq_hom _ _ ≫ second_to_max₃ sb sc sd) (coeq_hom _ _ ≫ third_to_max₃ sb sc sd),
use sf,
use first_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ first_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
use second_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ second_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
use third_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ third_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
fsplit,
slice_lhs 1 3 { rw [← category.assoc, coeq_condition] },
slice_lhs 3 6 { rw [← category.assoc, coeq₃_condition₁] },
simp only [category.assoc],
fsplit,
slice_lhs 3 6 { rw [← category.assoc, coeq₃_condition₁] },
slice_lhs 1 3 { rw [← category.assoc, coeq_condition] },
slice_rhs 3 6 { rw [← category.assoc, ← coeq₃_condition₂] },
simp only [category.assoc],
slice_rhs 3 6 { rw [← category.assoc, coeq₃_condition₂] },
slice_rhs 1 3 { rw [← category.assoc, ← coeq_condition] },
simp only [category.assoc],
end
end special_shapes
end is_filtered
/--
A category `is_cofiltered_or_empty` if
1. for every pair of objects there exists another object "to the left", and
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal.
-/
class is_cofiltered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g)
/--
A category `is_cofiltered` if
1. for every pair of objects there exists another object "to the left",
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal, and
3. there exists some object.
See https://stacks.math.columbia.edu/tag/04AZ.
-/
class is_cofiltered extends is_cofiltered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_cofiltered_or_empty_of_semilattice_inf
(α : Type u) [semilattice_inf α] : is_cofiltered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊓ Y, hom_of_le inf_le_left, hom_of_le inf_le_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨X, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_cofiltered_of_semilattice_inf_nonempty
(α : Type u) [semilattice_inf α] [nonempty α] : is_cofiltered α := {}
@[priority 100]
instance is_cofiltered_or_empty_of_directed_ge (α : Type u) [preorder α]
[is_directed α (swap (≤))] :
is_cofiltered_or_empty α :=
{ cocone_objs := λ X Y, let ⟨Z, hX, hY⟩ := exists_le_le X Y in
⟨Z, hom_of_le hX, hom_of_le hY, trivial⟩,
cocone_maps := λ X Y f g, ⟨X, 𝟙 _, by simp⟩ }
@[priority 100]
instance is_cofiltered_of_directed_ge_nonempty (α : Type u) [preorder α] [is_directed α (swap (≤))]
[nonempty α] :
is_cofiltered α := {}
-- Sanity checks
example (α : Type u) [semilattice_inf α] [order_bot α] : is_cofiltered α := by apply_instance
example (α : Type u) [semilattice_inf α] [order_top α] : is_cofiltered α := by apply_instance
namespace is_cofiltered
variables {C} [is_cofiltered C]
/--
`min j j'` is an arbitrary choice of object to the left of both `j` and `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min (j j' : C) : C :=
(is_cofiltered_or_empty.cocone_objs j j').some
/--
`min_to_left j j'` is an arbitrarily choice of morphism from `min j j'` to `j`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_left (j j' : C) : min j j' ⟶ j :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some
/--
`min_to_right j j'` is an arbitrarily choice of morphism from `min j j'` to `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_right (j j' : C) : min j j' ⟶ j' :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`eq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq {j j' : C} (f f' : j ⟶ j') : C :=
(is_cofiltered_or_empty.cocone_maps f f').some
/--
`eq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq_hom {j j' : C} (f f' : j ⟶ j') : eq f f' ⟶ j :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some
/--
`eq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
-/
@[simp, reassoc]
lemma eq_condition {j j' : C} (f f' : j ⟶ j') : eq_hom f f' ≫ f = eq_hom f f' ≫ f' :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a cofiltered category has an object "to the left".
-/
lemma inf_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (S ⟶ X) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_cofiltered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use min X S',
rintros Y mY,
obtain rfl|h := eq_or_ne Y X,
{ exact ⟨min_to_left _ _⟩, },
{ exact ⟨min_to_right _ _ ≫ (w' (finset.mem_of_mem_insert_of_ne mY h)).some⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : S ⟶ X` from each `X`,
such that the triangles commute: `T X ≫ f = T Y`, for `f : X ⟶ Y` in the `finset`.
-/
lemma inf_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (S ⟶ X)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → T mX ≫ f = T mY :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := inf_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨eq (T' mX ≫ f) (T' mY), λ Z mZ, eq_hom (T' mX ≫ f) (T' mY) ≫ T' mZ, _⟩,
intros X' Y' mX' mY' f' mf',
rw [category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply eq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' _,
apply finset.mem_of_mem_insert_of_ne mf',
contrapose! h,
obtain ⟨rfl, h⟩ := h,
rw [heq_iff_eq, psigma.mk.inj_iff] at h,
exact ⟨rfl, h.1.symm⟩ }, },
end
/--
An arbitrary choice of object "to the left"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def inf : C :=
(inf_exists O H).some
/--
The morphisms from `inf O H`.
-/
noncomputable
def inf_to {X : C} (m : X ∈ O) :
inf O H ⟶ X :=
(inf_exists O H).some_spec.some m
/--
The triangles consisting of a morphism in `H` and the maps from `inf O H` commute.
-/
lemma inf_to_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
inf_to O H mX ≫ f = inf_to O H mY :=
(inf_exists O H).some_spec.some_spec mX mY mf
variables {J : Type v} [small_category J] [fin_category J]
/--
If we have `is_cofiltered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cone over `F`.
-/
lemma cone_nonempty (F : J ⥤ C) : _root_.nonempty (cone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := inf_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.id_comp],
symmetry,
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cone over `F : J ⥤ C`, for `fin_category J` and `is_cofiltered C`.
-/
noncomputable def cone (F : J ⥤ C) : cone F :=
(cone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is cofiltered, and we have a functor `L : C ⥤ D` with a right adjoint,
then `D` is cofiltered.
-/
lemma of_left_adjoint {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : is_cofiltered D :=
{ cocone_objs := λ X Y,
⟨L.obj (min (R.obj X) (R.obj Y)),
(h.hom_equiv _ X).symm (min_to_left _ _), (h.hom_equiv _ Y).symm (min_to_right _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨L.obj (eq (R.map f) (R.map g)), (h.hom_equiv _ _).symm (eq_hom _ _),
by rw [← h.hom_equiv_naturality_right_symm, ← h.hom_equiv_naturality_right_symm,
eq_condition]⟩,
nonempty := is_cofiltered.nonempty.map L.obj }
/-- If `C` is cofiltered, and we have a left adjoint functor `L : C ⥤ D`, then `D` is cofiltered. -/
lemma of_is_left_adjoint (L : C ⥤ D) [is_left_adjoint L] : is_cofiltered D :=
of_left_adjoint (adjunction.of_left_adjoint L)
/-- Being cofiltered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_cofiltered D :=
of_left_adjoint h.to_adjunction
end is_cofiltered
section opposite
open opposite
instance is_cofiltered_op_of_is_filtered [is_filtered C] : is_cofiltered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_filtered.max X.unop Y.unop),
(is_filtered.left_to_max _ _).op, (is_filtered.right_to_max _ _).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_filtered.coeq f.unop g.unop),
(is_filtered.coeq_hom _ _).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_filtered.coeq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_filtered.nonempty.some⟩ }
instance is_filtered_op_of_is_cofiltered [is_cofiltered C] : is_filtered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_cofiltered.min X.unop Y.unop),
(is_cofiltered.min_to_left X.unop Y.unop).op,
(is_cofiltered.min_to_right X.unop Y.unop).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_cofiltered.eq f.unop g.unop),
(is_cofiltered.eq_hom f.unop g.unop).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_cofiltered.eq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_cofiltered.nonempty.some⟩ }
end opposite
end category_theory
|
85497f52a5d5faf5aeb02b35b26928874fadbb66 | 74924b1fe80b8f61262cefcfc0cd4d96135c8731 | /src/algebra/ordered_ring.lean | 7587067fbdebf72ee010b524f15c09c9ed4fa759 | [
"Apache-2.0"
] | permissive | 101damnations/mathlib | 0938b3806a09032d8716d3642cbab65db7688c23 | 900c53ae6d5e3f8cc47953363479593e8debc4d8 | refs/heads/master | 1,593,832,305,164 | 1,565,631,735,000 | 1,565,631,735,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,654 | 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 tactic.split_ifs order.basic algebra.order algebra.ordered_group algebra.ring data.nat.cast
universe u
variable {α : Type u}
-- TODO: this is necessary additionally to mul_nonneg otherwise the simplifier can not match
lemma zero_le_mul [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b :=
mul_nonneg
section linear_ordered_semiring
variable [linear_ordered_semiring α]
@[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h),
λ h', mul_lt_mul_of_pos_left h' h⟩
@[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h),
λ h', mul_lt_mul_of_pos_right h' h⟩
lemma mul_lt_mul'' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) :
a * b < c * d :=
(lt_or_eq_of_le h4).elim
(λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1)))
(λ b0, by rw [← b0, mul_zero]; exact
mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2))
lemma le_mul_iff_one_le_left {a b : α} (hb : b > 0) : b ≤ a * b ↔ 1 ≤ a :=
suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this,
mul_le_mul_right hb
lemma lt_mul_iff_one_lt_left {a b : α} (hb : b > 0) : b < a * b ↔ 1 < a :=
suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this,
mul_lt_mul_right hb
lemma le_mul_iff_one_le_right {a b : α} (hb : b > 0) : b ≤ b * a ↔ 1 ≤ a :=
suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this,
mul_le_mul_left hb
lemma lt_mul_iff_one_lt_right {a b : α} (hb : b > 0) : b < b * a ↔ 1 < a :=
suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this,
mul_lt_mul_left hb
lemma lt_mul_of_gt_one_right' {a b : α} (hb : b > 0) : a > 1 → b < b * a :=
(lt_mul_iff_one_lt_right hb).2
lemma le_mul_of_ge_one_right' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a :=
suffices b * 1 ≤ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_ge_one_left' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b :=
suffices 1 * b ≤ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b :=
⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩
lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a :=
bit1_pos (le_of_lt h)
lemma lt_add_one (a : α) : a < a + 1 :=
lt_add_of_le_of_pos (le_refl _) zero_lt_one
lemma one_lt_two : 1 < (2 : α) := lt_add_one _
lemma one_lt_mul {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
(one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha)
lemma mul_le_one {a b : α} (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 :=
begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end
lemma one_lt_mul_of_le_of_lt {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha)
lemma one_lt_mul_of_lt_of_le {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul ha hb zero_lt_one (le_trans zero_le_one (le_of_lt ha))
lemma mul_le_of_le_one_right {a b : α} (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a :=
calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha
... = a : mul_one a
lemma mul_le_of_le_one_left {a b : α} (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b :=
calc a * b ≤ 1 * b : mul_le_mul ha1 (le_refl b) hb zero_le_one
... = b : one_mul b
lemma mul_lt_one_of_nonneg_of_lt_one_left {a b : α}
(ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 :=
calc a * b ≤ a : mul_le_of_le_one_right ha0 hb
... < 1 : ha
lemma mul_lt_one_of_nonneg_of_lt_one_right {a b : α}
(ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 :=
calc a * b ≤ b : mul_le_of_le_one_left hb0 ha
... < 1 : hb
lemma mul_le_iff_le_one_left {a b : α} (hb : b > 0) : a * b ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩
lemma mul_lt_iff_lt_one_left {a b : α} (hb : b > 0) : a * b < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩
lemma mul_le_iff_le_one_right {a b : α} (hb : b > 0) : b * a ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩
lemma mul_lt_iff_lt_one_right {a b : α} (hb : b > 0) : b * a < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩
lemma nonpos_of_mul_nonneg_left {a b : α} (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 :=
le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_neg_of_pos_of_neg ha hb)))
lemma nonpos_of_mul_nonneg_right {a b : α} (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 :=
le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_neg_of_neg_of_pos ha hb)))
lemma neg_of_mul_pos_left {a b : α} (h : 0 < a * b) (hb : b ≤ 0) : a < 0 :=
lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonpos_of_nonneg_of_nonpos ha hb)))
lemma neg_of_mul_pos_right {a b : α} (h : 0 < a * b) (ha : a ≤ 0) : b < 0 :=
lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonpos_of_nonpos_of_nonneg ha hb)))
end linear_ordered_semiring
section decidable_linear_ordered_semiring
variable [decidable_linear_ordered_semiring α]
@[simp] lemma decidable.mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h
@[simp] lemma decidable.mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h
end decidable_linear_ordered_semiring
instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] :
no_top_order α :=
⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩
instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] :
no_bot_order α :=
⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩
instance to_domain [s : linear_ordered_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s,
..s }
section linear_ordered_ring
variable [linear_ordered_ring α]
@[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h,
λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h,
λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h)
@[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h)
lemma sub_one_lt (a : α) : a - 1 < a :=
sub_lt_iff_lt_add.2 (lt_add_one a)
lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a :=
by rcases lt_trichotomy a 0 with h|h|h;
[exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h]
lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y :=
begin
cases le_total 0 x,
{ exact mul_self_le_mul_self h h₁ },
{ rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ }
end
lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a :=
le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb)))
lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b :=
le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb)))
lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a :=
lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb)))
lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b :=
lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb)))
end linear_ordered_ring
set_option old_structure_cmd true
/-- Extend `nonneg_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (α : Type*)
extends ring α, zero_ne_one_class α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(mul_pos : ∀ {a b}, pos a → pos b → pos (a * b))
/-- Extend `nonneg_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(nonneg_total : ∀ a, nonneg a ∨ nonneg (-a))
namespace nonneg_ring
open nonneg_comm_group
variable [s : nonneg_ring α]
instance to_ordered_ring : ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg,
mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos,
..s }
def nonneg_ring.to_linear_nonneg_ring
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_nonneg_ring α :=
{ nonneg_total := nonneg_total,
eq_zero_or_eq_zero_of_mul_eq_zero :=
suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0,
from λ a b, (nonneg_total a).elim (this b)
(λ na, by simpa using this b na),
suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0,
from λ a b na, (nonneg_total b).elim (this na)
(λ nb, by simpa using this na nb),
λ a b na nb z, classical.by_cases
(λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna))
(λ pa, classical.by_cases
(λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb))
(λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos
((pos_iff _ _).2 ⟨na, pa⟩)
((pos_iff _ _).2 ⟨nb, pb⟩))),
..s }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_comm_group
variable [s : linear_nonneg_ring α]
instance to_nonneg_ring : nonneg_ring α :=
{ mul_pos := λ a b pa pb,
let ⟨a1, a2⟩ := (pos_iff α a).1 pa,
⟨b1, b2⟩ := (pos_iff α b).1 pb in
have ab : nonneg (a * b), from mul_nonneg a1 b1,
(pos_iff α _).2 ⟨ab, λ hn,
have a * b = 0, from nonneg_antisymm ab hn,
(eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim
(ne_of_gt (pos_def.1 pa))
(ne_of_gt (pos_def.1 pb))⟩,
..s }
instance to_linear_order : linear_order α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
..s }
instance to_linear_ordered_ring : linear_ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := @le_total _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _,
mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin
rw [zero_sub] at h,
have := mul_nonneg h h, simp at this,
exact zero_ne_one _ (nonneg_antisymm this h).symm
end, ..s }
instance to_decidable_linear_ordered_comm_ring
[decidable_pred (@nonneg α _)]
[comm : @is_commutative α (*)]
: decidable_linear_ordered_comm_ring α :=
{ decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
mul_comm := is_commutative.comm (*),
..@linear_nonneg_ring.to_linear_ordered_ring _ s }
end linear_nonneg_ring
class canonically_ordered_comm_semiring (α : Type*) extends
canonically_ordered_monoid α, comm_semiring α, zero_ne_one_class α :=
(mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0)
namespace canonically_ordered_semiring
open canonically_ordered_monoid
lemma mul_le_mul [canonically_ordered_comm_semiring α] {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) :
a * c ≤ b * d :=
begin
rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩,
rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩,
suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul],
exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩
end
end canonically_ordered_semiring
instance : canonically_ordered_comm_semiring ℕ :=
{ le_iff_exists_add := assume a b,
⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩,
assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩,
zero_ne_one := ne_of_lt zero_lt_one,
mul_eq_zero_iff := assume a b,
iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}),
bot := 0,
bot_le := nat.zero_le,
.. (infer_instance : ordered_comm_monoid ℕ),
.. (infer_instance : linear_ordered_semiring ℕ),
.. (infer_instance : comm_semiring ℕ) }
namespace with_top
variables [canonically_ordered_comm_semiring α] [decidable_eq α]
instance : mul_zero_class (with_top α) :=
{ zero := 0,
mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)),
zero_mul := assume a, if_pos $ or.inl rfl,
mul_zero := assume a, if_pos $ or.inr rfl }
instance : has_one (with_top α) := ⟨↑(1:α)⟩
lemma mul_def {a b : with_top α} :
a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl
@[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) .
@[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ .
@[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 :=
iff.intro
(assume h, match a, h with _, rfl := rfl end)
(assume h, h.symm ▸ rfl)
@[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 :=
by rw [eq_comm, coe_eq_zero]
@[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl
@[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ :=
top_mul top_ne_zero
lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b :=
decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha,
decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb,
by simp [*, mul_def]; refl
lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b))
| none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤,
by simp [hb]
| (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm
private lemma comm (a b : with_top α) : a * b = b * a :=
begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
simp [ha, hb, mul_def, option.bind_comm a b, mul_comm]
end
@[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) :=
begin
have H : ∀x:α, (¬x = 0) ↔ (⊤ : with_top α) * ↑x = ⊤ :=
λx, ⟨λhx, by simp [top_mul, hx], λhx f, by simpa [f] using hx⟩,
cases a; cases b; simp [none_eq_top, top_mul, coe_ne_top, some_eq_coe, coe_mul.symm],
{ rw [H b] },
{ rw [H a, comm] }
end
private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c :=
begin
cases c,
{ show (a + b) * ⊤ = a * ⊤ + b * ⊤,
by_cases ha : a = 0; simp [ha] },
{ show (a + b) * c = a * c + b * c,
by_cases hc : c = 0, { simp [hc] },
simp [mul_coe hc], cases a; cases b,
repeat { refl <|> exact congr_arg some (add_mul _ _ _) } }
end
private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 :=
by cases a; cases b; dsimp [mul_def]; split_ifs;
simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at *
private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) :=
begin
cases a,
{ by_cases hb : b = 0; by_cases hc : c = 0;
simp [*, none_eq_top, mul_eq_zero b c] },
cases b,
{ by_cases ha : a = 0; by_cases hc : c = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] },
cases c,
{ by_cases ha : a = 0; by_cases hb : b = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] },
simp [some_eq_coe, coe_mul.symm, mul_assoc]
end
private lemma one_mul' : ∀a : with_top α, 1 * a = a
| none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_bot.coe_one]
| (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_bot.coe_one]
instance [canonically_ordered_comm_semiring α] [decidable_eq α] :
canonically_ordered_comm_semiring (with_top α) :=
{ one := (1 : α),
right_distrib := distrib',
left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl,
mul_assoc := assoc,
mul_comm := comm,
mul_eq_zero_iff := mul_eq_zero,
one_mul := one_mul',
mul_one := assume a, by rw [comm, one_mul'],
zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h,
.. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_monoid }
@[simp] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n
| 0 := rfl
| (n+1) := have (((1 : nat) : α) : with_top α) = ((1 : nat) : with_top α) := rfl,
by rw [nat.cast_add, coe_add, nat.cast_add, coe_nat n, this]
@[simp] lemma nat_ne_top (n : nat) : (n : with_top α ) ≠ ⊤ :=
by rw [←coe_nat n]; apply coe_ne_top
@[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n :=
by rw [←coe_nat n]; apply top_ne_coe
@[elab_as_eliminator]
lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ)
(h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a :=
begin
have A : ∀n:ℕ, P n,
{ assume n,
induction n with n IH,
{ exact h0 },
{ exact hsuc n IH } },
cases a,
{ exact htop A },
{ exact A a }
end
end with_top
|
23e698b5ac8127b86836aabc0fb3464cc58ff8a9 | 6ae186a0c6ab366b39397ec9250541c9d5aeb023 | /src/category_theory/adjunctions/examples/functor_categories.lean | c8f0404b12e6fd62ec543276bdbd754b1710a543 | [] | no_license | ThanhPhamPhuong/lean-category-theory | 0d5c4fe1137866b4fe29ec2753d99aa0d0667881 | 968a29fe7c0b20e10d8a27e120aca8ddc184e1ea | refs/heads/master | 1,587,206,682,489 | 1,544,045,056,000 | 1,544,045,056,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 842 | 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
open category_theory
namespace categories.adjunctions
universes u₁ u₂ u₃
variable {C : Type (u₁+1)}
variable [large_category C]
variable {D : Type (u₂+1)}
variable [large_category D]
variable {E : Type (u₃+1)}
variable [large_category E]
-- EXERCISE an adjunction F ⊢ G gives an adjunction F^* ⊢ G^*
-- cf Leinster 2.2.14
-- def pullback_adjunction {L : Functor C D} {R : Functor D C} (A : Adjunction L R)
-- : Adjunction (whisker_left_functor L E) (whisker_left_functor R E) := {
-- unit := sorry,
-- counit := sorry,
-- triangle_1 := sorry,
-- triangle_2 := sorry
-- }
end categories.adjunctions |
b0c6582e684d9b3c204223d445e947f0714ac0c4 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/number_theory/quadratic_reciprocity.lean | e2ddcd8cd422c5a84871009dbd86f31f85d55e49 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 24,971 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import field_theory.finite
import data.zmod.basic
import data.nat.parity
/-!
# Quadratic reciprocity.
This file contains results about quadratic residues modulo a prime number.
The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the
interpretations in terms of existence of square roots depending on the congruence mod 4,
`exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and
`exists_pow_two_eq_prime_iff_of_mod_four_eq_three`.
Also proven are conditions for `-1` and `2` to be a square modulo a prime,
`exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and
`exists_pow_two_eq_two_iff`
## Implementation notes
The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma
-/
open function finset nat finite_field zmod
open_locale big_operators
namespace zmod
variables (p q : ℕ) [fact p.prime] [fact q.prime]
@[simp] lemma card_units : fintype.card (units (zmod p)) = p - 1 :=
by rw [card_units, card]
/-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem fermat_little_units {p : ℕ} [fact p.prime] (a : units (zmod p)) :
a ^ (p - 1) = 1 :=
by rw [← card_units p, pow_card_eq_one]
/-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem fermat_little {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 :=
begin
have := fermat_little_units (units.mk0 a ha),
apply_fun (coe : units (zmod p) → zmod p) at this,
simpa,
end
/-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion_units (x : units (zmod p)) :
(∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim },
obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)),
obtain ⟨n, hn⟩ : x ∈ powers g, { rw powers_eq_gpowers, apply hg },
split,
{ rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, fermat_little_units], },
{ subst x, assume h,
have key : 2 * (p / 2) ∣ n * (p / 2),
{ rw [← pow_mul] at h,
rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg],
apply order_of_dvd_of_pow_eq_one h },
have : 0 < p / 2 := nat.div_pos (show fact (1 < p), by apply_instance) dec_trivial,
obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key,
refine ⟨g ^ m, _⟩,
rw [mul_comm, pow_mul], },
end
/-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion {a : zmod p} (ha : a ≠ 0) :
(∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 :=
begin
apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)),
simp only [units.ext_iff, _root_.pow_two, units.coe_mk0, units.coe_mul],
split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ },
{ rintro ⟨y, rfl⟩,
have hy : y ≠ 0, { rintro rfl, simpa [_root_.zero_pow] using ha, },
refine ⟨units.mk0 y hy, _⟩, simp, }
end
lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three :
(∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ substI p, exact dec_trivial },
change fact (p % 2 = 1) at hp_odd, resetI,
have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero,
rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two],
cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd,
{ rw [p_half_even, _root_.pow_zero, eq_self_iff_true, true_iff],
contrapose! p_half_even with hp,
rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp],
exact dec_trivial },
{ rw [p_half_odd, _root_.pow_one,
iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not],
rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd,
rw [_root_.fact, ← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd,
have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial,
revert hp hp_odd p_half_odd,
generalize : p % 4 = k, revert k, exact dec_trivial }
end
lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) :
a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ substI p, revert a ha, exact dec_trivial },
rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp_odd],
exact fermat_little p ha
end
/-- Wilson's Lemma: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/
@[simp] lemma wilsons_lemma : (nat.fact (p - 1) : zmod p) = -1 :=
begin
refine
calc (nat.fact (p - 1) : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) :
by rw [← finset.prod_Ico_id_eq_fact, prod_nat_cast]
... = (∏ x : units (zmod p), x) : _
... = -1 :
by rw [prod_hom _ (coe : units (zmod p) → zmod p),
prod_univ_units_id_eq_neg_one, units.coe_neg, units.coe_one],
have hp : 0 < p := nat.prime.pos ‹p.prime›,
symmetry,
refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _,
{ intros a ha,
rw [Ico.mem, ← nat.succ_sub hp, nat.succ_sub_one],
split,
{ apply nat.pos_of_ne_zero, rw ← @val_zero p,
assume h, apply units.coe_ne_zero a (val_injective p h) },
{ exact val_lt _ } },
{ intros a ha, simp only [cast_id, nat_cast_val], },
{ intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h },
{ intros b hb,
rw [Ico.mem, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, nat.pos_iff_ne_zero] at hb,
refine ⟨units.mk0 b _, finset.mem_univ _, _⟩,
{ assume h, apply hb.1, apply_fun val at h,
simpa only [val_cast_of_lt hb.right, val_zero] using h },
{ simp only [val_cast_of_lt hb.right, units.coe_mk0], } }
end
@[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 :=
begin
conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (nat.prime.pos ‹p.prime›)] },
rw [← prod_nat_cast, finset.prod_Ico_id_eq_fact, wilsons_lemma]
end
end zmod
/-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value
of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set
of non zero natural numbers `x` such that `x ≤ p / 2` -/
lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id
(p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) :
(Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) =
(Ico 1 (p / 2).succ).1.map (λ a, a) :=
begin
have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2,
by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt},
have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p,
from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial),
have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x,
from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx),
have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ),
(a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ,
{ assume x hx,
simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff,
nat.pos_iff_ne_zero, nat_abs_val_min_abs_le _], },
have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ),
∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs,
{ assume b hb,
refine ⟨(b / a : zmod p).val_min_abs.nat_abs, Ico.mem.mpr ⟨_, _⟩, _⟩,
{ apply nat.pos_of_ne_zero,
simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff,
val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] },
{ apply lt_succ_of_le, apply nat_abs_val_min_abs_le },
{ rw cast_nat_abs_val_min_abs,
split_ifs,
{ erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb),
if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], },
{ erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg,
val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2),
int.nat_abs_of_nat] } } },
exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _)
(λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl)
(inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj
end
private lemma gauss_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
(a^(p / 2) * (p / 2).fact : zmod p) =
(-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact :=
calc (a ^ (p / 2) * (p / 2).fact : zmod p) =
(∏ x in Ico 1 (p / 2).succ, a * x) :
by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact,
prod_const, Ico.card, succ_sub_one]; simp
... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp
... = (∏ x in Ico 1 (p / 2).succ,
(if (a * x : zmod p).val ≤ p / 2 then 1 else -1) *
(a * x : zmod p).val_min_abs.nat_abs) :
prod_congr rfl $ λ _ _, begin
simp only [cast_nat_abs_val_min_abs],
split_ifs; simp
end
... = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card *
(∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) :
have (∏ x in Ico 1 (p / 2).succ,
if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) =
(∏ x in (Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1),
from prod_bij_ne_one (λ x _ _, x)
(λ x, by split_ifs; simp * at * {contextual := tt})
(λ _ _ _ _ _ _, id)
(λ b h _, ⟨b, by simp [-not_le, *] at *⟩)
(by intros; split_ifs at *; simp * at *),
by rw [prod_mul_distrib, this]; simp
... = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact :
by rw [← prod_nat_cast, finset.prod_eq_multiset_prod,
Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap,
← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact]
private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
(a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card :=
(domain.mul_left_inj
(show ((p / 2).fact : zmod p) ≠ 0,
by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.dvd_fact, not_le];
exact nat.div_lt_self hp.pos dec_trivial)).1 $
by simpa using gauss_lemma_aux₁ p hap
private lemma eisenstein_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) =
((Ico 1 (p / 2).succ).filter
((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card +
∑ x in Ico 1 (p / 2).succ, x
+ (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) :=
have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2,
calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2)
= ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) :
by simp only [mod_add_div]
... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) +
(∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) :
by simp only [val_cast_nat];
simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2]
... = _ : congr_arg2 (+)
(calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2)
= ∑ x in Ico 1 (p / 2).succ,
((((a * x : zmod p).val_min_abs +
(if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) :
by simp only [(val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast]
... = ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card +
((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) :
by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast], }
... = _ : by rw [finset.sum_eq_multiset_sum,
Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap,
← finset.sum_eq_multiset_sum];
simp [sum_nat_cast]) rfl
private lemma eisenstein_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) :
((Ico 1 (p / 2).succ).filter
((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card
≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] :=
have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2,
(eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $
by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast,
add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc]
using eq.symm (eisenstein_lemma_aux₁ p hap)
lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b =
((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card :=
calc a / b = (Ico 1 (a / b).succ).card : by simp
... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card :
congr_arg _ $ finset.ext $ λ x,
have x * b ≤ a → x ≤ c,
from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc,
by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto
/-- The given sum is the number of integer points in the triangle formed by the diagonal of the
rectangle `(0, p/2) × (0, q/2)` -/
private lemma sum_Ico_eq_card_lt {p q : ℕ} :
∑ a in Ico 1 (p / 2).succ, (a * q) / p =
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card :=
if hp0 : p = 0 then by simp [hp0, finset.ext_iff]
else
calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p =
∑ a in Ico 1 (p / 2).succ,
((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card :
finset.sum_congr rfl $ λ x hx,
div_eq_filter_card (nat.pos_of_ne_zero hp0)
(calc x * q / p ≤ (p / 2) * q / p :
nat.div_le_div_right (mul_le_mul_of_nonneg_right
(le_of_lt_succ $ by finish)
(nat.zero_le _))
... ≤ _ : nat.div_mul_div_le_div _ _ _)
... = _ : by rw [← card_sigma];
exact card_congr (λ a _, ⟨a.1, a.2⟩)
(by simp {contextual := tt})
(λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩,
by revert h; simp {contextual := tt}⟩)
/-- Each of the sums in this lemma is the cardinality of the set integer points in each of the
two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them
gives the number of points in the rectangle. -/
private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime]
(hq0 : (q : zmod p) ≠ 0) :
∑ a in Ico 1 (p / 2).succ, (a * q) / p +
∑ a in Ico 1 (q / 2).succ, (a * p) / q =
(p / 2) * (q / 2) :=
have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card =
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card :=
card_congr (λ x _, prod.swap x)
(λ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {contextual := tt}⟩),
have hdisj : disjoint
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q))
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)),
from disjoint_filter.2 $ λ x hx hpq hqp,
have hxp : x.1 < p, from lt_of_le_of_lt
(show x.1 ≤ p / 2, by simp [*, nat.lt_succ_iff] at *; tauto)
(nat.div_lt_self hp.pos dec_trivial),
begin
have : (x.1 : zmod p) = 0,
{ simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) },
apply_fun zmod.val at this,
rw [val_cast_of_lt hxp, val_zero] at this,
simp * at *
end,
have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪
((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) =
((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)),
from finset.ext $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto,
by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion,
card_product];
simp
variables (p q : ℕ) [fact p.prime] [fact q.prime]
namespace zmod
/-- The Legendre symbol of `a` and `p` is an integer defined as
* `0` if `a` is `0` modulo `p`;
* `1` if `a ^ (p / 2)` is `1` modulo `p`
(by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”);
* `-1` otherwise.
-/
def legendre_sym (a p : ℕ) : ℤ :=
if (a : zmod p) = 0 then 0
else if (a : zmod p) ^ (p / 2) = 1 then 1
else -1
lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] :
(legendre_sym a p : zmod p) = (a ^ (p / 2)) :=
begin
rw legendre_sym,
by_cases ha : (a : zmod p) = 0,
{ simp only [if_pos, ha, _root_.zero_pow (nat.div_pos (hp.two_le) (succ_pos 1)), int.cast_zero] },
cases hp.eq_two_or_odd with hp2 hp_odd,
{ substI p,
have : ∀ (a : zmod 2),
((if a = 0 then 0 else if a ^ (2 / 2) = 1 then 1 else -1 : ℤ) : zmod 2) = a ^ (2 / 2),
by exact dec_trivial,
exact this a },
{ change fact (p % 2 = 1) at hp_odd, resetI,
rw if_neg ha,
have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm,
cases pow_div_two_eq_neg_one_or_one p ha with h h,
{ rw [if_pos h, h, int.cast_one], },
{ rw [h, if_neg this, int.cast_neg, int.cast_one], } }
end
lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) :
legendre_sym a p = -1 ∨ legendre_sym a p = 1 :=
by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at *
lemma legendre_sym_eq_zero_iff (a p : ℕ) :
legendre_sym a p = 0 ↔ (a : zmod p) = 0 :=
begin
split,
{ classical, contrapose,
assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h,
all_goals { rw h, norm_num } },
{ assume ha, rw [legendre_sym, if_pos ha] }
end
/-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less
than `p/2` such that `(a * x) % p > p / 2` -/
lemma gauss_lemma {a : ℕ} [hp1 : fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card :=
have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p),
by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp,
begin
cases legendre_sym_eq_one_or_neg_one a p ha0;
cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card;
simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at *
end
lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) :=
begin
rw [euler_criterion p ha0, legendre_sym, if_neg ha0],
split_ifs,
{ simp only [h, eq_self_iff_true] },
finish -- this is quite slow. I'm actually surprised that it can close the goal at all!
end
lemma eisenstein_lemma [hp1 : fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p :=
by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two,
show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0]
theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) :
legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) :=
have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm,
have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq,
by rw [eisenstein_lemma q hp1 hpq0, eisenstein_lemma p hq1 hqp0,
← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm]
-- move this
instance fact_prime_two : fact (nat.prime 2) := nat.prime_two
lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) :=
have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1),
have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial)
(nat.div_le_self (p / 2) 2),
have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp,
have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x,
from λ x hx, have h2xp : 2 * x < p,
from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left
(le_of_lt_succ $ by finish) dec_trivial
... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, show p % 2 = 1, from hp1]}; exact lt_succ_self _,
by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp],
have hdisj : disjoint
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val))
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)),
from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]),
have hunion :
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) =
Ico 1 (p / 2).succ,
begin
rw [filter_union_right],
conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]},
exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm])
end,
begin
rw [gauss_lemma p (prime_ne_zero p 2 hp2),
neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)],
refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _),
rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add,
← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two,
← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard]
end
lemma exists_pow_two_eq_two_iff [hp1 : fact (p % 2 = 1)] :
(∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 :=
have hp2 : ((2 : ℕ) : zmod p) ≠ 0,
from prime_ne_zero p 2 (λ h, by simpa [h] using hp1),
have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm,
have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm,
begin
rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2,
legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial),
even_add, even_div, even_div],
have := nat.mod_lt p (show 0 < 8, from dec_trivial),
resetI, rw _root_.fact at hp1,
revert this hp1,
erw [hpm4, hpm2],
generalize hm : p % 8 = m,
clear hm,
revert m,
exact dec_trivial
end
lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] :
(∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p :=
if hpq : p = q then by substI hpq else
have h1 : ((p / 2) * (q / 2)) % 2 = 0,
from (dvd_iff_mod_eq_zero _ _).1
(dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $
by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _),
begin
haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_one hp1,
have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq),
have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg hqp0, if_neg hpq0] at this,
rw [euler_criterion q hpq0, euler_criterion p hqp0],
split_ifs at this; simp *; contradiction,
end
lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3)
(hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p :=
have h1 : ((p / 2) * (q / 2)) % 2 = 1,
from nat.odd_mul_odd
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl)
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl),
begin
haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_three hp3,
haveI hq_odd : fact (q % 2 = 1) := odd_of_mod_four_eq_three hq3,
have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq),
have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg hpq0, if_neg hqp0] at this,
rw [euler_criterion q hpq0, euler_criterion p hqp0],
split_ifs at this; simp *; contradiction
end
end zmod
|
22fd976c6c4fbe70805919fd328f5b4baad80fbc | 9bb72db9297f7837f673785604fb89b3184e13f8 | /library/init/meta/widget/basic.lean | 93c275c9e57f3cccd8d2d1f98bac07bcbc3b72e1 | [
"Apache-2.0"
] | permissive | dselsam/lean | ec83d7592199faa85687d884bbaaa570b62c1652 | 6b0bd5bc2e07e13880d332c89093fe3032bb2469 | refs/heads/master | 1,621,807,064,966 | 1,611,454,685,000 | 1,611,975,642,000 | 42,734,348 | 3 | 3 | null | 1,498,748,560,000 | 1,442,594,289,000 | C++ | UTF-8 | Lean | false | false | 16,412 | 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
-/
prelude
import init.function
import init.data.option.basic
import init.util
import init.meta.tactic
import init.meta.mk_dec_eq_instance
import init.meta.json
/-! A component is a piece of UI which may contain internal state. Use component.mk to build new components.
## Using widgets.
To make a widget, you need to make a custom executor object and then instead of calling `save_info_thunk` you call `save_widget`.
Additionally, you will need a compatible build of the vscode extension or web app to use widgets in vscode.
## How it works:
The design is inspired by React.
If you are familiar with using React or Elm or a similar functional UI framework then that's helpful for this.
The [React article on reconciliation](https://reactjs.org/docs/reconciliation.html) might be helpful.
One can imagine making a UI for a particular object as just being a function `f : α → UI` where `UI` is some inductive datatype for buttons, textboxes, lists and so on.
The process of evaluating `f` is called __rendering__.
So for example `α` could be `tactic_state` and the function renders a goal view.
## HTML
For our purposes, `UI` is an HTML tree and is written `html α : Type`. I'm going to assume some familiarity with HTML for the purposes of this document.
An HTML tree is composed of elements and strings.
Each element has a tag such as "div", "span", "article" and so on and a set of attributes and child html.
Use the helper function `h : string → list (attr α) → list (html α) → html α` to build new pieces of `html`. So for example:
```lean
h "ul" [] [
h "li" [] ["this is list item 1"],
h "li" [style [("color", "blue")]] ["this is list item 2"],
h "hr" [] [],
h "li" [] [
h "span" [] ["there is a button here"],
h "button" [on_click (λ _, 3)] ["click me!"]
]
]
```
Has the type `html nat`.
The `nat` type is called the __action__ and whenever the user interacts with the UI, the html will emit an object of type `nat`.
So for example if the user clicks the button above, the html will 'emit' `3`.
The above example is compiled to the following piece of html:
```html
<ul>
<li>this is list item 1</li>
<li style="{ color: blue; }">this is list item 2</li>
<hr/>
<li>
<span>There is a button here</span>
<button onClick="[handler]">click me!</button>
</li>
</ul>
```
## Components
In order for the UI to react to events, you need to be able to take these actions α and alter some state.
To do this we use __components__. `component` takes two type arguments: `π` and `α`. `α` is called the 'action' and `π` are the 'props'.
The props can be thought of as a kind of wrapped function domain for `component`. So given `C : component nat α`, one can turn this into html with
`html.of_component 4 C : html α`.
The base constructor for a component is `pure`:
```lean
meta def Hello : component string α := component.pure (λ s, ["hello, ", s, ", good day!"])
#html Hello "lean" -- renders "hello, lean, good day!"
```
So here a pure component is just a simple function `π → list (html α)`.
However, one can augment components with __hooks__.
The hooks available for compoenents are listed in the inductive definition for component.
Here we will just look at the `with_state` hook, which can be used to build components with inner state.
```
meta inductive my_action
| increment
| decrement
open my_action
meta def Counter : component unit α :=
component.with_state
my_action -- the action of the inner component
int -- the state
(λ _, 0) -- initialise the state
(λ _ _ s, s) -- update the state if the props change
(λ _ s a, -- update the state if an action was received
match a with
| increment := (s + 1, none) -- replace `none` with `some _` to emit an action
| decrement := (s - 1, none)
end
)
$ component.pure (λ ⟨state, ⟨⟩⟩, [
button "+" (λ _, increment),
to_string state,
button "-" (λ _, decrement)
])
#html Counter ()
```
You can add many hooks to a component.
- `filter_map_action` lets you filter or map actions that are emmitted by the component
- `map_props` lets you map the props.
- `with_should_update` will not re-render the child component if the given test returns false. This can be useful for efficiency.
- `with_state` discussed above.`
- `with_mouse` subscribes the component to the mouse state, for example whether or not the mouse is over the component. See the `tests/lean/widget/widget_mouse.lean` test for an example.
Given an active document, Lean (in server mode) maintains a set of __widgets__ for the document.
A widget is a component `c`, some `p : Props` and an internal state-manager which manages the states
of the component and subcomponents and also handles the routing of events from the UI.
## Reconciliation
If a parent component's state changes, this can cause child components to change position or to appear and dissappear.
However we want to preserve the state of these child components where we can.
The UI system will try to match up these child components through a process called __reconciliation__.
Reconciliation will make sure that the states are carried over correctly and will also not rerender subcomponents if they haven't changed their props or state.
To compute whether two components are the same, the system will perform a hash on their VM objects.
Not all VM objects can be hashed, so it's important to make sure that any items that you expect to change over the lifetime of the component are fed through the 'Props' argument.
This is why we need the props argument on `component`.
The reconciliation engine uses the `props_eq` predicate passed to the component constructor to determine whether the props have changed and hence whether the component should be re-rendered.
## Keys
If you have some list of components and the list changes according to some state, it is important to add keys to the components so
that if two components change order in the list their states are preserved.
If you don't provide keys or there are duplicate keys then you may get some strange behaviour in both the Lean widget engine and react.
It is possible to use incorrect HTML tags and attributes, there is (currently) no type checking that the result is a valid piece of HTML.
So for example, the client widget system will error if you add a `text_change_event` attribute to anything other than an element tagged with `input`.
## Styles with Tachyons
The widget system assumes that a stylesheet called 'tachyons' is present.
You can find documentation for this stylesheet at [Tachyons.io](http://tachyons.io/).
Tachyons was chosen because it is very terse and allows arbitrary styling without using inline styles and without needing to dynamically load a stylesheet.
## Further work (up for grabs!)
- Add type checking for html.
- Better error handling when the html tree is malformed.
- Better error handling when keys are malformed.
- Add a 'with_task' which lets long-running operations (eg running `simp`) not block the UI update.
- Timers, animation (ambitious).
- More event handlers
- Drag and drop support.
- The current perf bottleneck is sending the full UI across to the server for every update.
Instead, it should be possible to send a smaller [JSON Patch](http://jsonpatch.com).
Which is already supported by `json.hpp` and javascript ecosystem.
-/
namespace widget
inductive mouse_event_kind
| on_click
| on_mouse_enter
| on_mouse_leave
/-- An effect is some change that the widget makes outside of its own state.
Usually, giving instructions to the editor to perform some task.
- `insert_text_relative` will insert at a line relative to the position of the widget.
- `insert_text_absolute` will insert text at the precise position given.
- `reveal_position` will move the editor to view the given position.
- `highlight_position` will add a text highlight to the given position.
- `clear_highlighting` will remove all highlights created with `highlight_position`.
- `copy_text` will copy the given text to the clipboard.
- `custom` can be used to pass custom effects to the client without having to recompile Lean.
-/
meta inductive effect : Type
| insert_text_absolute (file_name : option string) (p : pos) (text : string)
| insert_text_relative (relative_line : int) (text : string)
| reveal_position (file_name : option string) (p : pos)
| highlight_position (file_name : option string) (p : pos)
| clear_highlighting
| copy_text (text : string)
| custom (key : string) (value : string)
meta def effects := list effect
meta mutual inductive component, html, attr
with component : Type → Type → Type
| pure
{Props Action : Type}
(view : Props → list (html Action))
: component Props Action
| filter_map_action
{Props InnerAction OuterAction}
(action_map : Props → InnerAction → option OuterAction)
: component Props InnerAction → component Props OuterAction
| map_props
{Props1 Props2 Action}
(map : Props2 → Props1)
: component Props1 Action → component Props2 Action
| with_should_update
{Props Action : Type}
(should_update : Π (old new : Props), bool)
: component Props Action → component Props Action
| with_state
{Props Action : Type}
(InnerAction State : Type)
(init : Props → State)
(props_changed : Props → Props → State → State)
(update : Props → State → InnerAction → State × option Action)
: component (State × Props) InnerAction → component Props Action
| with_effects
{Props Action : Type}
(emit : Props → Action → effects)
: component Props Action → component Props Action
with html : Type → Type
| element {α : Type} (tag : string) (attrs : list (attr α)) (children : list (html α)) : html α
| of_string {α : Type} : string → html α
| of_component {α : Type} {Props : Type} : Props → component Props α → html α
with attr : Type → Type
| val {α : Type} (name : string) (value : json) : attr α
| mouse_event {α : Type} (kind : mouse_event_kind) (handler : unit → α) : attr α
| style {α : Type} : list (string × string) → attr α
| tooltip {α : Type} : html α → attr α
| text_change_event {α : Type} (handler : string → α) : attr α
variables {α β : Type} {π : Type}
namespace component
meta def map_action (f : α → β) : component π α → component π β
| c := filter_map_action (λ p a, some $ f a) c
/-- Returns a component that will never trigger an action. -/
meta def ignore_action : component π α → component π β
| c := component.filter_map_action (λ p a, none) c
meta def ignore_props : component unit α → component π α
| c := with_should_update (λ a b, ff) $ component.map_props (λ p, ()) c
meta instance : has_coe (component π empty) (component π α) :=
⟨component.filter_map_action (λ p x, none)⟩
meta instance : has_coe_to_fun (component π α) :=
{ F := λ c, π → html α,
coe := λ c p, html.of_component p c }
meta def stateful {π α : Type}
(β σ : Type)
(init : π → option σ → σ)
(update : π → σ → β → σ × option α)
(view : π → σ → list (html β))
: component π α :=
with_state β σ (λ p, init p none) (λ _ p s, init p $ some s) update (component.pure (λ ⟨s,p⟩, view p s))
meta def stateless {π α : Type} [decidable_eq π] (view : π → list (html α)) : component π α :=
component.with_should_update (λ p1 p2, p1 ≠ p2)
$ component.pure view
/-- Causes the component to only update on a props change when `test old_props new_props` yields `ff`. -/
meta def with_props_eq (test : π → π → bool) : component π α → component π α
| c := component.with_should_update (λ x y, bnot $ test x y) c
end component
meta mutual def attr.map_action, html.map_action (f : α → β)
with attr.map_action : attr α → attr β
| (attr.val k v) := attr.val k v
| (attr.style s) := attr.style s
| (attr.tooltip h) := attr.tooltip $ html.map_action h
| (attr.mouse_event k a) := attr.mouse_event k (f ∘ a)
| (attr.text_change_event a) := attr.text_change_event (f ∘ a)
with html.map_action : html α → html β
| (html.element t a c) := html.element t (list.map attr.map_action a) (list.map html.map_action c)
| (html.of_string s) := html.of_string s
| (html.of_component p c) := html.of_component p $ component.map_action f c
meta instance attr.is_functor : functor attr :=
{ map := @attr.map_action }
meta instance html.is_functor : functor html :=
{ map := λ _ _, html.map_action }
namespace html
meta instance to_string_coe [has_to_string β] : has_coe β (html α) :=
⟨html.of_string ∘ to_string⟩
meta instance : has_emptyc (html α) := ⟨of_string ""⟩
meta instance list_coe : has_coe (html α) (list (html α)) := ⟨λ x, [x]⟩
end html
meta def as_element : html α → option (string × list (attr α) × list (html α))
| (html.element t a c) := some ⟨t,a,c⟩
| _ := none
meta def key [has_to_string β] : β → attr α
| s := attr.val "key" $ to_string s
meta def className : string → attr α
| s := attr.val "className" $ s
meta def on_click : (unit → α) → attr α
| a := attr.mouse_event mouse_event_kind.on_click a
meta def on_mouse_enter : (unit → α) → attr α
| a := attr.mouse_event mouse_event_kind.on_mouse_enter a
meta def on_mouse_leave : (unit → α) → attr α
| a := attr.mouse_event mouse_event_kind.on_mouse_leave a
/-- Alias for `html.element`. -/
meta def h : string → list (attr α) → list (html α) → html α := html.element
/-- Alias for className. -/
meta def cn : string → attr α := className
meta def button : string → thunk α → html α
| s t := h "button" [on_click t] [s]
meta def textbox : string → (string → α) → html α
| s t := h "input" [attr.val "type" "text", attr.val "value" s, attr.text_change_event t] []
meta structure select_item (α : Type) :=
(result : α)
(key : string)
(view : list (html α))
/-- Choose from a dropdown selection list. -/
meta def select {α} [decidable_eq α] : list (select_item α) → α → html α
| items value :=
let k := match list.filter (λ i, select_item.result i = value) items with
| [] := "" | (h::_) := select_item.key h
end in
h "select" [
attr.val "value" k,
attr.val "key" k,
attr.text_change_event (λ k,
match items.filter (λ i, select_item.key i = k) with
| [] := undefined
| (h::_) := h.result
end
)]
$ items.map (λ i, h "option" [attr.val "value" i.key] $ select_item.view i)
/-- If the html is not an of_element it will wrap it in a div. -/
meta def with_attrs : list (attr α) → html α → html α
| a x := match as_element x with
| (some ⟨t,as,c⟩) := html.element t (a ++ as) c
| none := html.element "div" a [x]
end
/-- If the html is not an of_element it will wrap it in a div. -/
meta def with_attr : attr α → html α → html α
| a x := with_attrs [a] x
meta def with_style : string → string → html α → html α
| k v h := with_attr (attr.style [(k,v)]) h
meta def with_cn : string → html α → html α
| s h := with_attr (className s) h
meta def with_key {β} [has_to_string β] : β → html α → html α
| s h := with_attr (key s) h
meta def effect.insert_text : string → effect :=
effect.insert_text_relative 0
end widget
namespace tactic
/-- Same as `tactic.save_info_thunk` except saves a widget to be displayed by a compatible infoviewer. -/
meta constant save_widget : pos → widget.component tactic_state empty → tactic unit
/-- Outputs a widget trace position at the given position. -/
meta constant trace_widget_at (p : pos) (w : widget.component tactic_state empty)
(text := "(widget)") : tactic unit
/-- Outputs a widget trace position at the current default trace position. -/
meta def trace_widget (w : widget.component tactic_state empty) (text := "(widget)") : tactic unit :=
do p ← get_trace_msg_pos, trace_widget_at p w text
end tactic
|
c4a21aeed206e003c777b937ea94ab31abfd61dd | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/dedekind_domain/basic.lean | c4ad4e9238297f35776fa21ae23e56cc8457f084 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 4,823 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.ideal.over
import ring_theory.polynomial.rational_root
/-!
# Dedekind domains
This file defines the notion of a Dedekind domain (or Dedekind ring),
as a Noetherian integrally closed commutative ring of Krull dimension at most one.
## Main definitions
- `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is
Noetherian, integrally closed in its field of fractions and has Krull dimension at most one.
`is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
Often, definitions assume that Dedekind domains are not fields. We found it more practical
to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K]
open_locale non_zero_divisors polynomial
/-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/
def ring.dimension_le_one : Prop :=
∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal
open ideal ring
namespace ring
lemma dimension_le_one.principal_ideal_ring
[is_domain A] [is_principal_ideal_ring A] : dimension_le_one A :=
λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero }
lemma dimension_le_one.is_integral_closure (B : Type*) [comm_ring B] [is_domain B]
[nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A]
[is_integral_closure B R A] (h : dimension_le_one R) :
dimension_le_one B :=
λ p ne_bot prime, by exactI
is_integral_closure.is_maximal_of_is_maximal_comap A p
(h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance)
lemma dimension_le_one.integral_closure [nontrivial R] [is_domain A] [algebra R A]
(h : dimension_le_one R) : dimension_le_one (integral_closure R A) :=
h.is_integral_closure R A (integral_closure R A)
variables {R}
lemma dimension_le_one.not_lt_lt (h : ring.dimension_le_one R)
(p₀ p₁ p₂ : ideal R) [hp₁ : p₁.is_prime] [hp₂ : p₂.is_prime] :
¬ (p₀ < p₁ ∧ p₁ < p₂)
| ⟨h01, h12⟩ := h12.ne ((h p₁ (bot_le.trans_lt h01).ne' hp₁).eq_of_le hp₂.ne_top h12.le)
lemma dimension_le_one.eq_bot_of_lt (h : ring.dimension_le_one R)
(p P : ideal R) [hp : p.is_prime] [hP : P.is_prime] (hpP : p < P) : p = ⊥ :=
by_contra (λ hp0, h.not_lt_lt ⊥ p P ⟨ne.bot_lt hp0, hpP⟩)
end ring
variables [is_domain A]
/--
A Dedekind domain is an integral domain that is Noetherian, integrally closed, and
has Krull dimension at most one.
This is definition 3.2 of [Neukirch1992].
The integral closure condition is independent of the choice of field of fractions:
use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`.
This is the default implementation, but there are equivalent definitions,
`is_dedekind_domain_dvr` and `is_dedekind_domain_inv`.
TODO: Prove that these are actually equivalent definitions.
-/
class is_dedekind_domain : Prop :=
(is_noetherian_ring : is_noetherian_ring A)
(dimension_le_one : dimension_le_one A)
(is_integrally_closed : is_integrally_closed A)
-- See library note [lower instance priority]
attribute [instance, priority 100]
is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed
/-- An integral domain is a Dedekind domain iff and only if it is
Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field.
In particular, this definition does not depend on the choice of this fraction field. -/
lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] :
is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧
(∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) :=
⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩,
λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩
@[priority 100] -- See library note [lower instance priority]
instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] :
is_dedekind_domain A :=
⟨principal_ideal_ring.is_noetherian_ring,
ring.dimension_le_one.principal_ideal_ring A,
unique_factorization_monoid.is_integrally_closed⟩
|
c68f9e77ca09ac5cea820bdacd51f289719c8016 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/kernel2.lean | b36891faedf409f1eff846a972728227d9785bd5 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,142 | lean | import Lean
open Lean
def checkDefEq (a b : Name) : CoreM Unit := do
env ← getEnv;
let a := mkConst a;
let b := mkConst b;
let r := Kernel.isDefEq env {} a b;
IO.println (toString a ++ " =?= " ++ toString b ++ " := " ++ toString r)
def whnf (a : Name) : CoreM Unit := do
env ← getEnv;
let a := mkConst a;
let r := Kernel.whnf env {} a;
IO.println (toString a ++ " ==> " ++ toString r)
def fact : Nat → Nat
| 0 => 1
| (n+1) => (n+1)*fact n
def c1 := 30000000000 + 10000000000
def c2 := 40000000000
def c3 := fact 10
def v1 := 3628800
def v2 := 3628801
#eval whnf `c3
#eval checkDefEq `c3 `v1
#eval checkDefEq `c3 `v2
#eval checkDefEq `c1 `c2
def c4 := decide (100000000 < 20000000000)
#eval whnf `c4
#eval checkDefEq `c4 `Bool.true
def c5 := "h".length
def c6 := 1
set_option pp.all true
#eval whnf `c5
#eval checkDefEq `c5 `c6
def c7 := decide ("hello" = "world")
#eval whnf `c7
def c8 := "hello".length
#eval whnf `c8
def c9 : String := "hello" ++ "world"
def c10 : String := "helloworld"
#eval checkDefEq `c9 `c10
def c11 : Bool := decide ('a' = 'b')
#eval whnf `c11
def c12 : Nat := 'a'.toNat
#eval whnf `c12
|
72b491d6bfc9c5f2820f08f502ddd38071c86f60 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/sites/adjunction.lean | 4587bcca61a9fa40eae44dab795f2b10a2d82471 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,091 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.sites.compatible_sheafification
import category_theory.adjunction.whiskering
/-!
In this file, we show that an adjunction `F ⊣ G` induces an adjunction between
categories of sheaves, under certain hypotheses on `F` and `G`.
-/
namespace category_theory
open category_theory.grothendieck_topology
open category_theory
open category_theory.limits
open opposite
universes w₁ w₂ v u
variables {C : Type u} [category.{v} C] (J : grothendieck_topology C)
variables {D : Type w₁} [category.{max v u} D]
variables {E : Type w₂} [category.{max v u} E]
variables {F : D ⥤ E} {G : E ⥤ D}
variables [∀ (X : C) (S : J.cover X) (P : Cᵒᵖ ⥤ D),
preserves_limit (S.index P).multicospan F]
variables
[concrete_category.{max v u} D]
[preserves_limits (forget D)]
/-- The forgetful functor from `Sheaf J D` to sheaves of types, for a concrete category `D`
whose forgetful functor preserves the correct limits. -/
abbreviation Sheaf_forget : Sheaf J D ⥤ SheafOfTypes J :=
Sheaf_compose J (forget D) ⋙ (Sheaf_equiv_SheafOfTypes J).functor
-- We need to sheafify...
variables
[∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]
[∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
[∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]
[reflects_isomorphisms (forget D)]
namespace Sheaf
noncomputable theory
/-- This is the functor sending a sheaf `X : Sheaf J E` to the sheafification
of `X ⋙ G`. -/
abbreviation compose_and_sheafify (G : E ⥤ D) : Sheaf J E ⥤ Sheaf J D :=
Sheaf_to_presheaf J E ⋙ (whiskering_right _ _ _).obj G ⋙ presheaf_to_Sheaf J D
/-- An auxiliary definition to be used in defining `category_theory.Sheaf.adjunction` below. -/
@[simps]
def compose_equiv (adj : G ⊣ F) (X : Sheaf J E) (Y : Sheaf J D) :
((compose_and_sheafify J G).obj X ⟶ Y) ≃ (X ⟶ (Sheaf_compose J F).obj Y) :=
let A := adj.whisker_right Cᵒᵖ in
{ to_fun := λ η, ⟨A.hom_equiv _ _ (J.to_sheafify _ ≫ η.val)⟩,
inv_fun := λ γ, ⟨J.sheafify_lift ((A.hom_equiv _ _).symm ((Sheaf_to_presheaf _ _).map γ)) Y.2⟩,
left_inv := begin
intros η,
ext1,
dsimp,
symmetry,
apply J.sheafify_lift_unique,
rw equiv.symm_apply_apply,
end,
right_inv := begin
intros γ,
ext1,
dsimp,
rw [J.to_sheafify_sheafify_lift, equiv.apply_symm_apply],
end }
/-- An adjunction `adj : G ⊣ F` with `F : D ⥤ E` and `G : E ⥤ D` induces an adjunction
between `Sheaf J D` and `Sheaf J E`, in contexts where one can sheafify `D`-valued presheaves,
and `F` preserves the correct limits. -/
@[simps unit_app_val counit_app_val]
def adjunction (adj : G ⊣ F) : compose_and_sheafify J G ⊣ Sheaf_compose J F :=
adjunction.mk_of_hom_equiv
{ hom_equiv := compose_equiv J adj,
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext1, dsimp, simp },
hom_equiv_naturality_right' := λ X Y Y' f g, by { ext1, dsimp, simp } }
instance [is_right_adjoint F] : is_right_adjoint (Sheaf_compose J F) :=
⟨_, adjunction J (adjunction.of_right_adjoint F)⟩
section forget_to_type
/-- This is the functor sending a sheaf of types `X` to the sheafification of `X ⋙ G`. -/
abbreviation compose_and_sheafify_from_types (G : Type (max v u) ⥤ D) :
SheafOfTypes J ⥤ Sheaf J D :=
(Sheaf_equiv_SheafOfTypes J).inverse ⋙ compose_and_sheafify _ G
/-- A variant of the adjunction between sheaf categories, in the case where the right adjoint
is the forgetful functor to sheaves of types. -/
def adjunction_to_types {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D) :
compose_and_sheafify_from_types J G ⊣ Sheaf_forget J :=
adjunction.comp _ _ ((Sheaf_equiv_SheafOfTypes J).symm.to_adjunction) (adjunction J adj)
@[simp]
lemma adjunction_to_types_unit_app_val {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D)
(Y : SheafOfTypes J) :
((adjunction_to_types J adj).unit.app Y).val =
(adj.whisker_right _).unit.app ((SheafOfTypes_to_presheaf J).obj Y) ≫
whisker_right (J.to_sheafify _) (forget D) :=
begin
dsimp [adjunction_to_types, adjunction.comp],
simpa,
end
@[simp]
lemma adjunction_to_types_counit_app_val {G : Type (max v u) ⥤ D} (adj : G ⊣ forget D)
(X : Sheaf J D) :
((adjunction_to_types J adj).counit.app X).val =
J.sheafify_lift ((functor.associator _ _ _).hom ≫ (adj.whisker_right _).counit.app _) X.2 :=
begin
dsimp [adjunction_to_types, adjunction.comp, adjunction.whisker_right],
rw category.id_comp,
apply J.sheafify_lift_unique,
rw [adjunction_counit_app_val, J.sheafify_map_sheafify_lift, J.to_sheafify_sheafify_lift],
ext,
dsimp [Sheaf_equiv_SheafOfTypes, equivalence.symm,
equivalence.to_adjunction, nat_iso.of_components],
simp,
end
instance [is_right_adjoint (forget D)] : is_right_adjoint (Sheaf_forget J) :=
⟨_, adjunction_to_types J (adjunction.of_right_adjoint (forget D))⟩
end forget_to_type
end Sheaf
end category_theory
|
09cecf9517b38fe0a0671db73ac8635c67b9aa81 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Data.lean | 11dc7139ac98f18828f9b5cfaa9dd44578b9bae6 | [
"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 | 564 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Basic
import Init.Data.Nat
import Init.Data.Char
import Init.Data.String
import Init.Data.List
import Init.Data.Int
import Init.Data.Array
import Init.Data.ByteArray
import Init.Data.Fin
import Init.Data.UInt
import Init.Data.RBTree
import Init.Data.RBMap
import Init.Data.Option
import Init.Data.HashMap
import Init.Data.Random
import Init.Data.Queue
import Init.Data.Stack
|
f8a9d476e50aceb5414c691107ae385399976bb7 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/group/with_one.lean | a07309ad00325cf41367667e963e90c7e1c1c9f0 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 11,074 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johan Commelin
-/
import algebra.ring.basic
import data.equiv.basic
/-!
# Adjoining a zero/one to semigroups and related algebraic structures
This file contains different results about adjoining an element to an algebraic structure which then
behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That
this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`.
Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more
information about these structures (which are not that standard in informal mathematics, see
`algebra.group_with_zero.basic`)
-/
universes u v w
variable {α : Type u}
/-- Add an extra element `1` to a type -/
@[to_additive "Add an extra element `0` to a type"]
def with_one (α) := option α
namespace with_one
@[to_additive]
instance : monad with_one := option.monad
@[to_additive]
instance : has_one (with_one α) := ⟨none⟩
@[to_additive]
instance [has_mul α] : has_mul (with_one α) := ⟨option.lift_or_get (*)⟩
@[to_additive]
instance [has_inv α] : has_inv (with_one α) := ⟨λ a, option.map has_inv.inv a⟩
@[to_additive]
instance : inhabited (with_one α) := ⟨1⟩
@[to_additive]
instance [nonempty α] : nontrivial (with_one α) := option.nontrivial
@[to_additive]
instance : has_coe_t α (with_one α) := ⟨some⟩
@[to_additive]
lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl
@[simp, to_additive]
lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) :=
option.some_ne_none a
@[simp, to_additive]
lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a :=
coe_ne_one.symm
@[to_additive]
lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
@[to_additive]
instance : can_lift (with_one α) α :=
{ coe := coe,
cond := λ a, a ≠ 1,
prf := λ a, ne_one_iff_exists.1 }
@[simp, norm_cast, to_additive]
lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b :=
option.some_inj
@[elab_as_eliminator, to_additive]
protected lemma cases_on {P : with_one α → Prop} :
∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x :=
option.cases_on
-- the `show` statements in the proofs are important, because otherwise the generated lemmas
-- `with_one.mul_one_class._proof_{1,2}` have an ill-typed statement after `with_one` is made
-- irreducible.
@[to_additive]
instance [has_mul α] : mul_one_class (with_one α) :=
{ mul := (*),
one := (1),
one_mul := show ∀ x : with_one α, 1 * x = x, from (option.lift_or_get_is_left_id _).1,
mul_one := show ∀ x : with_one α, x * 1 = x, from (option.lift_or_get_is_right_id _).1 }
@[to_additive]
instance [semigroup α] : monoid (with_one α) :=
{ mul_assoc := (option.lift_or_get_assoc _).1,
..with_one.mul_one_class }
example [semigroup α] :
@monoid.to_mul_one_class _ (@with_one.monoid α _) = @with_one.mul_one_class α _ := rfl
@[to_additive]
instance [comm_semigroup α] : comm_monoid (with_one α) :=
{ mul_comm := (option.lift_or_get_comm _).1,
..with_one.monoid }
section
-- workaround: we make `with_one`/`with_zero` irreducible for this definition, otherwise `simps`
-- will unfold it in the statement of the lemma it generates.
local attribute [irreducible] with_one with_zero
/-- `coe` as a bundled morphism -/
@[to_additive "`coe` as a bundled morphism", simps apply]
def coe_mul_hom [has_mul α] : mul_hom α (with_one α) :=
{ to_fun := coe, map_mul' := λ x y, rfl }
end
section lift
variables [has_mul α] {β : Type v} [mul_one_class β]
/-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/
@[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism."]
def lift : mul_hom α β ≃ (with_one α →* β) :=
{ to_fun := λ f,
{ to_fun := λ x, option.cases_on x 1 f,
map_one' := rfl,
map_mul' := λ x y,
with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x,
with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y,
f.map_mul x y },
inv_fun := λ F, F.to_mul_hom.comp coe_mul_hom,
left_inv := λ f, mul_hom.ext $ λ x, rfl,
right_inv := λ F, monoid_hom.ext $ λ x, with_one.cases_on x F.map_one.symm $ λ x, rfl }
variables (f : mul_hom α β)
@[simp, to_additive]
lemma lift_coe (x : α) : lift f x = f x := rfl
@[simp, to_additive]
lemma lift_one : lift f 1 = 1 := rfl
@[to_additive]
theorem lift_unique (f : with_one α →* β) : f = lift (f.to_mul_hom.comp coe_mul_hom) :=
(lift.apply_symm_apply f).symm
end lift
section map
variables {β : Type v} [has_mul α] [has_mul β]
/-- Given a multiplicative map from `α → β` returns a monoid homomorphism
from `with_one α` to `with_one β` -/
@[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism
from `with_zero α` to `with_zero β`"]
def map (f : mul_hom α β) : with_one α →* with_one β :=
lift (coe_mul_hom.comp f)
@[simp, to_additive]
lemma map_id : map (mul_hom.id α) = monoid_hom.id (with_one α) :=
by { ext, cases x; refl }
@[simp, to_additive]
lemma map_comp {γ : Type w} [has_mul γ] (f : mul_hom α β) (g : mul_hom β γ) :
map (g.comp f) = (map g).comp (map f) :=
by { ext, cases x; refl }
end map
attribute [irreducible] with_one
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl
@[simp, norm_cast, to_additive]
lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_one α) = a⁻¹ := rfl
end with_one
namespace with_zero
instance [one : has_one α] : has_one (with_zero α) :=
{ ..one }
@[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl
instance [has_mul α] : mul_zero_class (with_zero α) :=
{ mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂),
zero_mul := λ a, rfl,
mul_zero := λ a, by cases a; refl,
..with_zero.has_zero }
@[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α]
{a b : α} : ((a * b : α) : with_zero α) = a * b := rfl
@[simp] lemma zero_mul {α : Type u} [has_mul α]
(a : with_zero α) : 0 * a = 0 := rfl
@[simp] lemma mul_zero {α : Type u} [has_mul α]
(a : with_zero α) : a * 0 = 0 := by cases a; refl
instance [semigroup α] : semigroup_with_zero (with_zero α) :=
{ mul_assoc := λ a b c, match a, b, c with
| none, _, _ := rfl
| some a, none, _ := rfl
| some a, some b, none := rfl
| some a, some b, some c := congr_arg some (mul_assoc _ _ _)
end,
..with_zero.mul_zero_class }
instance [comm_semigroup α] : comm_semigroup (with_zero α) :=
{ mul_comm := λ a b, match a, b with
| none, _ := (mul_zero _).symm
| some a, none := rfl
| some a, some b := congr_arg some (mul_comm _ _)
end,
..with_zero.semigroup_with_zero }
instance [mul_one_class α] : mul_zero_one_class (with_zero α) :=
{ one_mul := λ a, match a with
| none := rfl
| some a := congr_arg some $ one_mul _
end,
mul_one := λ a, match a with
| none := rfl
| some a := congr_arg some $ mul_one _
end,
..with_zero.mul_zero_class,
..with_zero.has_one }
instance [has_one α] [has_pow α ℕ] : has_pow (with_zero α) ℕ :=
⟨λ x n, match x, n with
| none, 0 := 1
| none, n + 1 := 0
| some x, n := ↑(x ^ n)
end⟩
@[simp, norm_cast] lemma coe_pow [has_one α] [has_pow α ℕ] {a : α} (n : ℕ) :
↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl
instance [monoid α] : monoid_with_zero (with_zero α) :=
{ npow := λ n x, x ^ n,
npow_zero' := λ x, match x with
| none := rfl
| some x := congr_arg some $ pow_zero _
end,
npow_succ' := λ n x, match x with
| none := rfl
| some x := congr_arg some $ pow_succ _ _
end,
.. with_zero.mul_zero_one_class,
.. with_zero.semigroup_with_zero }
instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) :=
{ ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup }
/-- Given an inverse operation on `α` there is an inverse operation
on `with_zero α` sending `0` to `0`-/
instance [has_inv α] : has_inv (with_zero α) := ⟨λ a, option.map has_inv.inv a⟩
@[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) :
((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl
@[simp] lemma inv_zero [has_inv α] :
(0 : with_zero α)⁻¹ = 0 := rfl
instance [has_div α] : has_div (with_zero α) :=
⟨λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a / b) o₂)⟩
@[norm_cast] lemma coe_div [has_div α] (a b : α) : ↑(a / b : α) = (a / b : with_zero α) := rfl
instance [has_one α] [has_pow α ℤ] : has_pow (with_zero α) ℤ :=
⟨λ x n, match x, n with
| none, int.of_nat 0 := 1
| none, int.of_nat (nat.succ n) := 0
| none, int.neg_succ_of_nat n := 0
| some x, n := ↑(x ^ n)
end⟩
@[simp, norm_cast] lemma coe_zpow [div_inv_monoid α] {a : α} (n : ℤ) :
↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl
instance [div_inv_monoid α] : div_inv_monoid (with_zero α) :=
{ div_eq_mul_inv := λ a b, match a, b with
| none, _ := rfl
| some a, none := rfl
| some a, some b := congr_arg some (div_eq_mul_inv _ _)
end,
zpow := λ n x, x ^ n,
zpow_zero' := λ x, match x with
| none := rfl
| some x := congr_arg some $ zpow_zero _
end,
zpow_succ' := λ n x, match x with
| none := rfl
| some x := congr_arg some $ div_inv_monoid.zpow_succ' _ _
end,
zpow_neg' := λ n x, match x with
| none := rfl
| some x := congr_arg some $ div_inv_monoid.zpow_neg' _ _
end,
.. with_zero.has_div,
.. with_zero.has_inv,
.. with_zero.monoid_with_zero, }
section group
variables [group α]
@[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 :=
show ((1⁻¹ : α) : with_zero α) = 1, by simp
/-- if `G` is a group then `with_zero G` is a group with zero. -/
instance : group_with_zero (with_zero α) :=
{ inv_zero := inv_zero,
mul_inv_cancel := λ a ha, by { lift a to α using ha, norm_cast, apply mul_right_inv },
.. with_zero.monoid_with_zero,
.. with_zero.div_inv_monoid,
.. with_zero.nontrivial }
end group
instance [comm_group α] : comm_group_with_zero (with_zero α) :=
{ .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero }
instance [semiring α] : semiring (with_zero α) :=
{ left_distrib := λ a b c, begin
cases a with a, {refl},
cases b with b; cases c with c; try {refl},
exact congr_arg some (left_distrib _ _ _)
end,
right_distrib := λ a b c, begin
cases c with c,
{ change (a + b) * 0 = a * 0 + b * 0, simp },
cases a with a; cases b with b; try {refl},
exact congr_arg some (right_distrib _ _ _)
end,
..with_zero.add_comm_monoid,
..with_zero.mul_zero_class,
..with_zero.monoid_with_zero }
attribute [irreducible] with_zero
end with_zero
|
32c275633f79099ea49f08b93dc2d9ade89d3abb | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/isDefEqCheckAssignmentBug.lean | 204d7291cd2cb49651dcb62302bcc4362da3e235 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 835 | lean | import Lean
open Lean
open Lean.Meta
def f (x : Type) := x
def tst : MetaM Unit := do
let m1 ← mkFreshExprMVar none
withLocalDeclD `x m1 fun x => do
trace[Meta.debug]! "{x} : {← inferType x}"
trace[Meta.debug]! "{m1} : {← inferType m1}"
let m2 ← mkFreshExprMVar (mkSort levelOne)
let t ← mkAppM ``f #[m2]
trace[Meta.debug]! "{m2} : {← inferType m2}"
unless (← fullApproxDefEq <| isDefEq m1 t) do -- m1 := f m3 -- where `m3` has a smaller scope than `m2`
throwError! "isDefEq failed"
trace[Meta.debug]! "{m2} : {← inferType m2}"
trace[Meta.debug]! "{m1} : {← inferType m1}"
let e ← mkForallFVars #[x] m2 -- `forall (x : f ?m2), ?m2`
trace[Meta.debug]! "{e} : {← e}"
return ()
set_option trace.Meta.isDefEq true
set_option trace.Meta.debug true
#eval tst
|
f0ae40d02561633b65d25c0f88983a0c7b4253cc | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world4/level4.lean | cd3591f02b7f1efec3a64f20bd54541fc5c26b5d | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 249 | lean | import game.world4.level3 -- hide
namespace mynat -- hide
/-
# Power World
## Level 4: `one_pow`
-/
/- Lemma
For all naturals $m$, $1 ^ m = 1$.
-/
lemma one_pow (m : mynat) : (1 : mynat) ^ m = 1 :=
begin [nat_num_game]
end
end mynat -- hide
|
6a0717c0bf77d73203e83c07907375aa62fe0938 | e898bfefd5cb60a60220830c5eba68cab8d02c79 | /uexp/src/uexp/rules/pullFilterThroughAggregate.lean | f60084a5a3c0b16e5561e19a8c62a98f0222cc0c | [
"BSD-2-Clause"
] | permissive | kkpapa/Cosette | 9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce | fda8fdbbf0de6c1be9b4104b87bbb06cede46329 | refs/heads/master | 1,584,573,128,049 | 1,526,370,422,000 | 1,526,370,422,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,157 | lean |
import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..cosette_tactics
open Expr
open Proj
open Pred
open SQL
open tree
notation `int` := datatypes.int
constant integer_5000: const int
theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp),
denoteSQL
((DISTINCT
(SELECT1 (combine (right⋅left) (combine (right⋅right⋅left) (right⋅right⋅right)))
(FROM1 ((SELECT1 (combine (right⋅emp_ename) (combine (right⋅emp_sal) (right⋅emp_deptno))) FROM1 (table rel_emp)))
WHERE (castPred (combine (right⋅right⋅left) (e2p (constantExpr integer_5000)) ) predicates.gt)))) : SQL Γ _) =
denoteSQL ((SELECT1 (combine (right⋅left) (combine (right⋅right⋅left) (right⋅right⋅right))) FROM1 (DISTINCT (SELECT1 (combine (right⋅emp_ename) (combine (right⋅emp_sal) (right⋅emp_deptno))) FROM1 (table rel_emp) )) WHERE (castPred (combine (right⋅right⋅left) (e2p (constantExpr integer_5000)) ) predicates.gt)) : SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
print_size,
simp,
print_size,
sorry
end |
b196f695d2a1bc1087c0778580ac1636fce9cbda | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/metric_space/gromov_hausdorff.lean | f3d546bb9f5dcbd9de2fc6c6c4ca1d63ced75275 | [
"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 | 55,932 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import set_theory.cardinal.basic
import topology.metric_space.closeds
import topology.metric_space.completion
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.kuratowski
/-!
# Gromov-Hausdorff distance
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topology ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat int Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private def isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λ x y, nonempty (x ≃ᵢ y)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λ x, ⟨isometry_equiv.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding X⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨⟨{0}, is_compact_singleton⟩, singleton_nonempty _⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
@[nolint has_nonempty_instance]
def GH_space.rep (p : GH_space) : Type := (quotient.out p : nonempty_compacts ℓ_infty_ℝ)
lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p :=
begin
simp only [to_GH_space, quotient.eq],
refine ⟨λ h, _, _⟩,
{ rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range.trans e,
use [λ x, f x, isometry_subtype_coe.comp f.isometry],
rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe],
refl },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry X).isometry_equiv_on_range.symm.trans
isomΨ.isometry_equiv_on_range).symm,
have E : (range Ψ ≃ᵢ nonempty_compacts.Kuratowski_embedding X) =
(p ≃ᵢ range (Kuratowski_embedding X)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
exact ⟨cast E f⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p :=
eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space p.rep := by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space p.rep := by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty p.rep := by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space p.rep = p :=
begin
change to_GH_space (quot.out p : nonempty_compacts ℓ_infty_ℝ) = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are
isometric. -/
lemma to_GH_space_eq_to_GH_space_iff_isometry_equiv {X : Type u} [metric_space X] [compact_space X]
[nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) :=
⟨begin
simp only [to_GH_space, quotient.eq],
rintro ⟨e⟩,
have I : ((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y))
= ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range,
have g := (Kuratowski_embedding.isometry Y).isometry_equiv_on_range.symm,
exact ⟨f.trans $ (cast I e).trans g⟩
end,
begin
rintro ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range.symm,
have g := (Kuratowski_embedding.isometry Y).isometry_equiv_on_range,
have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) =
((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y)),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
exact ⟨cast I ((f.trans e).trans g)⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λ x y, Inf $
(λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ,
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X]
[metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist p.rep (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
{γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λ x y, ha x y,
have IΨ' : isometry Ψ' := λ x y, hb x y,
have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xX⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_coe) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) =
Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Φ'), (is_compact_range IΦ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Ψ'), (is_compact_range IΨ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
have AX : ⟦A⟧ = to_GH_space X,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Φ' x), (Kuratowski_embedding.isometry _).comp IΦ', range_comp _ _⟩ },
have BY : ⟦B⟧ = to_GH_space Y,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Ψ' x), (Kuratowski_embedding.isometry _).comp IΨ', range_comp _ _⟩ },
refine cInf_le ⟨0, _⟩ _,
{ simp only [lower_bounds, mem_image, mem_prod, mem_set_of_eq, prod.exists, and_imp,
forall_exists_index],
assume t _ _ _ _ ht,
rw ← ht,
exact Hausdorff_dist_nonneg },
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [AX, BY],
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y :=
begin
inhabit X, inhabit Y,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y) →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y),
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y),
{ rw Ψrange,
have : Φ xX ∈ ↑p := Φrange.subst (mem_range_self _),
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) +
diam (univ : set Y) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl }
... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring },
let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates X Y,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λ x y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λ x y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λ x y, dist_comm _ _ },
{ exact λ x y z, dist_triangle _ _ _ },
{ exact λ x y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p ⊔ q).is_compact.bounded,
end
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)),
have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ ↑p := Φrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ ↑q := Ψrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp only [HD, csupr_le I1, csupr_le I2, max_le_iff, and_self] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq,
by_cases h :
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y))
≤ HD (candidates_b_dist X Y) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X]
(Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] :
∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling X Y),
let Φ := F ∘ optimal_GH_injl X Y,
let Ψ := F ∘ optimal_GH_injr X Y,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance : metric_space GH_space :=
{ dist := dist,
dist_self := λ x, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp only [mem_image, mem_prod, mem_set_of_eq, prod.exists],
existsi [y, y],
simpa only [and_self, Hausdorff_dist_self_zero, eq_self_iff_true, and_true]} },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λ x y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ∘ prod.swap) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}),
{ congr, funext, simp only [comp_app, prod.fst_swap, prod.snd_swap], rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, image_swap_prod],
end,
eq_of_dist_eq_zero := λ x y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous,
apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometry_equiv_on_range.symm,
have e := Φisom.isometry_equiv_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometry_equiv],
exact ⟨e⟩
end,
dist_triangle := λ x y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space
`γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) =
(to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X]
(p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {X : Type u} [metric_space X]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (coe : p → X) := isometry_subtype_coe,
have hb : isometry (coe : q → X) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist (p : set X) q := rfl,
have I : ↑p = range (coe : p → X) := subtype.range_coe_subtype.symm,
have J : ↑q = range (coe : q → X) := subtype.range_coe_subtype.symm,
rw [A, I, J],
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff
distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable
coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃)
(H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) :
GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine le_of_forall_pos_le_add (λ δ δ0, _),
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
rcases hs xX with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc
|dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `X` and `Y` along the almost matching subsets
letI : metric_space (X ⊕ Y) :=
glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl X Y,
let Fr := @sum.inr X Y,
have Il : isometry Fl := isometry.of_dist_eq (λ x y, rfl),
have Ir : isometry Fr := isometry.of_dist_eq (λ x y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images
in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff
distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and
`Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first
term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is
bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by
construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive
constant where positivity is used to ensure that the coupling is really a metric space and not a
premetric space on `X ⊕ Y`). -/
have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.mono (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x)
(λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty Y with ⟨xY, _⟩,
rcases hs' xY with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩)
(λ x _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λ δ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀ p:GH_space, ∃ s : set p.rep, s.finite ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λ p, by simpa only [subset_univ, exists_true_left]
using finite_cover_balls_of_compact is_compact_univ εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀ p:GH_space, ∀ t:set p.rep, t.finite → ∃ n:ℕ, ∃ e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λ p:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λ p:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋⟩,
refine ⟨Σ n, fin n → fin n → ℤ, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
{ rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y,
{ simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1,
{ simp only [equiv.apply_symm_apply, fin.val_eq_coe, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply fin.ext_iff.2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply fin.ext_iff.2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp only [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p),
cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n le_rfl,
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀ p:GH_space, ∃ s : set p.rep, ∃ N ≤ K n, ∃ E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set p.rep) (fin 0)),
{ rw ← fintype.card_eq, simp only [empty_card', fintype.card_fin] },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_aleph_0.1 (lt_of_le_of_lt scard (cardinal.nat_lt_aleph_0 _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp only [scover, implies_true_iff] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := ⌊ε⁻¹ * max C 0⌋₊,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λ a b, ⟨min M ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋₊,
( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, _, (λ p, F p), _⟩, apply_instance,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := fin.ext_iff.1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
have main : GH_dist p.rep (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊ε⁻¹ * dist x y⌋₊ := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply fin.ext_iff.2; refl }
... = min M ⌊ε⁻¹ * dist x y⌋₊ :
by simp only [F, (E p).symm_apply_apply]
... = ⌊ε⁻¹ * dist x y⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply fin.ext_iff.2; [exact i', exact j'] }
... = min M ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
by simp only [F, (E q).symm_apply_apply]
... = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : ⌊ε⁻¹ * dist x y⌋ = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋,
{ rw [Ap, Aq] at this,
have D : 0 ≤ ⌊ε⁻¹ * dist x y⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : 0 ≤ ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat,
this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp only [ε, one_div], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
local attribute [instance] aux_gluing_struct.metric
instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) :=
⟨{ space := A,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }⟩
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) :=
nat.rec_on n default $ λ n Y,
{ space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))),
metric := by apply_instance,
embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))))
∘ (optimal_GH_injr (X n) (X (n+1))),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) }
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space GH_space :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _),
-- `X n` is a representative of `u n`
let X := λ n, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
-- this equality is true by definition but Lean unfolds some defs in the wrong order
have E : ∀ n : ℕ,
glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X (n + 1))) = (Y (n + 1)).space :=
λ n, by { dsimp only [Y, aux_gluing], refl },
let c := λ n, cast (E n),
have ic : ∀ n, isometry (c n) := λ n x y, by { dsimp only [Y, aux_gluing], exact rfl },
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Π n, (Y n).space → (Y (n + 1)).space :=
λ n, c n ∘ to_glue_l (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)),
have I : ∀ n, isometry (f n) := λ n, (ic n).comp (to_glue_l_isometry _ _),
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
refine uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp (Y n).isom },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp ((ic n).comp (to_glue_r_isometry _ _)) } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λ n,
⟨⟨X2 n, is_compact_range (isom n).continuous⟩, range_nonempty _⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀ n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometry_equiv],
constructor,
convert (isom n).isometry_equiv_on_range.symm, },
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa only [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
dd5a775a4af2b03719cd80fbed11f76d58526093 | 3ed5a65c1ab3ce5d1a094edce8fa3287980f197b | /src/herstein/ex2_5/Q_01.lean | ce7e4291ab936b46e83b600a0ef7115a4d5e2a23 | [] | no_license | group-study-group/herstein | 35d32e77158efa2cc303c84e1ee5e3bc80831137 | f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66 | refs/heads/master | 1,586,202,191,519 | 1,548,969,759,000 | 1,548,969,759,000 | 157,746,953 | 0 | 0 | null | 1,542,412,901,000 | 1,542,302,366,000 | Lean | UTF-8 | Lean | false | false | 424 | lean | import algebra.group
import group_theory.subgroup
variables {G: Type*} {H K: set G}
theorem Q_01 [hG: group G] [hH: is_subgroup H] [hK: is_subgroup K]:
is_subgroup (H ∩ K) := {
inv_mem := λ a ha, ⟨
is_subgroup.inv_mem ha.1,
is_subgroup.inv_mem ha.2
⟩,
one_mem := ⟨hH.one_mem, hK.one_mem⟩,
mul_mem := λ a b ha hb, ⟨
is_submonoid.mul_mem ha.1 hb.1,
is_submonoid.mul_mem ha.2 hb.2,
⟩
}
|
69535d2965c24d4b8d969209e006cf5228523538 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/rw_instantiate_mvars.lean | c7682921463735995e49799b65e57411f2f9b6ac | [
"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 | 82 | lean | example (n : ℕ) (h : n + n ≠ 0) : n ≠ 0 :=
by refine mt (λ hz, _) h; rw hz
|
6a945dd1b6710bcec3d1d18e2726122781e9babe | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/hints/thursday/afternoon/category_theory/exercise6/hint2.lean | a46605a37a59cc12a597beb13e99d0d0843ecb85 | [] | 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,286 | 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.
-/
universes v u
variables {C : Type u} [category.{v} 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.
begin
fapply pushout_cocone.is_colimit.mk,
{ intro s,
apply s.ι.app walking_span.left, },
{ tidy, },
{ tidy, /- we clearly need to use that `f` is an epi here!-/ sorry },
{ tidy, }
end
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 :=
{ left_cancellation := λ Z g h hf,
begin
let a := pushout_cocone.mk _ _ hf,
have hg : is_colim.desc a = g, sorry,
have hh : is_colim.desc a = h, sorry,
rw [←hg, ←hh],
end }
|
8d1140e6b3d5b056886c1d4b7a4add54cbbd7162 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/measure_theory/l1_space.lean | 4ab2d55682a19241407bc649d1d675a5c109b184 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,333 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import measure_theory.lp_space
/-!
# Integrable functions and `L¹` space
In the first part of this file, the predicate `integrable` is defined and basic properties of
integrable functions are proved.
Such a predicate is already available under the name `mem_ℒp 1`. We give a direct definition which
is easier to use, and show that it is equivalent to `mem_ℒp 1`
In the second part, we establish an API between `integrable` and the space `L¹` of equivalence
classes of integrable functions, already defined as a special case of `L^p` spaces for `p = 1`.
## Notation
* `α →₁[μ] β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group`
with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is
also used to denote an `L¹` function.
`₁` can be typed as `\1`.
## Main definitions
* Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`.
Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ∞`.
* If `β` is moreover a `measurable_space` then `f` is called `integrable` if
`f` is `measurable` and `has_finite_integral f` holds.
## Implementation notes
To prove something for an arbitrary integrable function, a useful theorem is
`integrable.induction` in the file `set_integral`.
## Tags
integrable, function space, l1
-/
noncomputable theory
open_locale classical topological_space big_operators ennreal measure_theory
open set filter topological_space ennreal emetric measure_theory
variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α}
variables [normed_group β]
variables [normed_group γ]
namespace measure_theory
/-! ### Some results about the Lebesgue integral involving a normed group -/
lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) :
∫⁻ a, nnnorm (f a) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [edist_eq_coe_nnnorm]
lemma lintegral_norm_eq_lintegral_edist (f : α → β) :
∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm]
lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β]
[opens_measurable_space β] {f g h : α → β}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) (hh : ae_measurable h μ) :
∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ :=
begin
rw ← lintegral_add' (hf.edist hh) (hg.edist hh),
refine lintegral_mono (λ a, _),
apply edist_triangle_right
end
lemma lintegral_nnnorm_zero : ∫⁻ a : α, nnnorm (0 : β) ∂μ = 0 := by simp
lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β]
[measurable_space γ] [opens_measurable_space γ]
{f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ + ∫⁻ a, nnnorm (g a) ∂μ :=
lintegral_add' hf.ennnorm hg.ennnorm
lemma lintegral_nnnorm_neg {f : α → β} :
∫⁻ a, nnnorm ((-f) a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ :=
by simp only [pi.neg_apply, nnnorm_neg]
/-! ### The predicate `has_finite_integral` -/
/-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite.
`has_finite_integral f` means `has_finite_integral f volume`. -/
def has_finite_integral (f : α → β) (μ : measure α . volume_tac) : Prop :=
∫⁻ a, nnnorm (f a) ∂μ < ∞
lemma has_finite_integral_iff_norm (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ∞ :=
by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm]
lemma has_finite_integral_iff_edist (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ∞ :=
by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right]
lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) :
has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ∞ :=
have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ :=
begin
refine lintegral_congr_ae (h.mono $ λ a h, _),
rwa [real.norm_eq_abs, abs_of_nonneg]
end,
by rw [has_finite_integral_iff_norm, lintegral_eq]
lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ :=
begin
simp only [has_finite_integral_iff_norm] at *,
calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ :
lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h)
... < ∞ : hg
end
lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ :=
hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _)
lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
has_finite_integral g μ :=
hf.mono $ eventually_eq.le $ eventually_eq.symm h
lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩
lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) :
has_finite_integral g μ :=
hf.congr' $ h.fun_comp norm
lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
has_finite_integral_congr' $ h.fun_comp norm
lemma has_finite_integral_const_iff {c : β} :
has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
begin
simp only [has_finite_integral, lintegral_const],
by_cases hc : c = 0,
{ simp [hc] },
{ simp only [hc, false_or],
refine ⟨λ h, _, λ h, mul_lt_top coe_lt_top h⟩,
replace h := mul_lt_top (@coe_lt_top $ (nnnorm c)⁻¹) h,
rwa [← mul_assoc, ← coe_mul, _root_.inv_mul_cancel, coe_one, one_mul] at h,
rwa [ne.def, nnnorm_eq_zero] }
end
lemma has_finite_integral_const [finite_measure μ] (c : β) : has_finite_integral (λ x : α, c) μ :=
has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _)
lemma has_finite_integral_of_bounded [finite_measure μ] {f : α → β} {C : ℝ}
(hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ :=
(has_finite_integral_const C).mono' hC
lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) :
has_finite_integral f μ :=
lt_of_le_of_lt (lintegral_mono' hμ (le_refl _)) h
lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ)
(hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) :=
begin
simp only [has_finite_integral, lintegral_add_measure] at *,
exact add_lt_top.2 ⟨hμ, hν⟩
end
lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f μ :=
h.mono_measure $ measure.le_add_right $ le_refl _
lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f ν :=
h.mono_measure $ measure.le_add_left $ le_refl _
@[simp] lemma has_finite_integral_add_measure {f : α → β} :
has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ℝ≥0∞}
(hc : c < ∞) : has_finite_integral f (c • μ) :=
begin
simp only [has_finite_integral, lintegral_smul_measure] at *,
exact mul_lt_top hc h
end
@[simp] lemma has_finite_integral_zero_measure (f : α → β) : has_finite_integral f 0 :=
by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top]
variables (α β μ)
@[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ :=
by simp [has_finite_integral]
variables {α β μ}
lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (-f) μ :=
by simpa [has_finite_integral] using hfi
@[simp] lemma has_finite_integral_neg_iff {f : α → β} :
has_finite_integral (-f) μ ↔ has_finite_integral f μ :=
⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩
lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (λa, ∥f a∥) μ :=
have eq : (λa, (nnnorm ∥f a∥ : ℝ≥0∞)) = λa, (nnnorm (f a) : ℝ≥0∞),
by { funext, rw nnnorm_norm },
by { rwa [has_finite_integral, eq] }
lemma has_finite_integral_norm_iff (f : α → β) :
has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ :=
has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x)
section dominated_convergence
variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) :
∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) :=
λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h
lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) :
∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ :=
h.mono $
λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h
lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) :=
begin
have F_le_bound := all_ae_of_real_F_le_bound h_bound,
rw ← ae_all_iff at F_le_bound,
apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _),
assume a tendsto_norm F_le_bound,
exact le_of_tendsto' tendsto_norm (F_le_bound)
end
lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(bound_has_finite_integral : has_finite_integral bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
has_finite_integral f μ :=
/- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`,
and so `∫ ∥f∥ ≤ ∫ bound < ∞` since `bound` is has_finite_integral -/
begin
rw has_finite_integral_iff_norm,
calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ :
lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim
... < ∞ :
begin
rw ← has_finite_integral_iff_of_real,
{ exact bound_has_finite_integral },
exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h)
end
end
lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β]
[borel_space β] [second_countable_topology β]
{F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(F_measurable : ∀ n, ae_measurable (F n) μ)
(f_measurable : ae_measurable f μ)
(bound_has_finite_integral : has_finite_integral bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) :=
let b := λa, 2 * ennreal.of_real (bound a) in
/- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the
triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/
have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a,
begin
assume n,
filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim],
assume a h₁ h₂,
calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) :
begin
rw [← ennreal.of_real_add],
apply of_real_le_of_real,
{ apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ }
end
... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂
... = b a : by rw ← two_mul
end,
/- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/
have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0),
begin
rw ← ennreal.of_real_zero,
refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _),
rwa ← tendsto_iff_norm_tendsto_zero
end,
/- Therefore, by the dominated convergence theorem for nonnegative integration, have
` ∫ ∥f a - F n a∥ --> 0 ` -/
begin
suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)),
{ rwa lintegral_zero at h },
-- Using the dominated convergence theorem.
refine tendsto_lintegral_of_dominated_convergence' _ _ hb _ _,
-- Show `λa, ∥f a - F n a∥` is almost everywhere measurable for all `n`
{ exact λn, measurable_of_real.comp_ae_measurable ((F_measurable n).sub f_measurable).norm },
-- Show `2 * bound` is has_finite_integral
{ rw has_finite_integral_iff_of_real at bound_has_finite_integral,
{ calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ :
by { rw lintegral_const_mul', exact coe_ne_top }
... < ∞ : mul_lt_top (coe_lt_top) bound_has_finite_integral },
filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h },
-- Show `∥f a - F n a∥ --> 0`
{ exact h }
end
end dominated_convergence
section pos_part
/-! Lemmas used for defining the positive part of a `L¹` function -/
lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, max (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, le_abs_self]
lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, min (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x,
by simp [real.norm_eq_abs, abs_le, abs_nonneg, neg_le, neg_le_abs_self]
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ →
has_finite_integral (c • f) μ :=
begin
simp only [has_finite_integral], assume hfi,
calc
∫⁻ (a : α), nnnorm (c • f a) ∂μ = ∫⁻ (a : α), (nnnorm c) * nnnorm (f a) ∂μ :
by simp only [nnnorm_smul, ennreal.coe_mul]
... < ∞ :
begin
rw lintegral_const_mul',
exacts [mul_lt_top coe_lt_top hfi, coe_ne_top]
end
end
lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
has_finite_integral (c • f) μ ↔ has_finite_integral f μ :=
begin
split,
{ assume h,
simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ },
exact has_finite_integral.smul _
end
lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, c * f x) μ :=
(has_finite_integral.smul c h : _)
lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
end normed_space
/-! ### The predicate `integrable` -/
variables [measurable_space β] [measurable_space γ] [measurable_space δ]
/-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite.
`integrable f` means `integrable f volume`. -/
def integrable (f : α → β) (μ : measure α . volume_tac) : Prop :=
ae_measurable f μ ∧ has_finite_integral f μ
lemma integrable.ae_measurable {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.1
lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ :=
hf.2
lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : ae_measurable f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ :=
⟨hf, hg.has_finite_integral.mono h⟩
lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : ae_measurable f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ :=
⟨hf, hg.has_finite_integral.mono' h⟩
lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : ae_measurable g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ :=
⟨hg, hf.has_finite_integral.congr' h⟩
lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ :=
⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩
lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) :
integrable g μ :=
⟨hf.1.congr h, hf.2.congr h⟩
lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) :
integrable f μ ↔ integrable g μ :=
⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩
lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
begin
have : ae_measurable (λ (x : α), c) μ := measurable_const.ae_measurable,
rw [integrable, and_iff_right this, has_finite_integral_const_iff]
end
lemma integrable_const [finite_measure μ] (c : β) : integrable (λ x : α, c) μ :=
integrable_const_iff.2 $ or.inr $ measure_lt_top _ _
lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ :=
⟨h.ae_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩
lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) :
integrable f (μ + ν) :=
⟨hμ.ae_measurable.add_measure hν.ae_measurable,
hμ.has_finite_integral.add_measure hν.has_finite_integral⟩
lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ :=
h.mono_measure $ measure.le_add_right $ le_refl _
lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν :=
h.mono_measure $ measure.le_add_left $ le_refl _
@[simp] lemma integrable_add_measure {f : α → β} :
integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c < ∞) :
integrable f (c • μ) :=
⟨h.ae_measurable.smul_measure c, h.has_finite_integral.smul_measure hc⟩
lemma integrable_map_measure [opens_measurable_space β] {f : α → δ} {g : δ → β}
(hg : ae_measurable g (measure.map f μ)) (hf : measurable f) :
integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ :=
by simp [integrable, hg, hg.comp_measurable hf, has_finite_integral, lintegral_map' hg.ennnorm hf]
lemma lintegral_edist_lt_top [second_countable_topology β] [opens_measurable_space β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) :
∫⁻ a, edist (f a) (g a) ∂μ < ∞ :=
lt_of_le_of_lt
(lintegral_edist_triangle hf.ae_measurable hg.ae_measurable
(measurable_const.ae_measurable : ae_measurable (λa, (0 : β)) μ))
(ennreal.add_lt_top.2 $ by { simp_rw ← has_finite_integral_iff_edist,
exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ })
variables (α β μ)
@[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ :=
by simp [integrable, measurable_const.ae_measurable]
variables {α β μ}
lemma integrable.add' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ)
(hg : integrable g μ) :
has_finite_integral (f + g) μ :=
calc ∫⁻ a, nnnorm (f a + g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ :
lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _)
... = _ : lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable
... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩
lemma integrable.add [borel_space β] [second_countable_topology β]
{f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ :=
⟨hf.ae_measurable.add hg.ae_measurable, hf.add' hg⟩
lemma integrable_finset_sum {ι} [borel_space β] [second_countable_topology β] (s : finset ι)
{f : ι → α → β} (hf : ∀ i, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ :=
begin
refine finset.induction_on s _ _,
{ simp only [finset.sum_empty, integrable_zero] },
{ assume i s his ih, simp only [his, finset.sum_insert, not_false_iff],
exact (hf _).add ih }
end
lemma integrable.neg [borel_space β] {f : α → β} (hf : integrable f μ) : integrable (-f) μ :=
⟨hf.ae_measurable.neg, hf.has_finite_integral.neg⟩
@[simp] lemma integrable_neg_iff [borel_space β] {f : α → β} : integrable (-f) μ ↔ integrable f μ :=
⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩
lemma integrable.sub' [opens_measurable_space β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ :=
calc ∫⁻ a, nnnorm (f a - g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (-g a) ∂μ :
lintegral_mono (assume a, by { simp only [sub_eq_add_neg], exact_mod_cast nnnorm_add_le _ _ } )
... = _ :
by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable }
... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩
lemma integrable.sub [borel_space β] [second_countable_topology β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma integrable.norm [opens_measurable_space β] {f : α → β} (hf : integrable f μ) :
integrable (λa, ∥f a∥) μ :=
⟨hf.ae_measurable.norm, hf.has_finite_integral.norm⟩
lemma integrable_norm_iff [opens_measurable_space β] {f : α → β} (hf : ae_measurable f μ) :
integrable (λa, ∥f a∥) μ ↔ integrable f μ :=
by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff]
lemma integrable_of_norm_sub_le [opens_measurable_space β] {f₀ f₁ : α → β} {g : α → ℝ}
(hf₁_m : ae_measurable f₁ μ)
(hf₀_i : integrable f₀ μ)
(hg_i : integrable g μ)
(h : ∀ᵐ a ∂μ, ∥f₀ a - f₁ a∥ ≤ g a) :
integrable f₁ μ :=
begin
have : ∀ᵐ a ∂μ, ∥f₁ a∥ ≤ ∥f₀ a∥ + g a,
{ apply h.mono,
intros a ha,
calc ∥f₁ a∥ ≤ ∥f₀ a∥ + ∥f₀ a - f₁ a∥ : norm_le_insert _ _
... ≤ ∥f₀ a∥ + g a : add_le_add_left ha _ },
exact integrable.mono' (hf₀_i.norm.add hg_i) hf₁_m this
end
lemma integrable.prod_mk [opens_measurable_space β] [opens_measurable_space γ] {f : α → β}
{g : α → γ} (hf : integrable f μ) (hg : integrable g μ) :
integrable (λ x, (f x, g x)) μ :=
⟨hf.ae_measurable.prod_mk hg.ae_measurable,
(hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x,
calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _)
... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩
lemma mem_ℒp_one_iff_integrable {f : α → β} : mem_ℒp f 1 μ ↔ integrable f μ :=
by simp_rw [integrable, has_finite_integral, mem_ℒp,
snorm_eq_snorm' one_ne_zero ennreal.one_ne_top, ennreal.one_to_real, snorm', one_div_one,
ennreal.rpow_one]
lemma mem_ℒp.integrable [borel_space β] {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [finite_measure μ]
(hfq : mem_ℒp f q μ) : integrable f μ :=
mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1)
lemma lipschitz_with.integrable_comp_iff_of_antilipschitz [complete_space β] [borel_space β]
[borel_space γ] {K K'} {f : α → β} {g : β → γ} (hg : lipschitz_with K g)
(hg' : antilipschitz_with K' g) (g0 : g 0 = 0) :
integrable (g ∘ f) μ ↔ integrable f μ :=
by simp [← mem_ℒp_one_iff_integrable, hg.mem_ℒp_comp_iff_of_antilipschitz hg' g0]
section pos_part
/-! ### Lemmas used for defining the positive part of a `L¹` function -/
lemma integrable.max_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, max (f a) 0) μ :=
⟨hf.ae_measurable.max measurable_const.ae_measurable, hf.has_finite_integral.max_zero⟩
lemma integrable.min_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, min (f a) 0) μ :=
⟨hf.ae_measurable.min measurable_const.ae_measurable, hf.has_finite_integral.min_zero⟩
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma integrable.smul [borel_space β] (c : 𝕜) {f : α → β}
(hf : integrable f μ) : integrable (c • f) μ :=
⟨hf.ae_measurable.const_smul c, hf.has_finite_integral.smul c⟩
lemma integrable_smul_iff [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
integrable (c • f) μ ↔ integrable f μ :=
and_congr (ae_measurable_const_smul_iff' hc) (has_finite_integral_smul_iff hc f)
lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, c * f x) μ :=
integrable.smul c h
lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
end normed_space
section normed_space_over_complete_field
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 integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) :
integrable (λ x, f x • c) μ ↔ integrable f μ :=
begin
simp_rw [integrable, ae_measurable_smul_const hc, and.congr_right_iff, has_finite_integral,
nnnorm_smul, ennreal.coe_mul],
intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff],
have : ∀ x : ℝ≥0∞, x = 0 → x < ∞ := by simp,
simp [hc, or_iff_left_of_imp (this _)]
end
end normed_space_over_complete_field
/-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/
namespace ae_eq_fun
section
/-- A class of almost everywhere equal functions is `integrable` if its function representative
is integrable. -/
def integrable (f : α →ₘ[μ] β) : Prop := integrable f μ
lemma integrable_mk {f : α → β} (hf : ae_measurable f μ ) :
(integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ :=
begin
simp [integrable],
apply integrable_congr,
exact coe_fn_mk f hf
end
lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f :=
by rw [← integrable_mk, mk_coe_fn]
lemma integrable_zero : integrable (0 : α →ₘ[μ] β) :=
(integrable_zero α β μ).congr (coe_fn_mk _ _).symm
end
section
variables [borel_space β]
lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg
section
variable [second_countable_topology β]
lemma integrable_iff_mem_L1 {f : α →ₘ[μ] β} : integrable f ↔ f ∈ (α →₁[μ] β) :=
by rw [← integrable_coe_fn, ← mem_ℒp_one_iff_integrable, Lp.mem_Lp_iff_mem_ℒp]
lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) :=
begin
refine induction_on₂ f g (λ f hf g hg hfi hgi, _),
simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢,
exact hfi.add hgi
end
lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) :
integrable (f - g) :=
(sub_eq_add_neg f g).symm ▸ hf.add hg.neg
end
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _
end normed_space
end
end ae_eq_fun
namespace L1
variables [second_countable_topology β] [borel_space β]
lemma integrable_coe_fn (f : α →₁[μ] β) :
integrable f μ :=
by { rw ← mem_ℒp_one_iff_integrable, exact Lp.mem_ℒp f }
lemma has_finite_integral_coe_fn (f : α →₁[μ] β) :
has_finite_integral f μ :=
(integrable_coe_fn f).has_finite_integral
lemma measurable_coe_fn (f : α →₁[μ] β) :
measurable f := Lp.measurable f
lemma ae_measurable_coe_fn (f : α →₁[μ] β) :
ae_measurable f μ := Lp.ae_measurable f
lemma edist_def (f g : α →₁[μ] β) :
edist f g = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [Lp.edist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma dist_def (f g : α →₁[μ] β) :
dist f g = (∫⁻ a, edist (f a) (g a) ∂μ).to_real :=
by { simp [Lp.dist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma norm_def (f : α →₁[μ] β) :
∥f∥ = (∫⁻ a, nnnorm (f a) ∂μ).to_real :=
by { simp [Lp.norm_def, snorm, snorm'] }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `norm_def` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) :
∥f - g∥ = (∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ).to_real :=
begin
rw [norm_def],
congr' 1,
rw lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g],
assume a ha,
simp only [ha, pi.sub_apply],
end
lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) :
ennreal.of_real ∥f∥ = ∫⁻ x, (nnnorm (f x) : ℝ≥0∞) ∂μ :=
by { rw [norm_def, ennreal.of_real_to_real], rw [← ennreal.lt_top_iff_ne_top],
exact has_finite_integral_coe_fn f }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) :
ennreal.of_real ∥f - g∥ = ∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ :=
begin
simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm],
apply lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g],
assume a ha,
simp only [ha, pi.sub_apply],
end
end L1
namespace integrable
variables [second_countable_topology β] [borel_space β]
/-- Construct the equivalence class `[f]` of an integrable function `f`, as a member of the
space `L1 β 1 μ`. -/
def to_L1 (f : α → β) (hf : integrable f μ) : α →₁[μ] β :=
(mem_ℒp_one_iff_integrable.2 hf).to_Lp f
@[simp] lemma to_L1_coe_fn (f : α →₁[μ] β) (hf : integrable f μ) : hf.to_L1 f = f :=
by simp [integrable.to_L1]
lemma coe_fn_to_L1 {f : α → β} (hf : integrable f μ) : hf.to_L1 f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_L1_zero (h : integrable (0 : α → β) μ) : h.to_L1 0 = 0 := rfl
@[simp] lemma to_L1_eq_mk (f : α → β) (hf : integrable f μ) :
(hf.to_L1 f : α →ₘ[μ] β) = ae_eq_fun.mk f hf.ae_measurable :=
rfl
@[simp] lemma to_L1_eq_to_L1_iff (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 f hf = to_L1 g hg ↔ f =ᵐ[μ] g :=
mem_ℒp.to_Lp_eq_to_Lp_iff _ _
lemma to_L1_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl
lemma to_L1_neg (f : α → β) (hf : integrable f μ) :
to_L1 (- f) (integrable.neg hf) = - to_L1 f hf := rfl
lemma to_L1_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := rfl
lemma norm_to_L1 (f : α → β) (hf : integrable f μ) :
∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) :=
by { simp [to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
lemma norm_to_L1_eq_lintegral_norm (f : α → β) (hf : integrable f μ) :
∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) :=
by { rw [norm_to_L1, lintegral_norm_eq_lintegral_edist] }
@[simp] lemma edist_to_L1_to_L1 (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
edist (hf.to_L1 f) (hg.to_L1 g) = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
@[simp] lemma edist_to_L1_zero (f : α → β) (hf : integrable f μ) :
edist (hf.to_L1 f) 0 = ∫⁻ a, edist (f a) 0 ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) :
to_L1 (λa, k • f a) (hf.smul k) = k • to_L1 f hf := rfl
end integrable
end measure_theory
open measure_theory
lemma integrable_zero_measure [measurable_space β] {f : α → β} :
integrable f 0 :=
begin
apply (integrable_zero _ _ _).congr,
change (0 : measure α) {x | 0 ≠ f x} = 0,
refl,
end
variables {E : Type*} [normed_group E] [measurable_space E] [borel_space E] [normed_space ℝ E]
{H : Type*} [normed_group H] [normed_space ℝ H]
lemma measure_theory.integrable.apply_continuous_linear_map {φ : α → H →L[ℝ] E}
(φ_int : integrable φ μ) (v : H) : integrable (λ a, φ a v) μ :=
(φ_int.norm.mul_const ∥v∥).mono' (φ_int.ae_measurable.apply_continuous_linear_map v)
(eventually_of_forall $ λ a, (φ a).le_op_norm v)
|
b37cc327c6addbae2df1fc33f04f78d13fbbf83b | 2d787ac9a5ab28a7d164cd13cee8a3cdc1e4680a | /src/my_exercises/09_limits_final.lean | 0ab0b07e6f93857929c5cdc3e71e6f58831eb6ca | [
"Apache-2.0"
] | permissive | paulzfm/lean3-tutorials | 8c113ec2c9494d401c8a877f094db93e5a631fd6 | f41baf1c62c251976ec8dd9ccae9e85ec4c4d336 | refs/heads/master | 1,679,267,488,532 | 1,614,782,461,000 | 1,614,782,461,000 | 344,157,026 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,626 | lean | import tuto_lib
set_option pp.beta true
set_option pp.coercions false
/-
This is the final file in the series. Here we use everything covered
in previous files to prove a couple of famous theorems from
elementary real analysis. Of course they all have more general versions
in mathlib.
As usual, keep in mind the following:
abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y
ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q
le_max_left p q : p ≤ max p q
le_max_right p q : q ≤ max p q
as well as a lemma from the previous file:
le_of_le_add_all : (∀ ε > 0, y ≤ x + ε) → y ≤ x
Let's start with a variation on a known exercise.
-/
-- 0071
lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x)
(ineg : ∃ N, ∀ n ≥ N, y ≤ u n) : y ≤ x :=
begin
apply le_of_le_add_all,
intros ε hε,
cases hu ε hε with N hN,
cases ineg with N' hN',
specialize hN (max N N') (by apply le_max_left),
rw abs_le at hN,
linarith [hN' (max N N') (by apply le_max_right)],
end
/-
Let's now return to the result proved in the `00_` file of this series,
and prove again the sequential characterization of upper bounds (with a slighly
different proof).
For this, and other exercises below, we'll need many things that we proved in previous files,
and a couple of extras.
From the 5th file:
limit_const (x : ℝ) : seq_limit (λ n, x) x
squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l)
(hu : ∀ n, u n ≤ v n) (hw : ∀ n, v n ≤ w n) : seq_limit v l
From the 8th:
def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x
def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y
lt_sup (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a :=
You can also use:
nat.one_div_pos_of_nat {n : ℕ} : 0 < 1 / (n + 1 : ℝ)
inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε
and their easy consequences:
limit_of_sub_le_inv_succ (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x
limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x
limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x
The structure of the proof is offered. It features a new tactic:
`choose` which invokes the axiom of choice (observing the tactic state before and
after using it should be enough to understand everything).
-/
-- 0072
lemma is_sup_iff (A : set ℝ) (x : ℝ) :
(is_sup A x) ↔ (upper_bound A x ∧ ∃ u : ℕ → ℝ, seq_limit u x ∧ ∀ n, u n ∈ A ) :=
begin
split,
{ intro h,
split,
{
exact h.1,
},
{ have : ∀ n : ℕ, ∃ a ∈ A, x - 1/(n+1) < a,
{ intros n,
have : 1/(n+1 : ℝ) > 0,
exact nat.one_div_pos_of_nat,
exact lt_sup h (x - 1/(n+1)) (by linarith),
},
choose u hu using this,
use u, split,
{ apply limit_of_sub_le_inv_succ, intro n,
rw abs_le, split,
{ linarith [(hu n).2], },
{ suffices : u n - x < 1 / (n + 1), by linarith,
calc u n - x ≤ 0 : by linarith [h.1 _ ((hu n).1)]
... < 1 / (n + 1) : nat.one_div_pos_of_nat,
},
},
{ intro n, exact (hu n).1, }
} },
{ rintro ⟨maj, u, limu, u_in⟩,
split,
{ exact maj, },
{ intros y ub,
apply le_of_le_add_all,
intros ε hε,
cases limu ε hε with N hN,
specialize hN N (by linarith),
rw abs_le at hN,
linarith [ub _ (u_in N)],
}
},
end
/-- Continuity of a function at a point -/
def continuous_at_pt (f : ℝ → ℝ) (x₀ : ℝ) : Prop :=
∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε
variables {f : ℝ → ℝ} {x₀ : ℝ} {u : ℕ → ℝ}
-- 0073
lemma seq_continuous_of_continuous (hf : continuous_at_pt f x₀)
(hu : seq_limit u x₀) : seq_limit (f ∘ u) (f x₀) :=
begin
intros ε hε,
rcases hf ε hε with ⟨δ, hδ, hf⟩,
cases hu δ hδ with N hN,
use N, intros n hn,
apply hf,
apply hN,
exact hn,
end
-- 0074
example :
(∀ u : ℕ → ℝ, seq_limit u x₀ → seq_limit (f ∘ u) (f x₀)) →
continuous_at_pt f x₀ :=
begin
contrapose!,
intro hf,
unfold continuous_at_pt at hf,
push_neg at hf,
rcases hf with ⟨ε, hε, hf⟩,
have H : ∀ n : ℕ, ∃ x, |x - x₀| ≤ 1/(n+1) ∧ ε < |f x - f x₀|,
intro n,
apply hf,
exact nat.one_div_pos_of_nat,
clear hf,
choose u hu using H,
use u, split,
{ intros η hη,
cases inv_succ_le_all η hη with N hN,
use N, intros n hn,
linarith [(hu n).1, hN n hn],
},
{ unfold seq_limit,
push_neg,
use ε, split,
{ exact hε, },
{ intros N,
use N,
exact ⟨by linarith, (hu N).2⟩,
}
}
end
/-
Recall from the 6th file:
def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m
def cluster_point (u : ℕ → ℝ) (a : ℝ) :=
∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a
id_le_extraction : extraction φ → ∀ n, n ≤ φ n
and from the 8th file:
def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A
not_seq_limit_of_tendstoinfinity : tendsto_infinity u → ∀ l, ¬ seq_limit u l
-/
variables {φ : ℕ → ℕ}
-- 0075
lemma subseq_tendstoinfinity
(h : tendsto_infinity u) (hφ : extraction φ) :
tendsto_infinity (u ∘ φ) :=
begin
intro a,
cases h a with N hN,
use N,
intros n hn,
apply hN,
linarith [id_le_extraction hφ n],
end
-- 0076
lemma squeeze_infinity {u v : ℕ → ℝ} (hu : tendsto_infinity u)
(huv : ∀ n, u n ≤ v n) : tendsto_infinity v :=
begin
intro a,
cases hu a with N hN,
use N,
intros n hn,
linarith [huv n, hN n hn],
end
/-
We will use segments: Icc a b := { x | a ≤ x ∧ x ≤ b }
The notation stands for Interval-closed-closed. Variations exist with
o or i instead of c, where o stands for open and i for infinity.
We will use the following version of Bolzano-Weierstrass
bolzano_weierstrass (h : ∀ n, u n ∈ [a, b]) :
∃ c ∈ [a, b], cluster_point u c
as well as the obvious
seq_limit_id : tendsto_infinity (λ n, n)
-/
open set
-- 0077
lemma bdd_above_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ M, ∀ x ∈ Icc a b, f x ≤ M :=
begin
by_contradiction H,
push_neg at H,
have H' : ∀ n : ℕ, ∃ x, x ∈ Icc a b ∧ f x > n, from (λ n, H n),
clear H,
choose u hu using H',
rcases bolzano_weierstrass (λ n, (hu n).1) with ⟨c, hc, ⟨φ, hφ, hlim⟩⟩,
-- on the one hand
have has_limit : seq_limit (f ∘ (u ∘ φ)) (f c),
from seq_continuous_of_continuous (hf c hc) hlim,
-- on the other hand
have tendsto_inf₁ : tendsto_infinity (f ∘ u),
from squeeze_infinity seq_limit_id (λ n, by linarith [(hu n).2]),
have tendsto_inf : tendsto_infinity (f ∘ (u ∘ φ)),
from subseq_tendstoinfinity tendsto_inf₁ hφ,
-- therefore
exact not_seq_limit_of_tendstoinfinity tendsto_inf _ has_limit,
end
/-
In the next exercise, we can use:
abs_neg x : |-x| = |x|
-/
-- 0078
lemma continuous_opposite {f : ℝ → ℝ} {x₀ : ℝ} (h : continuous_at_pt f x₀) :
continuous_at_pt (λ x, -f x) x₀ :=
begin
intros ε hε,
rcases h ε hε with ⟨δ, hδ, h⟩,
use [δ, hδ],
intros x hx,
have : -f x - -f x₀ = -(f x - f x₀), by ring,
rw [this, abs_neg],
apply h, exact hx,
end
/-
Now let's combine the two exercises above
-/
-- 0079
lemma bdd_below_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ m, ∀ x ∈ Icc a b, m ≤ f x :=
begin
have : ∃ M, ∀ x ∈ Icc a b, -f x ≤ M,
{ apply bdd_above_segment,
intros x hx,
apply continuous_opposite,
exact hf x hx,
},
cases this with M hM,
use -M,
intros x hx,
linarith [hM x hx],
end
/-
Remember from the 5th file:
unique_limit : seq_limit u l → seq_limit u l' → l = l'
and from the 6th one:
subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) :
seq_limit (u ∘ φ) l
We now admit the following version of the least upper bound theorem
(that cannot be proved without discussing the construction of real numbers
or admitting another strong theorem).
sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) :
∃ x ∈ Icc a b, is_sup A x
In the next exercise, it can be useful to prove inclusions of sets of real number.
By definition, A ⊆ B means : ∀ x, x ∈ A → x ∈ B.
Hence one can start a proof of A ⊆ B by `intros x x_in`,
which brings `x : ℝ` and `x_in : x ∈ A` in the local context,
and then prove `x ∈ B`.
Note also the use of
{x | P x}
which denotes the set of x satisfying predicate P.
Hence `x' ∈ { x | P x} ↔ P x'`, by definition.
-/
-- 0080
example {a b : ℝ} (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ x₀ ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f x₀ :=
begin
cases bdd_above_segment hf with M hM,
cases bdd_below_segment hf with m hm,
let A := {y | ∃ x ∈ Icc a b, y = f x},
have A_nonempty : ∃ e, e ∈ A,
{ use f a, use a,
exact ⟨⟨by linarith, by linarith⟩, by ring⟩,
},
have A_inc : A ⊆ Icc m M,
{ rintros a ⟨x, hx, rfl⟩,
exact ⟨hm x hx, hM x hx⟩,
},
rcases sup_segment A_nonempty A_inc with ⟨y, hy, hsup⟩,
rw is_sup_iff at hsup,
rcases hsup with ⟨hub, u, ⟨lim_u, hu⟩⟩,
choose v hv using hu,
rcases bolzano_weierstrass (λ n, (hv n).1) with ⟨c, hc, ⟨φ, hφ, lim_vφ⟩⟩,
use [c, hc], intros x hx,
have lim_fvφ : seq_limit ((f ∘ v) ∘ φ) (f c),
from seq_continuous_of_continuous (hf c hc) lim_vφ,
clear lim_vφ,
have lim_uφ := subseq_tendsto_of_tendsto lim_u hφ,
have u_fv : u = f ∘ v, from funext (λ n, (hv n).2),
rw ← u_fv at lim_fvφ,
rw unique_limit lim_fvφ lim_uφ,
apply hub,
use x, exact ⟨hx, rfl⟩,
end
lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x ≠ b) : x < b :=
lt_of_le_of_ne h.right h'
/-
And now the final boss...
-/
def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here
-- 0081
example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (h₀ : f 0 < 0) (h₁ : f 1 > 0) :
∃ x₀ ∈ I, f x₀ = 0 :=
begin
let A := { x | x ∈ I ∧ f x < 0},
have ex_x₀ : ∃ x₀ ∈ I, is_sup A x₀,
{ apply sup_segment,
{ use 0, exact ⟨⟨by linarith, by linarith⟩, h₀⟩, },
{ intros a h, exact h.1, },
},
rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩,
use [x₀, x₀_in],
have : f x₀ ≤ 0,
{ rw is_sup_iff at x₀_sup,
rcases x₀_sup with ⟨_, u, lim_u, hu⟩,
have lim_fu := seq_continuous_of_continuous (hf x₀) lim_u,
have hfu : ∀ n, f (u n) ≤ 0, from λ n, by linarith [(hu n).2],
exact lim_le lim_fu hfu,
},
have x₀_1: x₀ < 1,
{ apply stupid x₀_in,
intro H,
rw H at this,
linarith,
},
have : f x₀ ≥ 0,
{ have in_I : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ I,
{ have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ 1-x₀,
from inv_succ_le_all _ (by linarith),
cases this with N hN,
use N, intros n hn,
have : 1 / (n + 1 : ℝ) > 0, from nat.one_div_pos_of_nat,
exact ⟨by linarith [x₀_in.1], by linarith [hN n hn]⟩,
},
have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A,
-- By definition, x ∉ A means ¬ (x ∈ A).
{ intros n hn,
have := x₀_sup.1 _ hn,
have : 1 / (n + 1 : ℝ) > 0, from nat.one_div_pos_of_nat,
linarith,
},
dsimp [A] at not_in,
push_neg at not_in,
cases in_I with N in_I,
have lim_f := seq_continuous_of_continuous (hf x₀) (limit_const_add_inv_succ _),
exact le_lim lim_f ⟨N, (λ n hn, not_in n (in_I n hn))⟩,
},
linarith,
end
-- In fact, a more general case is:
example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (a b : ℝ) (hab : a ≤ b)
(h₀ : f a < 0) (h₁ : f b > 0) :
∃ x₀ ∈ Icc a b, f x₀ = 0 :=
begin
let A := { x | x ∈ Icc a b ∧ f x < 0},
have ex_x₀ : ∃ x₀ ∈ Icc a b, is_sup A x₀,
{ apply sup_segment,
{ use a, exact ⟨⟨by linarith, hab⟩, h₀⟩, },
{ intros a h, exact h.1, },
},
rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩,
use [x₀, x₀_in],
have : f x₀ ≤ 0,
{ rw is_sup_iff at x₀_sup,
rcases x₀_sup with ⟨_, u, lim_u, hu⟩,
have lim_fu := seq_continuous_of_continuous (hf x₀) lim_u,
have hfu : ∀ n, f (u n) ≤ 0, from λ n, by linarith [(hu n).2],
exact lim_le lim_fu hfu,
},
have x₀_1: x₀ < b,
{ apply stupid x₀_in,
intro H,
rw H at this,
linarith,
},
have : f x₀ ≥ 0,
{ have in_I : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ Icc a b,
{ have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ b-x₀,
from inv_succ_le_all _ (by linarith),
cases this with N hN,
use N, intros n hn,
have : 1 / (n + 1 : ℝ) > 0, from nat.one_div_pos_of_nat,
exact ⟨by linarith [x₀_in.1], by linarith [hN n hn]⟩,
},
have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A,
-- By definition, x ∉ A means ¬ (x ∈ A).
{ intros n hn,
have := x₀_sup.1 _ hn,
have : 1 / (n + 1 : ℝ) > 0, from nat.one_div_pos_of_nat,
linarith,
},
dsimp [A] at not_in,
push_neg at not_in,
cases in_I with N in_I,
have lim_f := seq_continuous_of_continuous (hf x₀) (limit_const_add_inv_succ _),
exact le_lim lim_f ⟨N, (λ n hn, not_in n (in_I n hn))⟩,
},
linarith,
end
|
54ffcfd3848bb8909b6b16be510e55d4314050a9 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/data/set/intervals/basic.lean | 41299cd44a0d66b8cd8c3de1386626e605542cb1 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 30,498 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov
-/
import algebra.order_functions
import data.set.basic
/-!
# Intervals
In any preorder `α`, we define intervals (which on each side can be either infinite, open, or
closed) using the following naming conventions:
- `i`: infinite
- `o`: open
- `c`: closed
Each interval has the name `I` + letter for left side + letter for right side. For instance,
`Ioc a b` denotes the inverval `(a, b]`.
This file contains these definitions, and basic facts on inclusion, intersection, difference of
intervals (where the precise statements may depend on the properties of the order, in particular
for some statements it should be `linear_order` or `densely_ordered`).
TODO: This is just the beginning; a lot of rules are missing
-/
universe u
namespace set
open set
section intervals
variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α}
/-- Left-open right-open interval -/
def Ioo (a b : α) := {x | a < x ∧ x < b}
/-- Left-closed right-open interval -/
def Ico (a b : α) := {x | a ≤ x ∧ x < b}
/-- Left-infinite right-open interval -/
def Iio (a : α) := {x | x < a}
/-- Left-closed right-closed interval -/
def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b}
/-- Left-infinite right-closed interval -/
def Iic (b : α) := {x | x ≤ b}
/-- Left-open right-closed interval -/
def Ioc (a b : α) := {x | a < x ∧ x ≤ b}
/-- Left-closed right-infinite interval -/
def Ici (a : α) := {x | a ≤ x}
/-- Left-open right-infinite interval -/
def Ioi (a : α) := {x | a < x}
@[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl
@[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl
@[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl
@[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl
@[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl
@[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl
@[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl
@[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl
@[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl]
@[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl]
@[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl]
@[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl]
lemma left_mem_Ici : a ∈ Ici a := by simp
@[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl]
@[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl]
@[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl]
@[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl]
lemma right_mem_Iic : a ∈ Iic a := by simp
@[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl
@[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl
@[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl
@[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl
@[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a :=
set.ext $ λ x, and_comm _ _
@[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a :=
set.ext $ λ x, and_comm _ _
@[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a :=
set.ext $ λ x, and_comm _ _
@[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a :=
set.ext $ λ x, and_comm _ _
@[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b :=
⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩
@[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b :=
⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩
@[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b :=
⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩
@[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩
@[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩
@[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b :=
⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩
@[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a
@[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a
@[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h
@[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h
@[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h
@[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁
@[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _
@[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _
@[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _
lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a :=
⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩
lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b :=
@Ici_subset_Ici (order_dual α) _ _ _
lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a :=
⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩
lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b :=
⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩
lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Ioo a₁ b₁ ⊆ Ioo a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩
lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b :=
Ioo_subset_Ioo h (le_refl _)
lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ :=
Ioo_subset_Ioo (le_refl _) h
lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Ico a₁ b₁ ⊆ Ico a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩
lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b :=
Ico_subset_Ico h (le_refl _)
lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ :=
Ico_subset_Ico (le_refl _) h
lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Icc a₁ b₁ ⊆ Icc a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩
lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b :=
Icc_subset_Icc h (le_refl _)
lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ :=
Icc_subset_Icc (le_refl _) h
lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Ioc a₁ b₁ ⊆ Ioc a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩
lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b :=
Ioc_subset_Ioc h (le_refl _)
lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ :=
Ioc_subset_Ioc (le_refl _) h
lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b :=
λ x, and.imp_left $ lt_of_lt_of_le h₁
lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ :=
λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁
lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt
lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt
lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt
lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt
lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b :=
subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self
lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right
lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right
lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left
lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left
lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx
lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx
lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩,
λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩
lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ :=
⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩,
λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩
lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ :=
⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩,
λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩
lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ :=
⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩,
λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩
lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ :=
⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩
lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ :=
⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩
lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ :=
⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩
lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ :=
⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩
/-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need
the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/
lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a :=
λx hx, lt_of_le_of_lt h hx
/-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need
the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/
lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a :=
subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self
/-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need
the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/
lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b :=
λx hx, lt_of_lt_of_le hx h
/-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need
the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/
lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b :=
subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self
lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl
lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl
lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl
lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl
end intervals
section partial_order
variables {α : Type u} [partial_order α] {a b : α}
@[simp] lemma Icc_self (a : α) : Icc a a = {a} :=
set.ext $ by simp [Icc, le_antisymm_iff, and_comm]
lemma Icc_diff_left : Icc a b \ {a} = Ioc a b :=
ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm]
lemma Icc_diff_right : Icc a b \ {b} = Ico a b :=
ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc]
lemma Ico_diff_left : Ico a b \ {a} = Ioo a b :=
ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm]
lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b :=
ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne]
lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b :=
by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right]
lemma Ici_diff_left : Ici a \ {a} = Ioi a :=
ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm]
lemma Iic_diff_right : Iic a \ {a} = Iio a :=
ext $ λ x, by simp [lt_iff_le_and_ne]
lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} :=
by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)]
lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} :=
by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)]
lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} :=
by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)]
lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} :=
by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)]
lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} :=
by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] }
lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} :=
by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)]
lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} :=
by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)]
lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt]
lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm
lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) :
s ∈ ({Ici a, Ioi a} : set (set α)) :=
classical.by_cases
(λ h : a ∈ s, or.inl $ subset.antisymm hc $ by simp [← Ioi_union_left, insert_subset, *])
(λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho)
lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) :
s ∈ ({Iic a, Iio a} : set (set α)) :=
@mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc
lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) :
s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) :=
begin
classical,
by_cases ha : a ∈ s; by_cases hb : b ∈ s,
{ refine or.inl (subset.antisymm hc _),
rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha,
← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho },
{ refine (or.inr $ or.inl $ subset.antisymm _ _),
{ rw [← Icc_diff_right],
exact subset_diff_singleton hc hb },
{ rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } },
{ refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _),
{ rw [← Icc_diff_left],
exact subset_diff_singleton hc ha },
{ rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } },
{ refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho),
rw [← Ico_diff_left, ← Icc_diff_right],
apply_rules [subset_diff_singleton] }
end
end partial_order
section linear_order
variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α}
lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le
lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le
lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt
lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt
lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a :=
⟨λ eq, le_of_not_lt $ λ h,
let ⟨x, h₁, h₂⟩ := dense h in
eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩,
Ioo_eq_empty⟩
lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a :=
⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩,
Ico_eq_empty⟩
lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a :=
⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩,
Icc_eq_empty⟩
lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) :
Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩,
⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩,
λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩
lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) :
Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
⟨λ h, begin
rcases dense h₁ with ⟨x, xa, xb⟩,
split; refine le_of_not_lt (λ h', _),
{ have ab := lt_trans (h ⟨xa, xb⟩).1 xb,
exact lt_irrefl _ (h ⟨h', ab⟩).1 },
{ have ab := lt_trans xa (h ⟨xa, xb⟩).2,
exact lt_irrefl _ (h ⟨ab, h'⟩).2 }
end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩
lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
⟨λ e, begin
simp [subset.antisymm_iff] at e, simp [le_antisymm_iff],
cases h; simp [Ico_subset_Ico_iff h] at e;
[ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ];
have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e';
tauto
end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩
open_locale classical
@[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b :=
begin
refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩,
by_contradiction ba,
exact lt_irrefl _ (h (not_le.mp ba))
end
@[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b :=
begin
refine ⟨λh, _, λh, Ioi_subset_Ici h⟩,
by_contradiction ba,
obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba),
exact lt_irrefl _ (lt_of_lt_of_le ca (h bc))
end
@[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b :=
begin
refine ⟨λh, _, λh, Iio_subset_Iio h⟩,
by_contradiction ab,
exact lt_irrefl _ (h (not_le.mp ab))
end
@[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b :=
begin
refine ⟨λh, _, λh, Iio_subset_Iic h⟩,
by_contradiction ba,
obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba),
exact lt_irrefl _ (lt_of_lt_of_le bc (h ca))
end
/-! ### Unions of adjacent intervals -/
/-! #### Two infinite intervals -/
@[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a)
@[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a)
@[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a)
/-! #### A finite and an infinite interval -/
lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)
@[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a :=
subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioo_union_Ici
lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)
@[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a :=
subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Ico_union_Ici
lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)
@[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a :=
subset.antisymm (λ x hx, hx.elim and.left (lt_of_le_of_lt h)) Ioi_subset_Ioc_union_Ioi
lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)
@[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a :=
subset.antisymm (λ x hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx))) Ici_subset_Icc_union_Ioi
lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b :=
subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self)
@[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a :=
subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioc_union_Ici
lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b :=
subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self)
@[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a :=
subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Icc_union_Ici
/-! #### An infinite and a finite interval -/
lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b :=
λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)
@[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b :=
subset.antisymm (λ x hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right)
Iic_subset_Iio_union_Icc
lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b :=
λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)
@[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b :=
subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right) Iio_subset_Iio_union_Ico
lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b :=
λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)
@[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b :=
subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Ioc
lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b :=
λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)
@[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b :=
subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ioo
lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b :=
subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self)
@[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b :=
subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Icc
lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b :=
subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self)
@[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b :=
subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ico
/-! #### Two finite intervals, `I?o` and `Ic?` -/
variable {c : α}
lemma Ioo_subset_Ioo_union_Ici : Ioo a c ⊆ Ioo a b ∪ Ico b c :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩))
Ioo_subset_Ioo_union_Ici
lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩))
Ico_subset_Ico_union_Ico
lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩))
Icc_subset_Ico_union_Icc
lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c :=
λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩)
(λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩))
Ioc_subset_Ioo_union_Icc
/-! #### Two finite intervals, `I?c` and `Io?` -/
lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩))
Ioo_subset_Ioc_union_Ioo
lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩)
(λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩))
Ico_subset_Icc_union_Ioo
lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩))
Icc_subset_Icc_union_Ioc
lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c :=
λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)
@[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩))
Ioc_subset_Ioc_union_Ioc
/-! #### Two finite intervals with a common point -/
lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c :=
subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self)
@[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩))
Ioo_subset_Ioc_union_Ico
lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c :=
subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self)
@[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩))
Ico_subset_Icc_union_Ico
lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c :=
subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self)
@[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩))
Icc_subset_Icc_union_Icc
lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c :=
subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self)
@[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c :=
subset.antisymm
(λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩))
Ioc_subset_Ioc_union_Icc
end linear_order
section lattice
section inf
variables {α : Type u} [semilattice_inf α]
@[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) :=
by { ext x, simp [Iic] }
@[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) :=
by { ext x, simp [Iio] }
end inf
section sup
variables {α : Type u} [semilattice_sup α]
@[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) :=
by { ext x, simp [Ici] }
@[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) :=
by { ext x, simp [Ioi] }
end sup
section both
variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α}
lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl
@[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) :
Icc a b ∩ Icc b c = {b} :=
by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self]
include ht
lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl
lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl
lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl
end both
end lattice
section decidable_linear_order
variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α}
@[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b :=
set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt}
@[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) :=
set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt}
end decidable_linear_order
section decidable_linear_ordered_add_comm_group
variables {α : Type u} [decidable_linear_ordered_add_comm_group α]
/-- If we remove a smaller interval from a larger, the result is nonempty -/
lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) :
nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) :=
begin
cases lt_or_le x y with h' h',
{ use x, simp* },
{ use max x (x + dy), simp [*, le_refl] }
end
end decidable_linear_ordered_add_comm_group
end set
|
7f88e9e765523e1d02314da7dbcce37d998b9176 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/geometry/manifold/smooth_manifold_with_corners.lean | 3bfe3938d8683a6afbdca265a9470f11414d58f8 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 32,900 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.times_cont_diff
import geometry.manifold.charted_space
/-!
# Smooth manifolds (possibly with boundary or corners)
A smooth manifold is a manifold modelled on a normed vector space, or a subset like a
half-space (to get manifolds with boundaries) for which the changes of coordinates are smooth maps.
We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in
the vector space `E` (or more precisely as a structure containing all the relevant properties).
Given such a model with corners `I` on `(E, H)`, we define the groupoid of local
homeomorphisms of `H` which are smooth when read in `E` (for any regularity `n : with_top ℕ`).
With this groupoid at hand and the general machinery of charted spaces, we thus get the notion
of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. We also introduce a
specific type class for `C^∞` manifolds as these are the most commonly used.
## Main definitions
* `model_with_corners 𝕜 E H` :
a structure containing informations on the way a space `H` embeds in a
model vector space E over the field `𝕜`. This is all that is needed to
define a smooth manifold with model space `H`, and model vector space `E`.
* `model_with_corners_self 𝕜 E` :
trivial model with corners structure on the space `E` embedded in itself by the identity.
* `times_cont_diff_groupoid n I` :
when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of local homeos of `H`
which are of class `C^n` over the normed field `𝕜`, when read in `E`.
* `smooth_manifold_with_corners I M` :
a type class saying that the charted space `M`, modelled on the space `H`, has `C^∞` changes of
coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just
a shortcut for `has_groupoid M (times_cont_diff_groupoid ∞ I)`.
* `ext_chart_at I x`:
in a smooth manifold with corners with the model `I` on `(E, H)`, the charts take values in `H`,
but often we may want to use their `E`-valued version, obtained by composing the charts with `I`.
Since the target is in general not open, we can not register them as local homeomorphisms, but
we register them as local equivs. `ext_chart_at I x` is the canonical such local equiv around `x`.
As specific examples of models with corners, we define (in the file `real_instances.lean`)
* `model_with_corners_self ℝ (euclidean_space (fin n))` for the model space used to define
`n`-dimensional real manifolds without boundary (with notation `𝓡 n` in the locale `manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space
used to define `n`-dimensional real manifolds with boundary (with notation `𝓡∂ n` in the locale
`manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
With these definitions at hand, to invoke an `n`-dimensional real manifold without boundary,
one could use
`variables {n : ℕ} {M : Type*} [topological_space M] [charted_space (euclidean_space (fin n)) M]
[smooth_manifold_with_corners (𝓡 n) M]`.
However, this is not the recommended way: a theorem proved using this assumption would not apply
for instance to the tangent space of such a manifold, which is modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin n))` and not on `euclidean_space (fin (2 * n))`!
In the same way, it would not apply to product manifolds, modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin m))`.
The right invocation does not focus on one specific construction, but on all constructions sharing
the right properties, like
`variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{I : model_with_corners ℝ E E} [I.boundaryless]
{M : Type*} [topological_space M] [charted_space E M] [smooth_manifold_with_corners I M]`
Here, `I.boundaryless` is a typeclass property ensuring that there is no boundary (this is for
instance the case for `model_with_corners_self`, or products of these). Note that one could consider
as a natural assumption to only use the trivial model with corners `model_with_corners_self ℝ E`,
but again in product manifolds the natural model with corners will not be this one but the product
one (and they are not defeq as `(λp : E × F, (p.1, p.2))` is not defeq to the identity). So, it is
important to use the above incantation to maximize the applicability of theorems.
## Implementation notes
We want to talk about manifolds modelled on a vector space, but also on manifolds with
boundary, modelled on a half space (or even manifolds with corners). For the latter examples,
we still want to define smooth functions, tangent bundles, and so on. As smooth functions are
well defined on vector spaces or subsets of these, one could take for model space a subtype of a
vector space. With the drawback that the whole vector space itself (which is the most basic
example) is not directly a subtype of itself: the inclusion of `univ : set E` in `set E` would
show up in the definition, instead of `id`.
A good abstraction covering both cases it to have a vector
space `E` (with basic example the Euclidean space), a model space `H` (with basic example the upper
half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or
`subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a
model with corners, and we encompass all the relevant properties (in particular the fact that the
image of `H` in `E` should have unique differentials) in the definition of `model_with_corners`.
We concentrate on `C^∞` manifolds: all the definitions work equally well for `C^n` manifolds, but
later on it is a pain to carry all over the smoothness parameter, especially when one wants to deal
with `C^k` functions as there would be additional conditions `k ≤ n` everywhere. Since one deals
almost all the time with `C^∞` (or analytic) manifolds, this seems to be a reasonable choice that
one could revisit later if needed. `C^k` manifolds are still available, but they should be called
using `has_groupoid M (times_cont_diff_groupoid k I)` where `I` is the model with corners.
I have considered using the model with corners `I` as a typeclass argument, possibly `out_param`, to
get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural
model with corners, the trivial (identity) one, and the product one, and they are not defeq and one
needs to indicate to Lean which one we want to use.
This means that when talking on objects on manifolds one will most often need to specify the model
with corners one is using. For instance, the tangent bundle will be `tangent_bundle I M` and the
derivative will be `mfderiv I I' f`, instead of the more natural notations `tangent_bundle 𝕜 M` and
`mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as
real and complex manifolds).
-/
noncomputable theory
universes u v w u' v' w'
open set
localized "notation `∞` := (⊤ : with_top ℕ)" in manifold
section model_with_corners
/-! ### Models with corners. -/
/-- A structure containing informations on the way a space `H` embeds in a
model vector space `E` over the field `𝕜`. This is all what is needed to
define a smooth manifold with model space `H`, and model vector space `E`.
-/
@[nolint has_inhabited_instance]
structure model_with_corners (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] (H : Type*) [topological_space H]
extends local_equiv H E :=
(source_eq : source = univ)
(unique_diff' : unique_diff_on 𝕜 (range to_fun))
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
attribute [simp, mfld_simps] model_with_corners.source_eq
/-- A vector space is a model with corners. -/
def model_with_corners_self (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] : model_with_corners 𝕜 E E :=
{ to_fun := id,
inv_fun := id,
source := univ,
target := univ,
source_eq := rfl,
map_source' := λ_ _, mem_univ _,
map_target' := λ_ _, mem_univ _,
left_inv' := λ_ _, rfl,
right_inv' := λ_ _, rfl,
unique_diff' := by { rw range_id, exact unique_diff_on_univ },
continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id }
section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H)
instance : has_coe_to_fun (model_with_corners 𝕜 E H) := ⟨_, λ e, e.to_fun⟩
/-- The inverse to a model with corners, only registered as a local equiv. -/
protected def model_with_corners.symm : local_equiv E H := I.to_local_equiv.symm
/- Register a few lemmas to make sure that `simp` puts expressions in normal form -/
@[simp, mfld_simps] lemma model_with_corners.to_local_equiv_coe : (I.to_local_equiv : H → E) = I := rfl
@[simp, mfld_simps] lemma model_with_corners.mk_coe (e : local_equiv H E) (a b c d) :
((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H) : H → E) = (e : H → E) := rfl
@[simp, mfld_simps] lemma model_with_corners.to_local_equiv_coe_symm :
(I.to_local_equiv.symm : E → H) = I.symm := rfl
@[simp, mfld_simps] lemma model_with_corners.mk_coe_symm (e : local_equiv H E) (a b c d) :
((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H).symm : E → H) = (e.symm : E → H) :=
rfl
lemma model_with_corners.unique_diff : unique_diff_on 𝕜 (range I) := I.unique_diff'
protected lemma model_with_corners.continuous : continuous I := I.continuous_to_fun
lemma model_with_corners.continuous_symm : continuous I.symm := I.continuous_inv_fun
section
variables (𝕜 E)
/-- In the trivial model with corners, the associated local equiv is the identity. -/
@[simp, mfld_simps] lemma model_with_corners_self_local_equiv :
(model_with_corners_self 𝕜 E).to_local_equiv = local_equiv.refl E := rfl
@[simp, mfld_simps] lemma model_with_corners_self_coe :
(model_with_corners_self 𝕜 E : E → E) = id := rfl
@[simp, mfld_simps] lemma model_with_corners_self_coe_symm :
((model_with_corners_self 𝕜 E).symm : E → E) = id := rfl
end
@[simp, mfld_simps] lemma model_with_corners.target : I.target = range (I : H → E) :=
by { rw [← image_univ, ← I.source_eq], exact (I.to_local_equiv.image_source_eq_target).symm }
@[simp, mfld_simps] lemma model_with_corners.left_inv (x : H) : I.symm (I x) = x :=
by { convert I.left_inv' _, simp }
@[simp, mfld_simps] lemma model_with_corners.left_inv' : I.symm ∘ I = id :=
by { ext x, exact model_with_corners.left_inv _ _ }
@[simp, mfld_simps] lemma model_with_corners.right_inv {x : E} (hx : x ∈ range I) :
I (I.symm x) = x :=
by { apply I.right_inv', simp [hx] }
lemma model_with_corners.image (s : set H) :
I '' s = I.symm ⁻¹' s ∩ range I :=
begin
ext x,
simp only [mem_image, mem_inter_eq, mem_range, mem_preimage],
split,
{ rintros ⟨y, ⟨ys, hy⟩⟩,
rw ← hy,
simp only [ys, true_and, model_with_corners.left_inv],
exact ⟨y, rfl⟩ },
{ rintros ⟨xs, ⟨y, yx⟩⟩,
rw ← yx at xs,
simp only [model_with_corners.left_inv] at xs,
exact ⟨y, ⟨xs, yx⟩⟩ }
end
lemma model_with_corners.unique_diff_preimage {s : set H} (hs : is_open s) :
unique_diff_on 𝕜 (I.symm ⁻¹' s ∩ range I) :=
by { rw inter_comm, exact I.unique_diff.inter (I.continuous_inv_fun _ hs) }
lemma model_with_corners.unique_diff_preimage_source {β : Type*} [topological_space β]
{e : local_homeomorph H β} : unique_diff_on 𝕜 (I.symm ⁻¹' (e.source) ∩ range I) :=
I.unique_diff_preimage e.open_source
lemma model_with_corners.unique_diff_at_image {x : H} : unique_diff_within_at 𝕜 (range I) (I x) :=
I.unique_diff _ (mem_range_self _)
end
section model_with_corners_prod
/-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with
corners `I.prod I'` on `(E × E', H × H')`. This appears in particular for the manifold structure on
the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on `(E × E, H × E)`. -/
def model_with_corners.prod
{𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H)
{E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
(I' : model_with_corners 𝕜 E' H') : model_with_corners 𝕜 (E × E') (model_prod H H') :=
{ to_fun := λ p, (I p.1, I' p.2),
inv_fun := λ p, (I.symm p.1, I'.symm p.2),
source := (univ : set (H × H')),
target := set.prod (range I) (range I'),
map_source' := λ ⟨x, x'⟩ _, by simp [-mem_range, mem_range_self],
map_target' := λ ⟨x, x'⟩ _, mem_univ _,
left_inv' := λ ⟨x, x'⟩ _, by simp,
right_inv' := λ ⟨x, x'⟩ ⟨hx, hx'⟩, by simp [hx, hx'],
source_eq := rfl,
unique_diff' := begin
have : range (λ(p : model_prod H H'), (I p.1, I' p.2)) = set.prod (range I) (range I'),
by { dsimp [model_prod], rw ← prod_range_range_eq },
rw this,
exact unique_diff_on.prod I.unique_diff I'.unique_diff,
end,
continuous_to_fun := (continuous.comp I.continuous_to_fun continuous_fst).prod_mk
(continuous.comp I'.continuous_to_fun continuous_snd),
continuous_inv_fun := (continuous.comp I.continuous_inv_fun continuous_fst).prod_mk
(continuous.comp I'.continuous_inv_fun continuous_snd) }
/-- Special case of product model with corners, which is trivial on the second factor. This shows up
as the model to tangent bundles. -/
@[reducible] def model_with_corners.tangent
{𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H) : model_with_corners 𝕜 (E × E) (model_prod H E) :=
I.prod (model_with_corners_self 𝕜 E)
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{F : Type*} [normed_group F] [normed_space 𝕜 F] {F' : Type*} [normed_group F'] [normed_space 𝕜 F']
{H : Type*} [topological_space H] {H' : Type*} [topological_space H']
{G : Type*} [topological_space G] {G' : Type*} [topological_space G']
{I : model_with_corners 𝕜 E H} {J : model_with_corners 𝕜 F G}
@[simp, mfld_simps] lemma model_with_corners_prod_to_local_equiv :
(I.prod J).to_local_equiv = (I.to_local_equiv).prod (J.to_local_equiv) :=
begin
ext1 x,
{ refl, },
{ intro x, refl, },
{ simp only [set.univ_prod_univ, model_with_corners.source_eq, local_equiv.prod_source], }
end
@[simp, mfld_simps] lemma model_with_corners_prod_coe
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
(I.prod I' : _ × _ → _ × _) = prod.map I I' := rfl
@[simp, mfld_simps] lemma model_with_corners_prod_coe_symm
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
((I.prod I').symm : _ × _ → _ × _) = prod.map I.symm I'.symm := rfl
end model_with_corners_prod
section boundaryless
/-- Property ensuring that the model with corners `I` defines manifolds without boundary. -/
class model_with_corners.boundaryless {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H) : Prop :=
(range_eq_univ : range I = univ)
/-- The trivial model with corners has no boundary -/
instance model_with_corners_self_boundaryless (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).boundaryless :=
⟨by simp⟩
/-- If two model with corners are boundaryless, their product also is -/
instance model_with_corners.range_eq_univ_prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H) [I.boundaryless]
{E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
(I' : model_with_corners 𝕜 E' H') [I'.boundaryless] :
(I.prod I').boundaryless :=
begin
split,
dsimp [model_with_corners.prod, model_prod],
rw [← prod_range_range_eq, model_with_corners.boundaryless.range_eq_univ,
model_with_corners.boundaryless.range_eq_univ, univ_prod_univ]
end
end boundaryless
section times_cont_diff_groupoid
/-! ### Smooth functions on models with corners -/
variables {m n : with_top ℕ} {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M]
variable (n)
/-- Given a model with corners `(E, H)`, we define the groupoid of `C^n` transformations of `H` as
the maps that are `C^n` when read in `E` through `I`. -/
def times_cont_diff_groupoid : structure_groupoid H :=
pregroupoid.groupoid
{ property := λf s, times_cont_diff_on 𝕜 n (I ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
comp := λf g u v hf hg hu hv huv, begin
have : I ∘ (g ∘ f) ∘ I.symm = (I ∘ g ∘ I.symm) ∘ (I ∘ f ∘ I.symm),
by { ext x, simp },
rw this,
apply times_cont_diff_on.comp hg _,
{ rintros x ⟨hx1, hx2⟩,
simp only with mfld_simps at ⊢ hx1,
exact hx1.2 },
{ refine hf.mono _,
rintros x ⟨hx1, hx2⟩,
exact ⟨hx1.1, hx2⟩ }
end,
id_mem := begin
apply times_cont_diff_on.congr (times_cont_diff_id.times_cont_diff_on),
rintros x ⟨hx1, hx2⟩,
rcases mem_range.1 hx2 with ⟨y, hy⟩,
rw ← hy,
simp only with mfld_simps,
end,
locality := λf u hu H, begin
apply times_cont_diff_on_of_locally_times_cont_diff_on,
rintros y ⟨hy1, hy2⟩,
rcases mem_range.1 hy2 with ⟨x, hx⟩,
rw ← hx at ⊢ hy1,
simp only with mfld_simps at ⊢ hy1,
rcases H x hy1 with ⟨v, v_open, xv, hv⟩,
have : ((I.symm ⁻¹' (u ∩ v)) ∩ (range I))
= ((I.symm ⁻¹' u) ∩ (range I) ∩ I.symm ⁻¹' v),
{ rw [preimage_inter, inter_assoc, inter_assoc],
congr' 1,
rw inter_comm },
rw this at hv,
exact ⟨I.symm ⁻¹' v, I.continuous_symm _ v_open, by simpa, hv⟩
end,
congr := λf g u hu fg hf, begin
apply hf.congr,
rintros y ⟨hy1, hy2⟩,
rcases mem_range.1 hy2 with ⟨x, hx⟩,
rw ← hx at ⊢ hy1,
simp only with mfld_simps at ⊢ hy1,
rw fg _ hy1
end }
variable {n}
/-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when
`m ≤ n` -/
lemma times_cont_diff_groupoid_le (h : m ≤ n) :
times_cont_diff_groupoid n I ≤ times_cont_diff_groupoid m I :=
begin
rw [times_cont_diff_groupoid, times_cont_diff_groupoid],
apply groupoid_of_pregroupoid_le,
assume f s hfs,
exact times_cont_diff_on.of_le hfs h
end
/-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all
local homeomorphisms -/
lemma times_cont_diff_groupoid_zero_eq :
times_cont_diff_groupoid 0 I = continuous_groupoid H :=
begin
apply le_antisymm le_top,
assume u hu,
-- we have to check that every local homeomorphism belongs to `times_cont_diff_groupoid 0 I`,
-- by unfolding its definition
change u ∈ times_cont_diff_groupoid 0 I,
rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid],
simp only [times_cont_diff_on_zero],
split,
{ apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous)
_ (subset_univ _),
apply continuous_on.comp u.continuous_to_fun I.continuous_symm.continuous_on
(inter_subset_left _ _) },
{ apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous)
_ (subset_univ _),
apply continuous_on.comp u.continuous_inv_fun I.continuous_inv_fun.continuous_on
(inter_subset_left _ _) },
end
variable (n)
/-- An identity local homeomorphism belongs to the `C^n` groupoid. -/
lemma of_set_mem_times_cont_diff_groupoid {s : set H} (hs : is_open s) :
local_homeomorph.of_set s hs ∈ times_cont_diff_groupoid n I :=
begin
rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid],
suffices h : times_cont_diff_on 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
by simp [h],
have : times_cont_diff_on 𝕜 n id (univ : set E) :=
times_cont_diff_id.times_cont_diff_on,
exact this.congr_mono (λ x hx, by simp [hx.2]) (subset_univ _)
end
/-- The composition of a local homeomorphism from `H` to `M` and its inverse belongs to
the `C^n` groupoid. -/
lemma symm_trans_mem_times_cont_diff_groupoid (e : local_homeomorph M H) :
e.symm.trans e ∈ times_cont_diff_groupoid n I :=
begin
have : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target :=
local_homeomorph.trans_symm_self _,
exact structure_groupoid.eq_on_source _
(of_set_mem_times_cont_diff_groupoid n I e.open_target) this
end
variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H']
/-- The product of two smooth local homeomorphisms is smooth. -/
lemma times_cont_diff_groupoid_prod
{I : model_with_corners 𝕜 E H} {I' : model_with_corners 𝕜 E' H'}
{e : local_homeomorph H H} {e' : local_homeomorph H' H'}
(he : e ∈ times_cont_diff_groupoid ⊤ I) (he' : e' ∈ times_cont_diff_groupoid ⊤ I') :
e.prod e' ∈ times_cont_diff_groupoid ⊤ (I.prod I') :=
begin
cases he with he he_symm,
cases he' with he' he'_symm,
simp only at he he_symm he' he'_symm,
split;
simp only [local_equiv.prod_source, local_homeomorph.prod_to_local_equiv],
{ have h3 := times_cont_diff_on.map_prod he he',
rw [← model_with_corners.image I _, ← model_with_corners.image I' _,
set.prod_image_image_eq] at h3,
rw ← model_with_corners.image (I.prod I') _,
exact h3, },
{ have h3 := times_cont_diff_on.map_prod he_symm he'_symm,
rw [← model_with_corners.image I _, ← model_with_corners.image I' _,
set.prod_image_image_eq] at h3,
rw ← model_with_corners.image (I.prod I') _,
exact h3, }
end
/-- The `C^n` groupoid is closed under restriction. -/
instance : closed_under_restriction (times_cont_diff_groupoid n I) :=
(closed_under_restriction_iff_id_le _).mpr
begin
apply structure_groupoid.le_iff.mpr,
rintros e ⟨s, hs, hes⟩,
apply (times_cont_diff_groupoid n I).eq_on_source' _ _ _ hes,
exact of_set_mem_times_cont_diff_groupoid n I hs,
end
end times_cont_diff_groupoid
end model_with_corners
/-! ### Smooth manifolds with corners -/
/-- Typeclass defining smooth manifolds with corners with respect to a model with corners, over a
field `𝕜` and with infinite smoothness to simplify typeclass search and statements later on. -/
class smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{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] extends
has_groupoid M (times_cont_diff_groupoid ∞ I) : Prop
/-- For any model with corners, the model space is a smooth manifold -/
instance model_space_smooth {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
{I : model_with_corners 𝕜 E H} :
smooth_manifold_with_corners I H := {}
namespace smooth_manifold_with_corners
/- We restate in the namespace `smooth_manifolds_with_corners` some lemmas that hold for general
charted space with a structure groupoid, avoiding the need to specify the groupoid
`times_cont_diff_groupoid ∞ I` explicitly. -/
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{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]
/-- The maximal atlas of `M` for the smooth manifold with corners structure corresponding to the
model with corners `I`. -/
def maximal_atlas := (times_cont_diff_groupoid ∞ I).maximal_atlas M
variable {M}
lemma compatible [smooth_manifold_with_corners I M]
{e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) :
e.symm.trans e' ∈ times_cont_diff_groupoid ∞ I :=
has_groupoid.compatible _ he he'
lemma mem_maximal_atlas_of_mem_atlas [smooth_manifold_with_corners I M]
{e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ maximal_atlas I M :=
structure_groupoid.mem_maximal_atlas_of_mem_atlas _ he
lemma chart_mem_maximal_atlas [smooth_manifold_with_corners I M] (x : M) :
chart_at H x ∈ maximal_atlas I M :=
structure_groupoid.chart_mem_maximal_atlas _ x
variable {I}
lemma compatible_of_mem_maximal_atlas
{e e' : local_homeomorph M H} (he : e ∈ maximal_atlas I M) (he' : e' ∈ maximal_atlas I M) :
e.symm.trans e' ∈ times_cont_diff_groupoid ∞ I :=
structure_groupoid.compatible_of_mem_maximal_atlas he he'
/-- The product of two smooth manifolds with corners is naturally a smooth manifold with corners. -/
instance prod_smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
(M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
(M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] :
smooth_manifold_with_corners (I.prod I') (M×M') :=
{ compatible :=
begin
rintros f g ⟨f1, hf1, f2, hf2, hf⟩ ⟨g1, hg1, g2, hg2, hg⟩,
rw [hf, hg, local_homeomorph.prod_symm, local_homeomorph.prod_trans],
have h1 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) hf1 hg1,
have h2 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I') hf2 hg2,
exact times_cont_diff_groupoid_prod h1 h2,
end }
end smooth_manifold_with_corners
section extended_charts
open_locale topological_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{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]
(x : M) {s t : set M}
/-!
### Extended charts
In a smooth manifold with corners, the model space is the space `H`. However, we will also
need to use extended charts taking values in the model vector space `E`. These extended charts are
not `local_homeomorph` as the target is not open in `E` in general, but we can still register them
as `local_equiv`.
-/
/-- The preferred extended chart on a manifold with corners around a point `x`, from a neighborhood
of `x` to the model vector space. -/
@[simp, mfld_simps] def ext_chart_at (x : M) : local_equiv M E :=
(chart_at H x).to_local_equiv.trans I.to_local_equiv
lemma ext_chart_at_source : (ext_chart_at I x).source = (chart_at H x).source :=
by rw [ext_chart_at, local_equiv.trans_source, I.source_eq, preimage_univ, inter_univ]
lemma ext_chart_at_open_source : is_open (ext_chart_at I x).source :=
by { rw ext_chart_at_source, exact (chart_at H x).open_source }
lemma mem_ext_chart_source : x ∈ (ext_chart_at I x).source :=
by simp only with mfld_simps
lemma ext_chart_at_to_inv :
(ext_chart_at I x).symm ((ext_chart_at I x) x) = x :=
by simp only with mfld_simps
lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x :=
mem_nhds_sets (ext_chart_at_open_source I x) (mem_ext_chart_source I x)
lemma ext_chart_at_continuous_on :
continuous_on (ext_chart_at I x) (ext_chart_at I x).source :=
begin
refine continuous_on.comp I.continuous.continuous_on _ subset_preimage_univ,
rw ext_chart_at_source,
exact (chart_at H x).continuous_on
end
lemma ext_chart_at_continuous_at :
continuous_at (ext_chart_at I x) x :=
(ext_chart_at_continuous_on I x x (mem_ext_chart_source I x)).continuous_at
(ext_chart_at_source_mem_nhds I x)
lemma ext_chart_at_continuous_on_symm :
continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target :=
begin
apply continuous_on.comp (chart_at H x).continuous_on_symm I.continuous_symm.continuous_on,
simp [ext_chart_at, local_equiv.trans_target]
end
lemma ext_chart_at_target_mem_nhds_within :
(ext_chart_at I x).target ∈ nhds_within ((ext_chart_at I x) x) (range I) :=
begin
rw [ext_chart_at, local_equiv.trans_target],
simp only [function.comp_app, local_equiv.coe_trans, model_with_corners.target],
refine inter_mem_nhds_within _
(mem_nhds_sets (I.continuous_symm _ (chart_at H x).open_target) _),
simp only with mfld_simps
end
lemma ext_chart_at_coe (p : M) : (ext_chart_at I x) p = I ((chart_at H x : M → H) p) := rfl
lemma ext_chart_at_coe_symm (p : E) :
(ext_chart_at I x).symm p = ((chart_at H x).symm : H → M) (I.symm p) := rfl
lemma nhds_within_ext_chart_target_eq :
nhds_within ((ext_chart_at I x) x) (ext_chart_at I x).target =
nhds_within ((ext_chart_at I x) x) (range I) :=
begin
apply le_antisymm,
{ apply nhds_within_mono,
simp only with mfld_simps},
{ apply nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within _ _) }
end
lemma ext_chart_continuous_at_symm' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x') :=
begin
apply continuous_at.comp,
{ rw ext_chart_at_source at h,
simp only with mfld_simps,
exact ((chart_at H x).continuous_on_symm _
((chart_at H x).map_source h)).continuous_at
(mem_nhds_sets (chart_at H x).open_target
((chart_at H x).map_source h)) },
{ exact I.continuous_symm.continuous_at }
end
lemma ext_chart_continuous_at_symm :
continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x) :=
ext_chart_continuous_at_symm' I x (mem_ext_chart_source I x)
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
in the source is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source)
(ht : t ∈ nhds_within x' s) :
(ext_chart_at I x).symm ⁻¹' t ∈ nhds_within ((ext_chart_at I x) x')
((ext_chart_at I x).symm ⁻¹' s ∩ range I) :=
begin
apply (ext_chart_continuous_at_symm' I x h).continuous_within_at.tendsto_nhds_within_image,
rw (ext_chart_at I x).left_inv h,
apply nhds_within_mono _ _ ht,
have : (ext_chart_at I x).symm '' ((ext_chart_at I x).symm ⁻¹' s) ⊆ s :=
image_preimage_subset _ _,
exact subset.trans (image_subset _ (inter_subset_left _ _)) this
end
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of the
base point is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within (ht : t ∈ nhds_within x s) :
(ext_chart_at I x).symm ⁻¹' t ∈ nhds_within ((ext_chart_at I x) x)
((ext_chart_at I x).symm ⁻¹' s ∩ range I) :=
ext_chart_preimage_mem_nhds_within' I x (mem_ext_chart_source I x) ht
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
is a neighborhood of the preimage. -/
lemma ext_chart_preimage_mem_nhds (ht : t ∈ 𝓝 x) :
(ext_chart_at I x).symm ⁻¹' t ∈ 𝓝 ((ext_chart_at I x) x) :=
begin
apply (ext_chart_continuous_at_symm I x).preimage_mem_nhds,
rwa (ext_chart_at I x).left_inv (mem_ext_chart_source _ _)
end
/-- Technical lemma to rewrite suitably the preimage of an intersection under an extended chart, to
bring it into a convenient form to apply derivative lemmas. -/
lemma ext_chart_preimage_inter_eq :
((ext_chart_at I x).symm ⁻¹' (s ∩ t) ∩ range I)
= ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ∩ ((ext_chart_at I x).symm ⁻¹' t) :=
by mfld_set_tac
end extended_charts
/-- In the case of the manifold structure on a vector space, the extended charts are just the
identity.-/
lemma ext_chart_model_space_eq_id (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (x : E) :
ext_chart_at (model_with_corners_self 𝕜 E) x = local_equiv.refl E :=
by simp only with mfld_simps
|
9473539eb2f5c23a8bb43ae9de0c2444f3b35c79 | a537b538f2bea3181e24409d8a52590603d1ddd9 | /src/tidy/command/suggestion.lean | c9a0f568d22d6b1cd8a0371d8d0ae1414b115879 | [] | no_license | rwbarton/lean-tidy | 6134813ded72b275d19d4d32514dba80c21708e3 | fe1125d32adb60decda7a77d0f679614ba9f6fbb | refs/heads/master | 1,585,549,718,705 | 1,538,120,619,000 | 1,538,120,624,000 | 150,864,330 | 0 | 0 | null | 1,538,225,790,000 | 1,538,225,790,000 | null | UTF-8 | Lean | false | false | 566 | lean | import tidy.lib.parser
-- Import the `@[suggest]` attribute definition, since we emit code which uses it.
import tidy.rewrite_search.discovery.suggest
open lean.parser
open interactive
@[user_command]
meta def suggestion_cmd (d : decl_meta_info) (_ : parse $ tk "suggestion") : lean.parser unit := do
bn ← opt_single_or_list ident,
-- Implement option parsing here, e.g:
-- tgt ← optional (tk "at" *> ident),
n ← mk_user_fresh_name "suggestion" "s___",
mk_definition_here_raw n [] none (bn.map $ λ s, "`" ++ to_string s).to_string tt ["suggest"]
|
a6081e0f199b6e32820d3bf29895c87d12fd1c44 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/Group/default.lean | 6ca65b0ef36e4f39398826b3600c70b3ce1b34cc | [
"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 | 153 | lean | import algebra.category.Group.limits
import algebra.category.Group.colimits
import algebra.category.Group.preadditive
import algebra.category.Group.zero
|
0f32139e77754d3a4f2a7fa963a8224080a85bd7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/free_module/basic.lean | da064229d8fdf3717612390adbc546086d8da4d1 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,513 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.direct_sum.finsupp
import logic.small.basic
import linear_algebra.std_basis
import linear_algebra.finsupp_vector_space
import linear_algebra.tensor_product_basis
/-!
# Free modules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We introduce a class `module.free R M`, for `R` a `semiring` and `M` an `R`-module and we provide
several basic instances for this class.
Use `finsupp.total_id_surjective` to prove that any module is the quotient of a free module.
## Main definition
* `module.free R M` : the class of free `R`-modules.
-/
universes u v w z
variables {ι : Type*} (R : Type u) (M : Type v) (N : Type z)
open_locale tensor_product direct_sum big_operators
section basic
variables [semiring R] [add_comm_monoid M] [module R M]
/-- `module.free R M` is the statement that the `R`-module `M` is free.-/
class module.free : Prop :=
(exists_basis [] : nonempty (Σ (I : Type v), basis I R M))
/- If `M` fits in universe `w`, then freeness is equivalent to existence of a basis in that
universe.
Note that if `M` does not fit in `w`, the reverse direction of this implication is still true as
`module.free.of_basis`. -/
lemma module.free_def [small.{w} M] : module.free R M ↔ ∃ (I : Type w), nonempty (basis I R M) :=
⟨ λ h, ⟨shrink (set.range h.exists_basis.some.2),
⟨(basis.reindex_range h.exists_basis.some.2).reindex (equiv_shrink _)⟩⟩,
λ h, ⟨(nonempty_sigma.2 h).map $ λ ⟨i, b⟩, ⟨set.range b, b.reindex_range⟩⟩⟩
lemma module.free_iff_set : module.free R M ↔ ∃ (S : set M), nonempty (basis S R M) :=
⟨λ h, ⟨set.range h.exists_basis.some.2, ⟨basis.reindex_range h.exists_basis.some.2⟩⟩,
λ ⟨S, hS⟩, ⟨nonempty_sigma.2 ⟨S, hS⟩⟩⟩
variables {R M}
lemma module.free.of_basis {ι : Type w} (b : basis ι R M) : module.free R M :=
(module.free_def R M).2 ⟨set.range b, ⟨b.reindex_range⟩⟩
end basic
namespace module.free
section semiring
variables (R M) [semiring R] [add_comm_monoid M] [module R M] [module.free R M]
variables [add_comm_monoid N] [module R N]
/-- If `module.free R M` then `choose_basis_index R M` is the `ι` which indexes the basis
`ι → M`. -/
def choose_basis_index := (exists_basis R M).some.1
/-- If `module.free R M` then `choose_basis : ι → M` is the basis.
Here `ι = choose_basis_index R M`. -/
noncomputable def choose_basis : basis (choose_basis_index R M) R M := (exists_basis R M).some.2
/-- The isomorphism `M ≃ₗ[R] (choose_basis_index R M →₀ R)`. -/
noncomputable def repr : M ≃ₗ[R] (choose_basis_index R M →₀ R) := (choose_basis R M).repr
/-- The universal property of free modules: giving a functon `(choose_basis_index R M) → N`, for `N`
an `R`-module, is the same as giving an `R`-linear map `M →ₗ[R] N`.
This definition is parameterized over an extra `semiring S`,
such that `smul_comm_class R S M'` holds.
If `R` is commutative, you can set `S := R`; if `R` is not commutative,
you can recover an `add_equiv` by setting `S := ℕ`.
See library note [bundled maps over different rings]. -/
noncomputable def constr {S : Type z} [semiring S] [module S N] [smul_comm_class R S N] :
((choose_basis_index R M) → N) ≃ₗ[S] M →ₗ[R] N := basis.constr (choose_basis R M) S
@[priority 100]
instance no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M :=
let ⟨⟨_, b⟩⟩ := exists_basis R M in b.no_zero_smul_divisors
instance [nontrivial M] : nonempty (module.free.choose_basis_index R M) :=
(module.free.choose_basis R M).index_nonempty
variables {R M N}
lemma of_equiv (e : M ≃ₗ[R] N) : module.free R N :=
of_basis $ (choose_basis R M).map e
/-- A variation of `of_equiv`: the assumption `module.free R P` here is explicit rather than an
instance. -/
lemma of_equiv' {P : Type v} [add_comm_monoid P] [module R P] (h : module.free R P)
(e : P ≃ₗ[R] N) : module.free R N :=
of_equiv e
variables (R M N)
/-- The module structure provided by `semiring.to_module` is free. -/
instance self : module.free R R := of_basis (basis.singleton unit R)
instance prod [module.free R N] : module.free R (M × N) :=
of_basis $ (choose_basis R M).prod (choose_basis R N)
/-- The product of finitely many free modules is free. -/
instance pi (M : ι → Type*) [finite ι] [Π (i : ι), add_comm_monoid (M i)]
[Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π i, M i) :=
let ⟨_⟩ := nonempty_fintype ι in by exactI (of_basis $ pi.basis $ λ i, choose_basis R (M i))
/-- The module of finite matrices is free. -/
instance matrix {m n : Type*} [finite m] [finite n] : module.free R (matrix m n M) :=
module.free.pi R _
variables (ι)
/-- The product of finitely many free modules is free (non-dependent version to help with typeclass
search). -/
instance function [finite ι] : module.free R (ι → M) := free.pi _ _
instance finsupp : module.free R (ι →₀ M) :=
of_basis (finsupp.basis $ λ i, choose_basis R M)
variables {ι}
@[priority 100]
instance of_subsingleton [subsingleton N] : module.free R N :=
of_basis (basis.empty N : basis pempty R N)
@[priority 100]
instance of_subsingleton' [subsingleton R] : module.free R N :=
by letI := module.subsingleton R N; exact module.free.of_subsingleton R N
instance dfinsupp {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)]
[Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π₀ i, M i) :=
of_basis $ dfinsupp.basis $ λ i, choose_basis R (M i)
instance direct_sum {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)]
[Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (⨁ i, M i) :=
module.free.dfinsupp R M
end semiring
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
instance tensor : module.free R (M ⊗[R] N) :=
let ⟨bM⟩ := exists_basis R M, ⟨bN⟩ := exists_basis R N in of_basis (bM.2.tensor_product bN.2)
end comm_ring
section division_ring
variables [division_ring R] [add_comm_group M] [module R M]
@[priority 100]
instance of_division_ring : module.free R M :=
of_basis (basis.of_vector_space R M)
end division_ring
end module.free
|
1a5270a5df61814ac13799fb723161b325f1c1d1 | e89c01ae56ce079fecb3cee914e848b44949d055 | /src/impartial.lean | 9a6528343e05271315e9b2fea78035d13716e15d | [] | no_license | foxthomson/impartial | 968fea13b4a88bc59ddb05d764806763c068af8f | 5f8b405dbbd864682f1ccd30ff7504a23bb20a42 | refs/heads/master | 1,670,158,094,446 | 1,597,590,230,000 | 1,597,590,230,000 | 286,443,788 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,234 | lean | import set_theory.pgame
import position
import tactic
import tactic.nth_rewrite.default
universe u
/-!
# Basic deinitions about impartial (pre-)games
We will define an impartial game, one in which left and right can make exactly the same moves.
Our definition differs slightly by saying that the game is always equivilent to its negitve,
no matter what moves are played. This allows for games such as poker-nim to be classifed as
impartial.
-/
namespace pgame
local infix ` ≈ ` := pgame.equiv
/-- The definiton for a impartial game, defined using Conway induction -/
@[class] def impartial : pgame → Prop
| G := G ≈ -G ∧ (∀ i, impartial (G.move_left i)) ∧ (∀ j, impartial (G.move_right j))
using_well_founded {dec_tac := pgame_wf_tac}
@[instance] lemma zero_impartial : impartial 0 := by tidy
@[simp] lemma impartial_def {G : pgame} : G.impartial ↔ G ≈ -G ∧ (∀ i, impartial (G.move_left i)) ∧ (∀ j, impartial (G.move_right j)) :=
begin
split,
{ intro hi,
unfold1 impartial at hi,
exact hi },
{ intro hi,
unfold1 impartial,
exact hi }
end
lemma impartial_neg_equiv_self (G : pgame) [h : G.impartial] : G ≈ -G := (impartial_def.1 h).1
@[instance] lemma impartial_move_left_impartial {G : pgame} [h : G.impartial] (i : G.left_moves) : impartial (G.move_left i) :=
(impartial_def.1 h).2.1 i
@[instance] lemma impartial_move_right_impartial {G : pgame} [h : G.impartial] (j : G.right_moves) : impartial (G.move_right j) :=
(impartial_def.1 h).2.2 j
@[instance] lemma impartial_add : ∀ (G H : pgame) [hG : G.impartial] [hH : H.impartial], (G + H).impartial
| G H :=
begin
introsI hG hH,
rw impartial_def,
split,
{ apply equiv_trans _ (equiv_of_relabelling (neg_add_relabelling G H)).symm,
apply add_congr;
exact impartial_neg_equiv_self _ },
split,
{ intro i,
equiv_rw pgame.left_moves_add G H at i,
cases i with iG iH,
{ rw add_move_left_inl,
exact impartial_add (G.move_left iG) H },
{ rw add_move_left_inr,
exact impartial_add G (H.move_left iH) } },
{ intro j,
equiv_rw pgame.right_moves_add G H at j,
cases j with jG jH,
{ rw add_move_right_inl,
exact impartial_add (G.move_right jG) H },
{ rw add_move_right_inr,
exact impartial_add G (H.move_right jH) } }
end
using_well_founded {dec_tac := pgame_wf_tac}
@[instance] lemma impartial_neg : ∀ (G : pgame) [G.impartial], (-G).impartial
| G :=
begin
introI,
rw impartial_def,
split,
{ rw neg_neg,
symmetry,
exact impartial_neg_equiv_self G },
split,
{ intro i,
equiv_rw G.left_moves_neg at i,
rw move_left_left_moves_neg_symm,
exact impartial_neg (G.move_right i) },
{ intro j,
equiv_rw G.right_moves_neg at j,
rw move_right_right_moves_neg_symm,
exact impartial_neg (G.move_left j) }
end
using_well_founded {dec_tac := pgame_wf_tac}
lemma impartial_position_cases (G : pgame) [G.impartial] : G.p_position ∨ G.n_position :=
begin
rcases G.position_cases with hl | hr | hp | hn,
{ cases hl with hpos hnonneg,
rw ←not_lt at hnonneg,
have hneg := lt_of_lt_of_equiv hpos G.impartial_neg_equiv_self,
rw [lt_iff_neg_gt, neg_neg, neg_zero] at hneg,
contradiction },
{ cases hr with hnonpos hneg,
rw ←not_lt at hnonpos,
have hpos := lt_of_equiv_of_lt G.impartial_neg_equiv_self.symm hneg,
rw [lt_iff_neg_gt, neg_neg, neg_zero] at hpos,
contradiction },
{ left, assumption },
{ right, assumption }
end
lemma impartial_add_self (G : pgame) [G.impartial] : (G + G).p_position :=
p_position_is_zero.2 $ equiv_trans (add_congr G.impartial_neg_equiv_self G.equiv_refl) add_left_neg_equiv
/-- A different way of viewing equivalence. -/
def additive_equiv (G H : pgame) [G.impartial] [H.impartial] : Prop :=
∀ (F : pgame) [F.impartial], (G + F).p_position ↔ (H + F).p_position
lemma additive_equiv_equiv_equiv (G H : pgame) [hG : G.impartial] [hH : H.impartial] : G.additive_equiv H ↔ G ≈ H :=
begin
split,
{ intro heq,
cases G.impartial_position_cases with hGp hGn,
{ specialize heq 0,
rw [p_position_of_equiv_iff G.add_zero_equiv, p_position_of_equiv_iff H.add_zero_equiv, p_position_is_zero, p_position_is_zero] at heq,
rw p_position_is_zero at hGp,
exact equiv_trans hGp (heq.1 hGp).symm },
{ split,
{ rw le_iff_sub_nonneg,
specialize heq (-G),
rw [p_position_of_equiv_iff add_comm_equiv, p_position_of_equiv_iff add_left_neg_equiv] at heq,
exact (heq.1 zero_p_postition).2 },
{ rw le_iff_sub_nonneg,
specialize heq (-H),
nth_rewrite 1 p_position_of_equiv_iff add_comm_equiv at heq,
rw p_position_of_equiv_iff add_left_neg_equiv at heq,
exact (heq.2 zero_p_postition).2 } } },
{ intros heq F hf,
rw [p_position_is_zero, p_position_is_zero],
split,
{ intro hGF,
exact equiv_trans (add_congr heq.symm $ equiv_refl _) hGF },
{ intro hHF,
exact equiv_trans (add_congr heq $ equiv_refl _) hHF } }
end
lemma equiv_iff_sum_p_position (G H : pgame) [G.impartial] [H.impartial] : G ≈ H ↔ (G + H).p_position :=
begin
split,
{ intro heq,
exact p_position_of_equiv (add_congr (equiv_refl _) heq) G.impartial_add_self },
{ intro hGHp,
split,
{ rw le_iff_sub_nonneg,
exact le_trans hGHp.2 (le_trans add_comm_le $ le_of_le_of_equiv (le_refl _) $ add_congr (equiv_refl _) G.impartial_neg_equiv_self) },
{ rw le_iff_sub_nonneg,
exact le_trans hGHp.2 (le_of_le_of_equiv (le_refl _) $ add_congr (equiv_refl _) H.impartial_neg_equiv_self) } }
end
lemma impartial_p_position_symm (G : pgame) [G.impartial] : G.p_position ↔ G ≤ 0 :=
begin
use and.left,
{ intro hneg,
exact ⟨ hneg, zero_le_iff_neg_le_zero.2 (le_of_equiv_of_le (impartial_neg_equiv_self G).symm hneg) ⟩ }
end
lemma impartial_n_position_symm (G : pgame) [G.impartial] : G.n_position ↔ G < 0 :=
begin
use and.right,
{ intro hneg,
split,
rw lt_iff_neg_gt,
rw neg_zero,
exact lt_of_equiv_of_lt G.impartial_neg_equiv_self.symm hneg,
exact hneg }
end
lemma impartial_p_position_symm' (G : pgame) [G.impartial] : G.p_position ↔ 0 ≤ G :=
begin
use and.right,
{ intro hpos,
exact ⟨ le_zero_iff_zero_le_neg.2 $ le_of_le_of_equiv hpos G.impartial_neg_equiv_self, hpos ⟩ }
end
lemma impartial_n_position_symm' (G : pgame) [G.impartial] : G.n_position ↔ 0 < G :=
begin
use and.left,
{ intro hpos,
use hpos,
rw lt_iff_neg_gt,
rw neg_zero,
exact lt_of_lt_of_equiv hpos G.impartial_neg_equiv_self }
end
lemma no_good_left_moves_iff_p_position (G : pgame) [G.impartial] : (∀ (i : G.left_moves), (G.move_left i).n_position) ↔ G.p_position :=
begin
split,
{ intro hbad,
rw [impartial_p_position_symm, le_def_lt],
split,
{ intro i,
specialize hbad i,
exact hbad.2 },
{ intro j,
exact pempty.elim j } },
{ intros hp i,
exact (G.move_left i).impartial_n_position_symm.2 ((le_def_lt.1 $ G.impartial_p_position_symm.1 hp).1 i) }
end
lemma no_good_right_moves_iff_p_position (G : pgame) [G.impartial] : (∀ (j : G.right_moves), (G.move_right j).n_position) ↔ G.p_position :=
begin
split,
{ intro hbad,
rw [impartial_p_position_symm', le_def_lt],
split,
{ intro i,
exact pempty.elim i },
{ intro j,
specialize hbad j,
exact hbad.1 } },
{ intros hp j,
exact (G.move_right j).impartial_n_position_symm'.2 ((le_def_lt.1 $ G.impartial_p_position_symm'.1 hp).2 j) }
end
lemma good_left_move_iff_n_position (G : pgame) [G.impartial] : (∃ (i : G.left_moves), (G.move_left i).p_position) ↔ G.n_position :=
begin
split,
{ rintro ⟨ i, hi ⟩,
exact G.impartial_n_position_symm'.2 (lt_def_le.2 $ or.inl ⟨ i, hi.2 ⟩) },
{ intro hn,
rw [impartial_n_position_symm', lt_def_le] at hn,
rcases hn with ⟨ i, hi ⟩ | ⟨ j, _ ⟩,
{ exact ⟨ i, (G.move_left i).impartial_p_position_symm'.2 hi ⟩ },
{ exact pempty.elim j } }
end
lemma good_right_move_iff_n_position (G : pgame) [G.impartial] : (∃ j : G.right_moves, (G.move_right j).p_position) ↔ G.n_position :=
begin
split,
{ rintro ⟨ j, hj ⟩,
exact G.impartial_n_position_symm.2 (lt_def_le.2 $ or.inr ⟨ j, hj.1 ⟩) },
{ intro hn,
rw [impartial_n_position_symm, lt_def_le] at hn,
rcases hn with ⟨ i, _ ⟩ | ⟨ j, hj ⟩,
{ exact pempty.elim i },
{ exact ⟨ j, (G.move_right j).impartial_p_position_symm.2 hj ⟩ } }
end
end pgame
|
f506d10f85f4b93840273cbd16b6f9db976fa6f0 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/predicate_logic/intro_and_elim_rules/and.lean | 396a3161fcf2e77925fc6c4c006baf7b36eef958 | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 764 | lean | /-
If P and Q are arbitrary propositions, then to prove
P ∧ Q, you need to prove P and to prove Q and then to
form the pair of these proofs to construct a proof of
P ∧ Q.
-/
-- Suppose P and Q are arbitrary propositions
axioms (P Q : Prop)
-- Suppose you have proofs of P and of Q
axioms (p : P) (q : Q)
-- You can now construct a proof of P ∧ Q
#check and.intro p q
/-
Note: Lean provides a nice notation for
and.intro. Use backslash left and right
angle brackets. This notation emphasizes
that a proof of a conjunctions is formed
as a pair of proofs.
-/
lemma pq : P ∧ Q := ⟨ p, q ⟩
/-
The elimination rules for and allow you
to deduce from a proof of P ∧ Q that there
is a proof of P and a proof of Q.
-/
#check pq.left
#check pq.right |
01b36af4080ae7e5769be5c12f06b48c7290a2fb | 42610cc2e5db9c90269470365e6056df0122eaa0 | /hott/types/int/hott.hlean | 36ff46209bc16a84caf6efe6c231c5e464965c83 | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 5,859 | 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
Theorems about the integers specific to HoTT
-/
import .basic types.eq arity algebra.bundled
open core eq is_equiv equiv algebra is_trunc
open nat (hiding pred)
namespace int
section
open algebra
definition group_integers [constructor] : Group :=
Group.mk ℤ (group_of_add_group _)
notation `gℤ` := group_integers
end
definition is_equiv_succ [instance] : is_equiv succ :=
adjointify succ pred (λa, !add_sub_cancel) (λa, !sub_add_cancel)
definition equiv_succ : ℤ ≃ ℤ := equiv.mk succ _
definition is_equiv_neg [instance] : is_equiv (neg : ℤ → ℤ) :=
adjointify neg neg (λx, !neg_neg) (λa, !neg_neg)
definition equiv_neg : ℤ ≃ ℤ := equiv.mk neg _
definition iterate {A : Type} (f : A ≃ A) (a : ℤ) : A ≃ A :=
rec_nat_on a erfl
(λb g, f ⬝e g)
(λb g, g ⬝e f⁻¹ᵉ)
-- definition iterate_trans {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f a ⬝e f = iterate f (a + 1) :=
-- sorry
-- definition trans_iterate {A : Type} (f : A ≃ A) (a : ℤ)
-- : f ⬝e iterate f a = iterate f (a + 1) :=
-- sorry
-- definition iterate_trans_symm {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f a ⬝e f⁻¹e = iterate f (a - 1) :=
-- sorry
-- definition symm_trans_iterate {A : Type} (f : A ≃ A) (a : ℤ)
-- : f⁻¹e ⬝e iterate f a = iterate f (a - 1) :=
-- sorry
-- definition iterate_neg {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f (-a) = (iterate f a)⁻¹e :=
-- rec_nat_on a idp
-- (λn p, calc
-- iterate f (-succ n) = iterate f (-n) ⬝e f⁻¹e : rec_nat_on_neg
-- ... = (iterate f n)⁻¹e ⬝e f⁻¹e : by rewrite p
-- ... = (f ⬝e iterate f n)⁻¹e : sorry
-- ... = (iterate f (succ n))⁻¹e : idp)
-- sorry
-- definition iterate_add {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a + b) = equiv.trans (iterate f a) (iterate f b) :=
-- sorry
-- definition iterate_sub {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a - b) = equiv.trans (iterate f a) (equiv.symm (iterate f b)) :=
-- sorry
-- definition iterate_mul {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a * b) = iterate (iterate f a) b :=
-- sorry
end int open int
namespace eq
variables {A : Type} {a : A} (p : a = a) (b c : ℤ) (n : ℕ)
definition power : a = a :=
rec_nat_on b idp
(λc q, q ⬝ p)
(λc q, q ⬝ p⁻¹)
--iterate (equiv_eq_closed_right p a) b idp
-- definition power_neg_succ (n : ℕ) : power p (-succ n) = power p (-n) ⬝ p⁻¹ :=
-- !rec_nat_on_neg
-- local attribute nat.add int.add int.of_num nat.of_num int.succ [constructor]
definition power_con : power p b ⬝ p = power p (succ b) :=
rec_nat_on b
idp
(λn IH, idp)
(λn IH, calc
power p (-succ n) ⬝ p
= (power p (-int.of_nat n) ⬝ p⁻¹) ⬝ p : by krewrite [↑power,rec_nat_on_neg]
... = power p (-int.of_nat n) : inv_con_cancel_right
... = power p (succ (-succ n)) : by rewrite -succ_neg_succ)
definition power_con_inv : power p b ⬝ p⁻¹ = power p (pred b) :=
rec_nat_on b
idp
(λn IH, calc
power p (succ n) ⬝ p⁻¹ = power p n : by apply con_inv_cancel_right
... = power p (pred (succ n)) : by rewrite pred_nat_succ)
(λn IH, calc
power p (-int.of_nat (succ n)) ⬝ p⁻¹
= power p (-int.of_nat (succ (succ n))) : by krewrite [↑power,*rec_nat_on_neg]
... = power p (pred (-succ n)) : by rewrite -neg_succ)
definition con_power : p ⬝ power p b = power p (succ b) :=
rec_nat_on b
( by rewrite ↑[power];exact !idp_con⁻¹)
( λn IH, proof calc
p ⬝ power p (succ n) = (p ⬝ power p n) ⬝ p : con.assoc p _ p
... = power p (succ (succ n)) : by rewrite IH qed)
( λn IH, calc
p ⬝ power p (-int.of_nat (succ n))
= p ⬝ (power p (-int.of_nat n) ⬝ p⁻¹) : by rewrite [↑power, rec_nat_on_neg]
... = (p ⬝ power p (-int.of_nat n)) ⬝ p⁻¹ : con.assoc
... = power p (succ (-int.of_nat n)) ⬝ p⁻¹ : by rewrite IH
... = power p (pred (succ (-int.of_nat n))) : power_con_inv
... = power p (succ (-int.of_nat (succ n))) : by rewrite [succ_neg_nat_succ,int.pred_succ])
definition inv_con_power : p⁻¹ ⬝ power p b = power p (pred b) :=
rec_nat_on b
( by rewrite ↑[power];exact !idp_con⁻¹)
(λn IH, calc
p⁻¹ ⬝ power p (succ n) = p⁻¹ ⬝ power p n ⬝ p : con.assoc
... = power p (pred n) ⬝ p : by rewrite IH
... = power p (succ (pred n)) : power_con
... = power p (pred (succ n)) : by rewrite [succ_pred,-int.pred_succ n])
( λn IH, calc
p⁻¹ ⬝ power p (-int.of_nat (succ n))
= p⁻¹ ⬝ (power p (-int.of_nat n) ⬝ p⁻¹) : by rewrite [↑power,rec_nat_on_neg]
... = (p⁻¹ ⬝ power p (-int.of_nat n)) ⬝ p⁻¹ : con.assoc
... = power p (pred (-int.of_nat n)) ⬝ p⁻¹ : by rewrite IH
... = power p (-int.of_nat (succ n)) ⬝ p⁻¹ : by rewrite -neg_succ
... = power p (-succ (succ n)) : by krewrite [↑power,*rec_nat_on_neg]
... = power p (pred (-succ n)) : by rewrite -neg_succ)
definition power_con_power : Π(b : ℤ), power p b ⬝ power p c = power p (b + c) :=
rec_nat_on c
(λb, by rewrite int.add_zero)
(λn IH b, by rewrite [-con_power,-con.assoc,power_con,IH,↑succ,add.assoc,
add.comm (int.of_nat n)])
(λn IH b, by rewrite [neg_nat_succ,-inv_con_power,-con.assoc,power_con_inv,IH,↑pred,
+sub_eq_add_neg,add.assoc,add.comm (-n)])
end eq
|
8dcbe3a970525ca8d02cd504d9a340717442215d | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/conj.lean | 3e8c38feca61c8f4773b529f08aa8aec3bc8f932 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 5,728 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import category_theory.endomorphism
import algebra.group_power
/-!
# Conjugate morphisms by isomorphisms
An isomorphism `α : X ≅ Y` defines
- a monoid isomorphism `conj : End X ≃* End Y` by `α.conj f = α.inv ≫ f ≫ α.hom`;
- a group isomorphism `conj_Aut : Aut X ≃* Aut Y` by `α.conj_Aut f = α.symm ≪≫ f ≪≫ α`.
For completeness, we also define `hom_congr : (X ≅ X₁) → (Y ≅ Y₁) → (X ⟶ Y) ≃ (X₁ ⟶ Y₁)`, cf. `equiv.arrow_congr`.
-/
universes v u
namespace category_theory
namespace iso
variables {C : Type u} [category.{v} C]
/-- If `X` is isomorphic to `X₁` and `Y` is isomorphic to `Y₁`, then
there is a natural bijection between `X ⟶ Y` and `X₁ ⟶ Y₁`. See also `equiv.arrow_congr`. -/
def hom_congr {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) :
(X ⟶ Y) ≃ (X₁ ⟶ Y₁) :=
{ to_fun := λ f, α.inv ≫ f ≫ β.hom,
inv_fun := λ f, α.hom ≫ f ≫ β.inv,
left_inv := λ f, show α.hom ≫ (α.inv ≫ f ≫ β.hom) ≫ β.inv = f,
by rw [category.assoc, category.assoc, β.hom_inv_id, α.hom_inv_id_assoc, category.comp_id],
right_inv := λ f, show α.inv ≫ (α.hom ≫ f ≫ β.inv) ≫ β.hom = f,
by rw [category.assoc, category.assoc, β.inv_hom_id, α.inv_hom_id_assoc, category.comp_id] }
lemma hom_congr_apply {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) :
α.hom_congr β f = α.inv ≫ f ≫ β.hom :=
rfl
lemma hom_congr_comp {X Y Z X₁ Y₁ Z₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁)
(f : X ⟶ Y) (g : Y ⟶ Z) :
α.hom_congr γ (f ≫ g) = (α.hom_congr β f) ≫ (hom_congr β γ g) :=
by simp only [hom_congr_apply, category.assoc, β.hom_inv_id_assoc]
@[simp] lemma hom_congr_refl {X Y : C} (f : X ⟶ Y) :
(iso.refl X).hom_congr (iso.refl Y) f = f :=
by simp only [hom_congr_apply, iso.refl, category.comp_id, category.id_comp]
@[simp] lemma hom_congr_trans {X₁ Y₁ X₂ Y₂ X₃ Y₃ : C}
(α₁ : X₁ ≅ X₂) (β₁ : Y₁ ≅ Y₂) (α₂ : X₂ ≅ X₃) (β₂ : Y₂ ≅ Y₃) (f : X₁ ⟶ Y₁) :
(α₁ ≪≫ α₂).hom_congr (β₁ ≪≫ β₂) f = (α₁.hom_congr β₁).trans (α₂.hom_congr β₂) f :=
by simp only [hom_congr_apply, equiv.trans_apply, iso.trans, category.assoc]
@[simp] lemma hom_congr_symm {X₁ Y₁ X₂ Y₂ : C} (α : X₁ ≅ X₂) (β : Y₁ ≅ Y₂) :
(α.hom_congr β).symm = α.symm.hom_congr β.symm :=
rfl
variables {X Y : C} (α : X ≅ Y)
/-- An isomorphism between two objects defines a monoid isomorphism between their
monoid of endomorphisms. -/
def conj : End X ≃* End Y :=
{ map_mul' := λ f g, hom_congr_comp α α α g f,
.. hom_congr α α }
lemma conj_apply (f : End X) : α.conj f = α.inv ≫ f ≫ α.hom := rfl
@[simp] lemma conj_comp (f g : End X) : α.conj (f ≫ g) = (α.conj f) ≫ (α.conj g) :=
α.conj.map_mul g f
@[simp] lemma conj_id : α.conj (𝟙 X) = 𝟙 Y :=
α.conj.map_one
@[simp] lemma refl_conj (f : End X) : (iso.refl X).conj f = f :=
by rw [conj_apply, iso.refl_inv, iso.refl_hom, category.id_comp, category.comp_id]
@[simp] lemma trans_conj {Z : C} (β : Y ≅ Z) (f : End X) : (α ≪≫ β).conj f = β.conj (α.conj f) :=
hom_congr_trans α α β β f
@[simp] lemma symm_self_conj (f : End X) : α.symm.conj (α.conj f) = f :=
by rw [← trans_conj, α.self_symm_id, refl_conj]
@[simp] lemma self_symm_conj (f : End Y) : α.conj (α.symm.conj f) = f :=
α.symm.symm_self_conj f
@[simp] lemma conj_pow (f : End X) (n : ℕ) : α.conj (f^n) = (α.conj f)^n :=
α.conj.to_monoid_hom.map_pow f n
/-- `conj` defines a group isomorphisms between groups of automorphisms -/
def conj_Aut : Aut X ≃* Aut Y :=
(Aut.units_End_equiv_Aut X).symm.trans $
(units.map_equiv α.conj).trans $
Aut.units_End_equiv_Aut Y
lemma conj_Aut_apply (f : Aut X) : α.conj_Aut f = α.symm ≪≫ f ≪≫ α :=
by cases f; cases α; ext; refl
@[simp] lemma conj_Aut_hom (f : Aut X) : (α.conj_Aut f).hom = α.conj f.hom := rfl
@[simp] lemma trans_conj_Aut {Z : C} (β : Y ≅ Z) (f : Aut X) :
(α ≪≫ β).conj_Aut f = β.conj_Aut (α.conj_Aut f) :=
by simp only [conj_Aut_apply, iso.trans_symm, iso.trans_assoc]
@[simp] lemma conj_Aut_mul (f g : Aut X) : α.conj_Aut (f * g) = α.conj_Aut f * α.conj_Aut g :=
α.conj_Aut.map_mul f g
@[simp] lemma conj_Aut_trans (f g : Aut X) : α.conj_Aut (f ≪≫ g) = α.conj_Aut f ≪≫ α.conj_Aut g :=
conj_Aut_mul α g f
@[simp] lemma conj_Aut_pow (f : Aut X) (n : ℕ) : α.conj_Aut (f^n) = (α.conj_Aut f)^n :=
α.conj_Aut.to_monoid_hom.map_pow f n
@[simp] lemma conj_Aut_gpow (f : Aut X) (n : ℤ) : α.conj_Aut (f^n) = (α.conj_Aut f)^n :=
α.conj_Aut.to_monoid_hom.map_gpow f n
end iso
namespace functor
universes v₁ u₁
variables {C : Type u} [category.{v} C] {D : Type u₁} [category.{v₁} D] (F : C ⥤ D)
lemma map_hom_congr {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) :
F.map (iso.hom_congr α β f) = iso.hom_congr (F.map_iso α) (F.map_iso β) (F.map f) :=
by simp only [iso.hom_congr_apply, F.map_comp, F.map_iso_inv, F.map_iso_hom]
lemma map_conj {X Y : C} (α : X ≅ Y) (f : End X) :
F.map (α.conj f) = (F.map_iso α).conj (F.map f) :=
map_hom_congr F α α f
lemma map_conj_Aut (F : C ⥤ D) {X Y : C} (α : X ≅ Y) (f : Aut X) :
F.map_iso (α.conj_Aut f) = (F.map_iso α).conj_Aut (F.map_iso f) :=
by ext; simp only [map_iso_hom, iso.conj_Aut_hom, F.map_conj]
-- alternative proof: by simp only [iso.conj_Aut_apply, F.map_iso_trans, F.map_iso_symm]
end functor
end category_theory
|
fa5e3616139fcbf2515bcd6d562b7f02886aed7f | da3a76c514d38801bae19e8a9e496dc31f8e5866 | /tests/lean/run/basic_monitor3.lean | 1efcab3ae673024e5f302646f7357d0116b82909 | [
"Apache-2.0"
] | permissive | cipher1024/lean | 270c1ac5781e6aee12f5c8d720d267563a164beb | f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a | refs/heads/master | 1,611,223,459,029 | 1,487,566,573,000 | 1,487,566,573,000 | 83,356,543 | 0 | 0 | null | 1,488,229,336,000 | 1,488,229,336,000 | null | UTF-8 | Lean | false | false | 1,636 | lean | meta def get_file (fn : name) : vm format :=
do {
d ← vm.get_decl fn,
some n ← return (vm_decl.olean d) | failure,
return (to_fmt n)
}
<|>
return (to_fmt "<curr file>")
meta def pos_info (fn : name) : vm format :=
do {
d ← vm.get_decl fn,
some (line, col) ← return (vm_decl.pos d) | failure,
file ← get_file fn,
return (file ++ ":" ++ line ++ ":" ++ col)
}
<|>
return (to_fmt "<position not available>")
meta def obj_fmt (o : vm_obj) : vm format :=
match o^.kind with
| vm_obj_kind.tactic_state :=
return (to_fmt "state:" ++ format.nest 8 (format.line ++ o^.to_tactic_state^.to_format))
| _ := do s ← vm.obj_to_string o, return $ to_fmt s
end
meta def display_args_aux : nat → vm unit
| i := do
sz ← vm.stack_size,
if i = sz then return ()
else do
o ← vm.stack_obj i,
(n, t) ← vm.stack_obj_info i,
fmt ← obj_fmt o,
vm.trace (to_fmt " " ++ to_fmt n ++ " := " ++ fmt),
display_args_aux (i+1)
meta def display_args : vm unit :=
do bp ← vm.bp,
display_args_aux bp
meta def basic_monitor : vm_monitor nat :=
{ init := 1000,
step := λ sz, do
csz ← vm.call_stack_size,
if sz = csz then return sz
else
do {
fn ← vm.curr_fn,
pos ← pos_info fn,
vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos),
display_args,
return csz
}
<|>
return csz -- curr_fn failed
}
run_command vm_monitor.register `basic_monitor
set_option debugger true
open tactic
example (a b : Prop) : a → b → a ∧ b :=
by (intros >> constructor >> repeat assumption)
|
0564b3ba3a87b906553ee6427cf8288619f4f818 | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/algebra/group_with_zero.lean | 521eadc81f03b3d1ca2f24cae0d4f5cd11411e0c | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,659 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group.units
/-!
# G₀roups with an adjoined zero element
This file describes structures that are not usually studied on their own right in mathematics,
namely a special sort of monoid: apart from a distinguished “zero element” they form a group,
or in other words, they are groups with an adjoined zero element.
Examples are:
* division rings;
* the value monoid of a multiplicative valuation;
* in particular, the non-negative real numbers.
## Main definitions
* `group_with_zero`
* `comm_group_with_zero`
## Implementation details
As is usual in mathlib, we extend the inverse function to the zero element,
and require `0⁻¹ = 0`.
-/
set_option old_structure_cmd true
section prio
set_option default_priority 10 -- see Note [default priority]
/-- A type `M` is a “monoid with zero” if it is a monoid with zero element. -/
class monoid_with_zero (G₀ : Type*) extends monoid G₀, mul_zero_class G₀.
/-- A type `M` is a commutative “monoid with zero”
if it is a commutative monoid with zero element. -/
class comm_monoid_with_zero (G₀ : Type*) extends monoid G₀, mul_zero_class G₀.
/-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`.
Examples include division rings and the ordered monoids that are the
target of valuations in general valuation theory.-/
class group_with_zero (G₀ : Type*)
extends monoid_with_zero G₀, has_inv G₀, zero_ne_one_class G₀ :=
(inv_zero : (0 : G₀)⁻¹ = 0)
(mul_inv_cancel : ∀ a:G₀, a ≠ 0 → a * a⁻¹ = 1)
/-- A type `G₀` is a commutative “group with zero”
if it is a commutative monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/
class comm_group_with_zero (G₀ : Type*) extends comm_monoid G₀, group_with_zero G₀.
/-- The division operation on a group with zero element. -/
instance group_with_zero.has_div {G₀ : Type*} [group_with_zero G₀] :
has_div G₀ := ⟨λ g h, g * h⁻¹⟩
end prio
lemma div_eq_mul_inv {G₀ : Type*} [group_with_zero G₀] {a b : G₀} :
a / b = a * b⁻¹ := rfl
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
@[simp] lemma inv_zero' : (0 : G₀)⁻¹ = 0 :=
group_with_zero.inv_zero G₀
@[simp] lemma mul_inv_cancel' (a : G₀) (h : a ≠ 0) : a * a⁻¹ = 1 :=
group_with_zero.mul_inv_cancel a h
@[simp] lemma mul_inv_cancel_assoc_left (a b : G₀) (h : b ≠ 0) :
(a * b) * b⁻¹ = a :=
calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma mul_inv_cancel_assoc_right (a b : G₀) (h : a ≠ 0) :
a * (a⁻¹ * b) = b :=
calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
lemma inv_ne_zero' {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 :=
assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel' a h
@[simp] lemma inv_mul_cancel' (a : G₀) (h : a ≠ 0) : a⁻¹ * a = 1 :=
calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero' h]
... = a⁻¹ * a⁻¹⁻¹ : by simp [h]
... = 1 : by simp [inv_ne_zero' h]
@[simp] lemma inv_mul_cancel_assoc_left (a b : G₀) (h : b ≠ 0) :
(a * b⁻¹) * b = a :=
calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma inv_mul_cancel_assoc_right (a b : G₀) (h : a ≠ 0) :
a⁻¹ * (a * b) = b :=
calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
@[simp] lemma inv_inv'' (a : G₀) : a⁻¹⁻¹ = a :=
begin
classical,
by_cases h : a = 0, { simp [h] },
calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h]
... = a : by simp [inv_ne_zero' h]
end
lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) :=
inv_inv''
lemma ne_zero_of_mul_right_eq_one' (a b : G₀) (h : a * b = 1) : a ≠ 0 :=
assume a_eq_0, zero_ne_one (by simpa [a_eq_0] using h : (0:G₀) = 1)
lemma ne_zero_of_mul_left_eq_one' (a b : G₀) (h : a * b = 1) : b ≠ 0 :=
assume b_eq_0, zero_ne_one (by simpa [b_eq_0] using h : (0:G₀) = 1)
lemma eq_inv_of_mul_right_eq_one' (a b : G₀) (h : a * b = 1) :
b = a⁻¹ :=
calc b = a⁻¹ * (a * b) :
(inv_mul_cancel_assoc_right _ _ $ ne_zero_of_mul_right_eq_one' a b h).symm
... = a⁻¹ : by simp [h]
lemma eq_inv_of_mul_left_eq_one' (a b : G₀) (h : a * b = 1) :
a = b⁻¹ :=
calc a = (a * b) * b⁻¹ : (mul_inv_cancel_assoc_left _ _ (ne_zero_of_mul_left_eq_one' a b h)).symm
... = b⁻¹ : by simp [h]
@[simp] lemma inv_one' : (1 : G₀)⁻¹ = 1 :=
eq.symm $ eq_inv_of_mul_right_eq_one' _ _ (mul_one 1)
lemma inv_injective' : function.injective (@has_inv.inv G₀ _) :=
inv_involutive'.injective
@[simp] lemma inv_inj'' (g h : G₀) :
g⁻¹ = h⁻¹ ↔ g = h :=
⟨assume H, inv_injective' H, congr_arg _⟩
lemma inv_eq_iff {g h : G₀} : g⁻¹ = h ↔ h⁻¹ = g :=
by rw [← inv_inj'', eq_comm, inv_inv'']
@[simp] lemma coe_unit_mul_inv' (a : units G₀) : (a : G₀) * a⁻¹ = 1 :=
mul_inv_cancel' _ $ ne_zero_of_mul_right_eq_one' _ (a⁻¹ : units G₀) $ by simp
@[simp] lemma coe_unit_inv_mul' (a : units G₀) : (a⁻¹ : G₀) * a = 1 :=
inv_mul_cancel' _ $ ne_zero_of_mul_right_eq_one' _ (a⁻¹ : units G₀) $ by simp
@[simp] lemma unit_ne_zero (a : units G₀) : (a : G₀) ≠ 0 :=
assume a_eq_0, zero_ne_one $
calc 0 = (a : G₀) * a⁻¹ : by simp [a_eq_0]
... = 1 : by simp
end group_with_zero
namespace units
variables {G₀ : Type*} [group_with_zero G₀]
variables {a b : G₀}
/-- Embed a non-zero element of a `group_with_zero` into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ :=
⟨a, a⁻¹, mul_inv_cancel' _ ha, inv_mul_cancel' _ ha⟩
@[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl
@[simp] theorem inv_eq_inv (u : units G₀) : (↑u⁻¹ : G₀) = u⁻¹ :=
(mul_left_inj u).1 $ by { rw [units.mul_inv, mul_inv_cancel'], apply unit_ne_zero }
@[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u :=
units.ext rfl
@[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
end units
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
lemma mul_eq_zero' (a b : G₀) (h : a * b = 0) : a = 0 ∨ b = 0 :=
begin
classical, contrapose! h,
exact unit_ne_zero ((units.mk0 a h.1) * (units.mk0 b h.2))
end
section prio
set_option default_priority 10 -- see Note [default priority]
instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mul_eq_zero',
.. (‹_› : group_with_zero G₀) }
end prio
@[simp] lemma mul_eq_zero_iff' {a b : G₀} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨mul_eq_zero' a b, by rintro (H|H); simp [H]⟩
lemma mul_ne_zero'' {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
begin
assume ab0, rw mul_eq_zero_iff' at ab0,
cases ab0; contradiction
end
lemma mul_ne_zero_iff {a b : G₀} : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
by { classical, rw ← not_iff_not, push_neg, exact mul_eq_zero_iff' }
lemma mul_left_cancel' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : x * y = x * z) : y = z :=
calc y = x⁻¹ * (x * y) : by rw inv_mul_cancel_assoc_right _ _ hx
... = x⁻¹ * (x * z) : by rw h
... = z : by rw inv_mul_cancel_assoc_right _ _ hx
lemma mul_right_cancel' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y * x = z * x) : y = z :=
calc y = (y * x) * x⁻¹ : by rw mul_inv_cancel_assoc_left _ _ hx
... = (z * x) * x⁻¹ : by rw h
... = z : by rw mul_inv_cancel_assoc_left _ _ hx
lemma mul_inv_eq_of_eq_mul' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y * x⁻¹ = z :=
h.symm ▸ (mul_inv_cancel_assoc_left z x hx)
lemma eq_mul_inv_of_mul_eq' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y * x⁻¹ :=
eq.symm $ mul_inv_eq_of_eq_mul' hx h.symm
lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
classical,
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
symmetry,
apply eq_inv_of_mul_left_eq_one',
simp [mul_assoc, hx, hy]
end
theorem inv_comm_of_comm' {a b : G₀} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ :=
begin
have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ :=
congr_arg (λ x:G₀, a⁻¹ * x * a⁻¹) H.symm,
classical,
by_cases h : a = 0, { rw [h, inv_zero', zero_mul, mul_zero] },
rwa [inv_mul_cancel_assoc_right _ _ h, mul_assoc, mul_inv_cancel_assoc_left _ _ h] at this,
end
@[simp] lemma div_self' {a : G₀} (h : a ≠ 0) : a / a = 1 := mul_inv_cancel' _ h
@[simp] lemma div_one' (a : G₀) : a / 1 = a :=
show a * 1⁻¹ = a, by rw [inv_one', mul_one]
lemma one_div (a : G₀) : 1 / a = a⁻¹ := one_mul _
@[simp] lemma zero_div' (a : G₀) : 0 / a = 0 := zero_mul _
@[simp] lemma div_zero' (a : G₀) : a / 0 = 0 :=
show a * 0⁻¹ = 0, by rw [inv_zero', mul_zero]
@[simp] lemma div_mul_cancel' (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a :=
inv_mul_cancel_assoc_left a b h
@[simp] lemma mul_div_cancel'' (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a :=
mul_inv_cancel_assoc_left a b h
lemma mul_div_assoc'' {a b c : G₀} : a * b / c = a * (b / c) :=
mul_assoc _ _ _
local attribute [simp]
div_eq_mul_inv mul_comm mul_assoc
mul_left_comm mul_inv_cancel inv_mul_cancel
lemma div_eq_mul_one_div' (a b : G₀) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel' {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel' {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma one_div_one' : 1 / 1 = (1:G₀) :=
div_self' (ne.symm zero_ne_one)
lemma one_div_ne_zero' {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 :=
assume : 1 / a = 0,
have 0 = (1:G₀), from eq.symm (by rw [← mul_one_div_cancel' h, this, mul_zero]),
absurd this zero_ne_one
lemma mul_ne_zero_comm'' {a b : G₀} (h : a * b ≠ 0) : b * a ≠ 0 :=
by { rw mul_ne_zero_iff at h ⊢, rwa and_comm }
lemma eq_one_div_of_mul_eq_one' {a b : G₀} (h : a * b = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:G₀), by rwa [this, zero_mul] at h,
absurd this zero_ne_one,
have b = (1 / a) * a * b, by rw [one_div_mul_cancel' this, one_mul],
show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this
lemma eq_one_div_of_mul_eq_one_left' {a b : G₀} (h : b * a = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:G₀), by rwa [this, mul_zero] at h,
absurd this zero_ne_one,
by rw [← h, mul_div_assoc'', div_self' this, mul_one]
@[simp] lemma one_div_div' (a b : G₀) : 1 / (a / b) = b / a :=
by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv'', div_eq_mul_inv]
@[simp] lemma one_div_one_div' (a : G₀) : 1 / (1 / a) = a :=
by simp
lemma eq_of_one_div_eq_one_div' {a b : G₀} (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div' a, h, one_div_one_div']
end group_with_zero
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
variables {a b c : G₀}
@[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 :=
by rw [inv_eq_iff, inv_zero', eq_comm]
lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) :=
by simp only [div_eq_mul_inv, one_mul, mul_inv_rev']
theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u :=
congr_arg _ $ units.inv_eq_inv _
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div : (a / b)⁻¹ = b / a :=
(mul_inv_rev' _ _).trans (by rw inv_inv''; refl)
lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ :=
(mul_inv_rev' _ _).symm
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
mul_ne_zero'' ha (inv_ne_zero' hb)
lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 :=
⟨mt (λ h, by rw [h, zero_div']), λ ha, div_ne_zero ha hb⟩
lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 :=
by haveI := classical.prop_decidable; exact
not_iff_not.1 (div_ne_zero_iff hb)
lemma div_right_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj]
lemma mul_right_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b :=
by rw [← inv_inv'' c, ← div_eq_mul_inv, ← div_eq_mul_inv, div_right_inj' (inv_ne_zero' hc)]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel' _ hb],
λ h, by rw [← h, mul_div_cancel'' _ hb]⟩
end group_with_zero
section comm_group_with_zero -- comm
variables {G₀ : Type*} [comm_group_with_zero G₀] {a b c : G₀}
lemma mul_inv'' : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev', mul_comm]
lemma one_div_mul_one_div' (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div_rev, mul_comm b]
lemma div_mul_right' {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
eq.symm (calc
1 / b = a * ((1 / a) * (1 / b)) : by rw [← mul_assoc, one_div a, mul_inv_cancel' a ha, one_mul]
... = a * (1 / (b * a)) : by rw one_div_mul_one_div_rev
... = a * (a * b)⁻¹ : by rw [← one_div, mul_comm a b])
lemma div_mul_left' {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by rw [mul_comm a, div_mul_right' _ hb]
lemma mul_div_cancel_left' {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b :=
by rw [mul_comm a, (mul_div_cancel'' _ ha)]
lemma mul_div_cancel''' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel' _ hb)]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div' (a b c d : G₀) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by { simp [div_eq_mul_inv], rw [mul_inv_rev', mul_comm d⁻¹] }
lemma mul_div_mul_left' (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [← div_mul_div', div_self' hc, one_mul]
lemma mul_div_mul_right' (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by rw [mul_comm a, mul_comm b, mul_div_mul_left' _ _ hc]
lemma div_mul_eq_mul_div' (a b c : G₀) : (b / c) * a = (b * a) / c :=
by simp [div_eq_mul_inv]
lemma div_mul_eq_mul_div_comm' (a b c : G₀) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div', ← one_mul c, ← div_mul_div',
div_one', one_mul]
lemma mul_eq_mul_of_div_eq_div' (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self' hb,
← div_mul_eq_mul_div_comm', h, div_mul_eq_mul_div', div_mul_cancel' _ hd]
lemma div_div_eq_mul_div' (a b c : G₀) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div', one_div_div', ← mul_div_assoc'']
lemma div_div_eq_div_mul' (a b c : G₀) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div', div_mul_div', mul_one]
lemma div_div_div_div_eq' (a : G₀) {b c d : G₀} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div', div_mul_eq_mul_div', div_div_eq_div_mul']
lemma div_mul_eq_div_mul_one_div' (a b c : G₀) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul', ← div_eq_mul_one_div']
lemma eq_of_mul_eq_mul_of_nonzero_left' {a b c : G₀} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c :=
by rw [← one_mul b, ← div_self' h, div_mul_eq_mul_div', h₂, mul_div_cancel_left' _ h]
lemma eq_of_mul_eq_mul_of_nonzero_right' {a b c : G₀} (h : c ≠ 0) (h2 : a * c = b * c) : a = b :=
by rw [← mul_one a, ← div_self' h, ← mul_div_assoc'', h2, mul_div_cancel'' _ h]
lemma ne_zero_of_one_div_ne_zero' {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero'] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero' {a : G₀} (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, false.elim ((one_div_ne_zero' ha) h))
lemma div_helper' {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div', one_mul, div_mul_right' _ h]
end comm_group_with_zero
section comm_group_with_zero
variables {G₀ : Type*} [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_eq_inv_mul' : a / b = b⁻¹ * a := mul_comm _ _
lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b :=
by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc]; refl
lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc'', mul_div_right_comm]
lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div', mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc'', mul_comm, mul_div_assoc'']
lemma div_right_comm' (a : G₀) : (a / b) / c = (a / c) / b :=
by rw [div_div_eq_div_mul', div_div_eq_div_mul', mul_comm]
lemma div_div_div_cancel_right' (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div', div_mul_cancel' _ hc]
lemma div_mul_div_cancel' (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc'', div_mul_cancel' _ hc]
lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) :
by rw [mul_right_inj' (mul_ne_zero'' hb hd)]
... ↔ a * d = c * b :
by rw [← mul_assoc, div_mul_cancel' _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel' _ hd]
lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero
lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div, mul_div_cancel''' _ ha]
end comm_group_with_zero
|
7e029cbf5d1b5e422aa21421d46145fdcbcedb5d | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/finmap.lean | 60fd7350336149f25614cb3371cb86cccf79f4a0 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 11,290 | lean | /-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
Finite maps over `multiset`.
-/
import data.list.alist data.finset data.pfun
universes u v w
open list
variables {α : Type u} {β : α → Type v}
namespace multiset
/-- Multiset of keys of an association multiset. -/
def keys (s : multiset (sigma β)) : multiset α :=
s.map sigma.fst
@[simp] theorem coe_keys {l : list (sigma β)} :
keys (l : multiset (sigma β)) = (l.keys : multiset α) :=
rfl
/-- `nodupkeys s` means that `s` has no duplicate keys. -/
def nodupkeys (s : multiset (sigma β)) : Prop :=
quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p)
@[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl
end multiset
/-- `finmap β` is the type of finite maps over a multiset. It is effectively
a quotient of `alist β` by permutation of the underlying list. -/
structure finmap (β : α → Type v) : Type (max u v) :=
(entries : multiset (sigma β))
(nodupkeys : entries.nodupkeys)
/-- The quotient map from `alist` to `finmap`. -/
def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩
local notation `⟦`:max a `⟧`:0 := alist.to_finmap a
theorem alist.to_finmap_eq {s₁ s₂ : alist β} :
⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries :=
by cases s₁; cases s₂; simp [alist.to_finmap]
@[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl
namespace finmap
open alist
/-- Lift a permutation-respecting function on `alist` to `finmap`. -/
@[elab_as_eliminator] def lift_on
{γ} (s : finmap β) (f : alist β → γ)
(H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ :=
begin
refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ))
(λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _,
{ exact λ h₁ h₂, H _ _ (by exact p) },
{ have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id }
end
@[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) :
lift_on ⟦s⟧ f H = f s := by cases s; refl
/-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/
@[elab_as_eliminator] def lift_on₂
{γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ)
(H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ :=
lift_on s₁
(λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p))
(λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H'])
@[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) :
lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ :=
by cases s₁; cases s₂; refl
@[elab_as_eliminator] theorem induction_on
{C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s :=
by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩
@[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop}
(s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ :=
induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂
@[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop}
(s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ :=
induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃
@[extensionality] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t
| ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr'
@[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t :=
⟨ext, congr_arg _⟩
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩
theorem mem_def {a : α} {s : finmap β} :
a ∈ s ↔ a ∈ s.entries.keys := iff.rfl
@[simp] theorem mem_to_finmap {a : α} {s : alist β} :
a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl
/-- The set of keys of a finite map. -/
def keys (s : finmap β) : finset α :=
⟨s.entries.keys, induction_on s keys_nodup⟩
@[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl
@[simp] theorem keys_ext {s₁ s₂ : alist β} :
keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys :=
by simp [keys, alist.keys]
theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s :=
induction_on s $ λ s, alist.mem_keys
/-- The empty map. -/
instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩
@[simp] theorem empty_to_finmap (s : alist β) :
(⟦∅⟧ : finmap β) = ∅ := rfl
theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) :=
multiset.not_mem_zero a
@[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl
/-- The singleton map. -/
def singleton (a : α) (b : β a) : finmap β :=
⟨⟨a, b⟩::0, nodupkeys_singleton _⟩
@[simp] theorem keys_singleton (a : α) (b : β a) :
(singleton a b).keys = finset.singleton a := rfl
variables [decidable_eq α]
instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β)
| s₁ s₂ := decidable_of_iff _ ext_iff
/-- Look up the value associated to a key in a map. -/
def lookup (a : α) (s : finmap β) : option (β a) :=
lift_on s (lookup a) (λ s t, perm_lookup)
@[simp] theorem lookup_to_finmap (a : α) (s : alist β) :
lookup a ⟦s⟧ = s.lookup a := rfl
@[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none :=
rfl
theorem lookup_is_some {a : α} {s : finmap β} :
(s.lookup a).is_some ↔ a ∈ s :=
induction_on s $ λ s, alist.lookup_is_some
theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s :=
induction_on s $ λ s, alist.lookup_eq_none
instance (a : α) (s : finmap β) : decidable (a ∈ s) :=
decidable_of_iff _ lookup_is_some
/-- Replace a key with a given value in a finite map.
If the key is not present it does nothing. -/
def replace (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦replace a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p
@[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) :
replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace]
@[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) :
(replace a b s).keys = s.keys :=
induction_on s $ λ s, by simp
@[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} :
a' ∈ replace a b s ↔ a' ∈ s :=
induction_on s $ λ s, by simp
/-- Fold a commutative function over the key-value pairs in the map -/
def foldl {δ : Type w} (f : δ → Π a, β a → δ)
(H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁)
(d : δ) (m : finmap β) : δ :=
m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d
/-- Erase a key from the map. If the key is not present it does nothing. -/
def erase (a : α) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦erase a t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p
@[simp] theorem erase_to_finmap (a : α) (s : alist β) :
erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase]
@[simp] theorem keys_erase_to_finset (a : α) (s : alist β) :
keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a :=
by simp [finset.erase, keys, alist.erase, keys_kerase]
@[simp] theorem keys_erase (a : α) (s : finmap β) :
(erase a s).keys = s.keys.erase a :=
induction_on s $ λ s, by simp
@[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s :=
induction_on s $ λ s, by simp
@[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none :=
induction_on s $ lookup_erase a
@[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') :
lookup a (erase a' s) = lookup a s :=
induction_on s $ λ s, lookup_erase_ne h
/- insert -/
/-- Insert a key-value pair into a finite map, replacing any existing pair with
the same key. -/
def insert (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦insert a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p
@[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) :
insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert]
theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s →
(insert a b s).entries = ⟨a, b⟩ :: s.entries :=
induction_on s $ λ s h,
by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)]
@[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} :
a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
induction_on s mem_insert
@[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) :
lookup a (insert a b s) = some b :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert]
/- extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract (a : α) (s : finmap β) : option (β a) × finmap β :=
lift_on s (λ t, prod.map id to_finmap (extract a t)) $
λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p]
@[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) :
extract a s = (lookup a s, erase a s) :=
induction_on s $ λ s, by simp [extract]
/- union -/
/-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if
there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/
def union (s₁ s₂ : finmap β) : finmap β :=
lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $
λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄
instance : has_union (finmap β) := ⟨union⟩
@[simp] theorem mem_union {a} {s₁ s₂ : finmap β} :
a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
induction_on₂ s₁ s₂ $ λ _ _, mem_union
@[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ :=
by simp [(∪), union]
theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext' $ by simp [keys]
@[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} :
a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left
@[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} :
a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right
@[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union
theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} :
b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle
end finmap
|
be848b52ba78aa9b09751435b1646b02566d4009 | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/tools/super/subsumption.lean | 1c370e69b9c782007ed6fc7bff39a7481490d87e | [
"Apache-2.0"
] | permissive | leodemoura/lean_clone | 005c63aa892a6492f2d4741ee3c2cb07a6be9d7f | cc077554b584d39bab55c360bc12a6fe7957afe6 | refs/heads/master | 1,610,506,475,484 | 1,482,348,354,000 | 1,482,348,543,000 | 77,091,586 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,472 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .prover_state
open tactic monad
namespace super
private meta def try_subsume_core : list clause.literal → list clause.literal → tactic unit
| [] _ := skip
| small large := first $ do
i ← small^.zip_with_index, j ← large^.zip_with_index,
return $ do
unify_lit i.1 j.1,
try_subsume_core (small^.remove_nth i.2) (large^.remove_nth j.2)
-- FIXME: this is incorrect if a quantifier is unused
meta def try_subsume (small large : clause) : tactic unit := do
small_open ← clause.open_metan small (clause.num_quants small),
large_open ← clause.open_constn large (clause.num_quants large),
guard $ small^.num_lits ≤ large^.num_lits,
try_subsume_core small_open.1^.get_lits large_open.1^.get_lits
meta def does_subsume (small large : clause) : tactic bool :=
(try_subsume small large >> return tt) <|> return ff
meta def does_subsume_with_assertions (small large : derived_clause) : prover bool := do
if small^.assertions^.subset_of large^.assertions then do
♯ does_subsume small^.c large^.c
else
return ff
meta def any_tt {m : Type → Type} [monad m] (active : rb_map clause_id derived_clause) (pred : derived_clause → m bool) : m bool :=
active^.fold (return ff) $ λk a cont, do
v ← pred a, if v then return tt else cont
meta def any_tt_list {m : Type → Type} [monad m] {A} (pred : A → m bool) : list A → m bool
| [] := return ff
| (x::xs) := do v ← pred x, if v then return tt else any_tt_list xs
@[super.inf]
meta def forward_subsumption : inf_decl := inf_decl.mk 20 $
take given, do active ← get_active,
sequence' $ do a ← active^.values,
guard $ a^.id ≠ given^.id,
return $ do
ss ← ♯ does_subsume a^.c given^.c,
if ss
then remove_redundant given^.id [a]
else return ()
meta def forward_subsumption_pre : prover unit := preprocessing_rule $ λnew, do
active ← get_active, filter (λn, do
do ss ← any_tt active (λa,
if a^.assertions^.subset_of n^.assertions then do
♯ does_subsume a^.c n^.c
else
-- TODO: move to locked
return ff),
return (bnot ss)) new
meta def subsumption_interreduction : list derived_clause → prover (list derived_clause)
| (c::cs) := do
-- TODO: move to locked
cs_that_subsume_c ← filter (λd, does_subsume_with_assertions d c) cs,
if ¬cs_that_subsume_c^.empty then
-- TODO: update score
subsumption_interreduction cs
else do
cs_not_subsumed_by_c ← filter (λd, lift bnot (does_subsume_with_assertions c d)) cs,
cs' ← subsumption_interreduction cs_not_subsumed_by_c,
return (c::cs')
| [] := return []
meta def subsumption_interreduction_pre : prover unit :=
preprocessing_rule $ λnew,
let new' := list.sort_on (λc : derived_clause, c^.c^.num_lits) new in
subsumption_interreduction new'
meta def keys_where_tt {m} {K V : Type} [monad m] (active : rb_map K V) (pred : V → m bool) : m (list K) :=
@rb_map.fold _ _ (m (list K)) active (return []) $ λk a cont, do
v ← pred a, rest ← cont, return $ if v then k::rest else rest
@[super.inf]
meta def backward_subsumption : inf_decl := inf_decl.mk 20 $ λgiven, do
active ← get_active,
ss ← ♯ keys_where_tt active (λa, does_subsume given^.c a^.c),
sequence' $ do id ← ss, guard (id ≠ given^.id), [remove_redundant id [given]]
end super
|
e6160df9e896c1beabc38ee164956d6411ad9b84 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/pfun_auto.lean | 1c40bbe12bfa71ee4b63e776707e35ef9b7af3db | [] | 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 | 27,370 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.rel
import Mathlib.PostPort
universes u l u_1 u_2 u_3
namespace Mathlib
/-- `roption α` is the type of "partial values" of type `α`. It
is similar to `option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure roption (α : Type u) where
dom : Prop
get : dom → α
namespace roption
/-- Convert an `roption α` with a decidable domain to an option -/
def to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] : Option α :=
dite (dom o) (fun (h : dom o) => some (get o h)) fun (h : ¬dom o) => none
/-- `roption` extensionality -/
theorem ext' {α : Type u_1} {o : roption α} {p : roption α} (H1 : dom o ↔ dom p)
(H2 : ∀ (h₁ : dom o) (h₂ : dom p), get o h₁ = get p h₂) : o = p :=
sorry
/-- `roption` eta expansion -/
@[simp] theorem eta {α : Type u_1} (o : roption α) : (mk (dom o) fun (h : dom o) => get o h) = o :=
sorry
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def mem {α : Type u_1} (a : α) (o : roption α) := ∃ (h : dom o), get o h = a
protected instance has_mem {α : Type u_1} : has_mem α (roption α) := has_mem.mk roption.mem
theorem mem_eq {α : Type u_1} (a : α) (o : roption α) : a ∈ o = ∃ (h : dom o), get o h = a := rfl
theorem dom_iff_mem {α : Type u_1} {o : roption α} : dom o ↔ ∃ (y : α), y ∈ o := sorry
theorem get_mem {α : Type u_1} {o : roption α} (h : dom o) : get o h ∈ o := Exists.intro h rfl
/-- `roption` extensionality -/
theorem ext {α : Type u_1} {o : roption α} {p : roption α} (H : ∀ (a : α), a ∈ o ↔ a ∈ p) : o = p :=
sorry
/-- The `none` value in `roption` has a `false` domain and an empty function. -/
def none {α : Type u_1} : roption α := mk False False._oldrec
protected instance inhabited {α : Type u_1} : Inhabited (roption α) := { default := none }
@[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none :=
fun (h : a ∈ none) => Exists.fst h
/-- The `some a` value in `roption` has a `true` domain and the
function returns `a`. -/
def some {α : Type u_1} (a : α) : roption α := mk True fun (_x : True) => a
theorem mem_unique {α : Type u_1} : relator.left_unique has_mem.mem := sorry
theorem get_eq_of_mem {α : Type u_1} {o : roption α} {a : α} (h : a ∈ o) (h' : dom o) :
get o h' = a :=
mem_unique (Exists.intro h' rfl) h
@[simp] theorem get_some {α : Type u_1} {a : α} (ha : dom (some a)) : get (some a) ha = a := rfl
theorem mem_some {α : Type u_1} (a : α) : a ∈ some a := Exists.intro trivial rfl
@[simp] theorem mem_some_iff {α : Type u_1} {a : α} {b : α} : b ∈ some a ↔ b = a := sorry
theorem eq_some_iff {α : Type u_1} {a : α} {o : roption α} : o = some a ↔ a ∈ o := sorry
theorem eq_none_iff {α : Type u_1} {o : roption α} : o = none ↔ ∀ (a : α), ¬a ∈ o := sorry
theorem eq_none_iff' {α : Type u_1} {o : roption α} : o = none ↔ ¬dom o :=
{ mp := fun (e : o = none) => Eq.symm e ▸ id,
mpr := fun (h : ¬dom o) => iff.mpr eq_none_iff fun (a : α) (h' : a ∈ o) => h (Exists.fst h') }
theorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none :=
id
fun (h : some x = none) =>
id (eq.mpr (id (Eq._oldrec (Eq.refl (dom none)) (Eq.symm h))) trivial)
theorem ne_none_iff {α : Type u_1} {o : roption α} : o ≠ none ↔ ∃ (x : α), o = some x := sorry
theorem eq_none_or_eq_some {α : Type u_1} (o : roption α) : o = none ∨ ∃ (x : α), o = some x :=
sorry
@[simp] theorem some_inj {α : Type u_1} {a : α} {b : α} : some a = some b ↔ a = b :=
function.injective.eq_iff
fun (a b : α) (h : some a = some b) => congr_fun (eq_of_heq (and.right (mk.inj h))) trivial
@[simp] theorem some_get {α : Type u_1} {a : roption α} (ha : dom a) : some (get a ha) = a :=
Eq.symm (iff.mpr eq_some_iff (Exists.intro ha rfl))
theorem get_eq_iff_eq_some {α : Type u_1} {a : roption α} {ha : dom a} {b : α} :
get a ha = b ↔ a = some b :=
sorry
protected instance none_decidable {α : Type u_1} : Decidable (dom none) := decidable.false
protected instance some_decidable {α : Type u_1} (a : α) : Decidable (dom (some a)) :=
decidable.true
def get_or_else {α : Type u_1} (a : roption α) [Decidable (dom a)] (d : α) : α :=
dite (dom a) (fun (ha : dom a) => get a ha) fun (ha : ¬dom a) => d
@[simp] theorem get_or_else_none {α : Type u_1} (d : α) : get_or_else none d = d := dif_neg id
@[simp] theorem get_or_else_some {α : Type u_1} (a : α) (d : α) : get_or_else (some a) d = a :=
dif_pos trivial
@[simp] theorem mem_to_option {α : Type u_1} {o : roption α} [Decidable (dom o)] {a : α} :
a ∈ to_option o ↔ a ∈ o :=
sorry
/-- Convert an `option α` into an `roption α` -/
def of_option {α : Type u_1} : Option α → roption α := sorry
@[simp] theorem mem_of_option {α : Type u_1} {a : α} {o : Option α} : a ∈ of_option o ↔ a ∈ o :=
sorry
@[simp] theorem of_option_dom {α : Type u_1} (o : Option α) :
dom (of_option o) ↔ ↥(option.is_some o) :=
sorry
theorem of_option_eq_get {α : Type u_1} (o : Option α) :
of_option o = mk (↥(option.is_some o)) option.get :=
sorry
protected instance has_coe {α : Type u_1} : has_coe (Option α) (roption α) := has_coe.mk of_option
@[simp] theorem mem_coe {α : Type u_1} {a : α} {o : Option α} : a ∈ ↑o ↔ a ∈ o := mem_of_option
@[simp] theorem coe_none {α : Type u_1} : ↑none = none := rfl
@[simp] theorem coe_some {α : Type u_1} (a : α) : ↑(some a) = some a := rfl
protected theorem induction_on {α : Type u_1} {P : roption α → Prop} (a : roption α)
(hnone : P none) (hsome : ∀ (a : α), P (some a)) : P a :=
or.elim (classical.em (dom a)) (fun (h : dom a) => some_get h ▸ hsome (get a h))
fun (h : ¬dom a) => Eq.symm (iff.mpr eq_none_iff' h) ▸ hnone
protected instance of_option_decidable {α : Type u_1} (o : Option α) :
Decidable (dom (of_option o)) :=
sorry
@[simp] theorem to_of_option {α : Type u_1} (o : Option α) : to_option (of_option o) = o :=
option.cases_on o (Eq.refl (to_option (of_option none)))
fun (o : α) => Eq.refl (to_option (of_option (some o)))
@[simp] theorem of_to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] :
of_option (to_option o) = o :=
ext fun (a : α) => iff.trans mem_of_option mem_to_option
def equiv_option {α : Type u_1} : roption α ≃ Option α :=
equiv.mk (fun (o : roption α) => to_option o) of_option sorry sorry
protected instance order_bot {α : Type u_1} : order_bot (roption α) :=
order_bot.mk none (fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y)
(partial_order.lt._default fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y) sorry sorry sorry
sorry
protected instance preorder {α : Type u_1} : preorder (roption α) :=
partial_order.to_preorder (roption α)
theorem le_total_of_le_of_le {α : Type u_1} {x : roption α} {y : roption α} (z : roption α)
(hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x :=
sorry
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert {α : Type u_1} (p : Prop) (f : p → roption α) : roption α :=
mk (∃ (h : p), dom (f h)) fun (ha : ∃ (h : p), dom (f h)) => get (f sorry) sorry
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind {α : Type u_1} {β : Type u_2} (f : roption α) (g : α → roption β) : roption β :=
assert (dom f) fun (b : dom f) => g (get f b)
/-- The map operation for `roption` just maps the value and maintains the same domain. -/
def map {α : Type u_1} {β : Type u_2} (f : α → β) (o : roption α) : roption β :=
mk (dom o) (f ∘ get o)
theorem mem_map {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {a : α} :
a ∈ o → f a ∈ map f o :=
sorry
@[simp] theorem mem_map_iff {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {b : β} :
b ∈ map f o ↔ ∃ (a : α), ∃ (H : a ∈ o), f a = b :=
sorry
@[simp] theorem map_none {α : Type u_1} {β : Type u_2} (f : α → β) : map f none = none := sorry
@[simp] theorem map_some {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) :
map f (some a) = some (f a) :=
iff.mpr eq_some_iff (mem_map f (mem_some a))
theorem mem_assert {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} (h : p) :
a ∈ f h → a ∈ assert p f :=
sorry
@[simp] theorem mem_assert_iff {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} :
a ∈ assert p f ↔ ∃ (h : p), a ∈ f h :=
sorry
theorem assert_pos {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) : assert p f = f h := sorry
theorem assert_neg {α : Type u_1} {p : Prop} {f : p → roption α} (h : ¬p) : assert p f = none :=
sorry
theorem mem_bind {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} {a : α} {b : β} :
a ∈ f → b ∈ g a → b ∈ roption.bind f g :=
sorry
@[simp] theorem mem_bind_iff {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β}
{b : β} : b ∈ roption.bind f g ↔ ∃ (a : α), ∃ (H : a ∈ f), b ∈ g a :=
sorry
@[simp] theorem bind_none {α : Type u_1} {β : Type u_2} (f : α → roption β) :
roption.bind none f = none :=
sorry
@[simp] theorem bind_some {α : Type u_1} {β : Type u_2} (a : α) (f : α → roption β) :
roption.bind (some a) f = f a :=
sorry
theorem bind_some_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) (x : roption α) :
roption.bind x (some ∘ f) = map f x :=
sorry
theorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : roption α) (g : α → roption β)
(k : β → roption γ) :
roption.bind (roption.bind f g) k = roption.bind f fun (x : α) => roption.bind (g x) k :=
sorry
@[simp] theorem bind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : roption α)
(g : β → roption γ) : roption.bind (map f x) g = roption.bind x fun (y : α) => g (f y) :=
sorry
@[simp] theorem map_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → roption β)
(x : roption α) (g : β → γ) :
map g (roption.bind x f) = roption.bind x fun (y : α) => map g (f y) :=
sorry
theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β)
(o : roption α) : map g (map f o) = map (g ∘ f) o :=
sorry
protected instance monad : Monad roption :=
{ toApplicative :=
{ toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β },
toPure := { pure := some },
toSeq :=
{ seq :=
fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>
roption.bind f fun (_x : α → β) => map _x x },
toSeqLeft :=
{ seqLeft :=
fun (α β : Type u_1) (a : roption α) (b : roption β) =>
(fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>
roption.bind f fun (_x : α → β) => map _x x)
β α (map (function.const β) a) b },
toSeqRight :=
{ seqRight :=
fun (α β : Type u_1) (a : roption α) (b : roption β) =>
(fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>
roption.bind f fun (_x : α → β) => map _x x)
β β (map (function.const α id) a) b } },
toBind := { bind := roption.bind } }
protected instance is_lawful_monad : is_lawful_monad roption :=
is_lawful_monad.mk bind_some bind_assoc
theorem map_id' {α : Type u_1} {f : α → α} (H : ∀ (x : α), f x = x) (o : roption α) : map f o = o :=
eq.mpr (id (Eq._oldrec (Eq.refl (map f o = o)) ((fun (this : f = id) => this) (funext H))))
(id_map o)
@[simp] theorem bind_some_right {α : Type u_1} (x : roption α) : roption.bind x some = x := sorry
@[simp] theorem pure_eq_some {α : Type u_1} (a : α) : pure a = some a := rfl
@[simp] theorem ret_eq_some {α : Type u_1} (a : α) : return a = some a := rfl
@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} (f : α → β) (o : roption α) :
f <$> o = map f o :=
rfl
@[simp] theorem bind_eq_bind {α : Type u_1} {β : Type u_1} (f : roption α) (g : α → roption β) :
f >>= g = roption.bind f g :=
rfl
theorem bind_le {β : Type u_2} {α : Type u_2} (x : roption α) (f : α → roption β) (y : roption β) :
x >>= f ≤ y ↔ ∀ (a : α), a ∈ x → f a ≤ y :=
sorry
protected instance monad_fail : monad_fail roption :=
monad_fail.mk fun (_x : Type u_1) (_x_1 : string) => none
/- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when
`p` implies `o` is defined. -/
def restrict {α : Type u_1} (p : Prop) (o : roption α) : (p → dom o) → roption α := sorry
@[simp] theorem mem_restrict {α : Type u_1} (p : Prop) (o : roption α) (h : p → dom o) (a : α) :
a ∈ restrict p o h ↔ p ∧ a ∈ o :=
sorry
/-- `unwrap o` gets the value at `o`, ignoring the condition.
(This function is unsound.) -/
theorem assert_defined {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) :
dom (f h) → dom (assert p f) :=
exists.intro
theorem bind_defined {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} (h : dom f) :
dom (g (get f h)) → dom (roption.bind f g) :=
assert_defined
@[simp] theorem bind_dom {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} :
dom (roption.bind f g) ↔ ∃ (h : dom f), dom (g (get f h)) :=
iff.rfl
end roption
/-- `pfun α β`, or `α →. β`, is the type of partial functions from
`α` to `β`. It is defined as `α → roption β`. -/
def pfun (α : Type u_1) (β : Type u_2) := α → roption β
infixr:25 " →. " => Mathlib.pfun
namespace pfun
protected instance inhabited {α : Type u_1} {β : Type u_2} : Inhabited (α →. β) :=
{ default := fun (a : α) => roption.none }
/-- The domain of a partial function -/
def dom {α : Type u_1} {β : Type u_2} (f : α →. β) : set α :=
set_of fun (a : α) => roption.dom (f a)
theorem mem_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) :
x ∈ dom f ↔ ∃ (y : β), y ∈ f x :=
sorry
theorem dom_eq {α : Type u_1} {β : Type u_2} (f : α →. β) :
dom f = set_of fun (x : α) => ∃ (y : β), y ∈ f x :=
set.ext (mem_dom f)
/-- Evaluate a partial function -/
def fn {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (h : dom f x) : β := roption.get (f x) h
/-- Evaluate a partial function to return an `option` -/
def eval_opt {α : Type u_1} {β : Type u_2} (f : α →. β) [D : decidable_pred (dom f)] (x : α) :
Option β :=
roption.to_option (f x)
/-- Partial function extensionality -/
theorem ext' {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β}
(H1 : ∀ (a : α), a ∈ dom f ↔ a ∈ dom g)
(H2 : ∀ (a : α) (p : dom f a) (q : dom g a), fn f a p = fn g a q) : f = g :=
funext fun (a : α) => roption.ext' (H1 a) (H2 a)
theorem ext {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β}
(H : ∀ (a : α) (b : β), b ∈ f a ↔ b ∈ g a) : f = g :=
funext fun (a : α) => roption.ext (H a)
/-- Turn a partial function into a function out of a subtype -/
def as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : ↥(dom f)) : β := fn f ↑s sorry
/-- The set of partial functions `α →. β` is equivalent to
the set of pairs `(p : α → Prop, f : subtype p → β)`. -/
def equiv_subtype {α : Type u_1} {β : Type u_2} :
(α →. β) ≃ sigma fun (p : α → Prop) => Subtype p → β :=
equiv.mk (fun (f : α →. β) => sigma.mk (fun (a : α) => roption.dom (f a)) (as_subtype f))
(fun (f : sigma fun (p : α → Prop) => Subtype p → β) (x : α) =>
roption.mk (sigma.fst f x) fun (h : sigma.fst f x) => sigma.snd f { val := x, property := h })
sorry sorry
theorem as_subtype_eq_of_mem {α : Type u_1} {β : Type u_2} {f : α →. β} {x : α} {y : β}
(fxy : y ∈ f x) (domx : x ∈ dom f) : as_subtype f { val := x, property := domx } = y :=
roption.mem_unique (roption.get_mem (as_subtype._proof_1 f { val := x, property := domx })) fxy
/-- Turn a total function into a partial function -/
protected def lift {α : Type u_1} {β : Type u_2} (f : α → β) : α →. β :=
fun (a : α) => roption.some (f a)
protected instance has_coe {α : Type u_1} {β : Type u_2} : has_coe (α → β) (α →. β) :=
has_coe.mk pfun.lift
@[simp] theorem lift_eq_coe {α : Type u_1} {β : Type u_2} (f : α → β) : pfun.lift f = ↑f := rfl
@[simp] theorem coe_val {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) :
coe f a = roption.some (f a) :=
rfl
/-- The graph of a partial function is the set of pairs
`(x, f x)` where `x` is in the domain of `f`. -/
def graph {α : Type u_1} {β : Type u_2} (f : α →. β) : set (α × β) :=
set_of fun (p : α × β) => prod.snd p ∈ f (prod.fst p)
def graph' {α : Type u_1} {β : Type u_2} (f : α →. β) : rel α β := fun (x : α) (y : β) => y ∈ f x
/-- The range of a partial function is the set of values
`f x` where `x` is in the domain of `f`. -/
def ran {α : Type u_1} {β : Type u_2} (f : α →. β) : set β :=
set_of fun (b : β) => ∃ (a : α), b ∈ f a
/-- Restrict a partial function to a smaller domain. -/
def restrict {α : Type u_1} {β : Type u_2} (f : α →. β) {p : set α} (H : p ⊆ dom f) : α →. β :=
fun (x : α) => roption.restrict (x ∈ p) (f x) H
@[simp] theorem mem_restrict {α : Type u_1} {β : Type u_2} {f : α →. β} {s : set α} (h : s ⊆ dom f)
(a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a :=
sorry
def res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) : α →. β :=
restrict (pfun.lift f) (set.subset_univ s)
theorem mem_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (a : α) (b : β) :
b ∈ res f s a ↔ a ∈ s ∧ f a = b :=
sorry
theorem res_univ {α : Type u_1} {β : Type u_2} (f : α → β) : res f set.univ = ↑f := rfl
theorem dom_iff_graph {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) :
x ∈ dom f ↔ ∃ (y : β), (x, y) ∈ graph f :=
roption.dom_iff_mem
theorem lift_graph {α : Type u_1} {β : Type u_2} {f : α → β} {a : α} {b : β} :
(a, b) ∈ graph ↑f ↔ f a = b :=
sorry
/-- The monad `pure` function, the total constant `x` function -/
protected def pure {α : Type u_1} {β : Type u_2} (x : β) : α →. β := fun (_x : α) => roption.some x
/-- The monad `bind` function, pointwise `roption.bind` -/
def bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α →. β) (g : β → α →. γ) : α →. γ :=
fun (a : α) => roption.bind (f a) fun (b : β) => g b a
/-- The monad `map` function, pointwise `roption.map` -/
def map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (g : α →. β) : α →. γ :=
fun (a : α) => roption.map f (g a)
protected instance monad {α : Type u_1} : Monad (pfun α) :=
{ toApplicative :=
{ toFunctor := { map := map, mapConst := fun (α_1 β : Type u_2) => map ∘ function.const β },
toPure := { pure := pfun.pure },
toSeq :=
{ seq :=
fun (α_1 β : Type u_2) (f : α →. α_1 → β) (x : α →. α_1) =>
bind f fun (_x : α_1 → β) => map _x x },
toSeqLeft :=
{ seqLeft :=
fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>
(fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) =>
bind f fun (_x : α_2 → β) => map _x x)
β α_1 (map (function.const β) a) b },
toSeqRight :=
{ seqRight :=
fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>
(fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) =>
bind f fun (_x : α_2 → β) => map _x x)
β β (map (function.const α_1 id) a) b } },
toBind := { bind := bind } }
protected instance is_lawful_monad {α : Type u_1} : is_lawful_monad (pfun α) :=
is_lawful_monad.mk
(fun (β γ : Type u_2) (x : β) (f : β → α →. γ) =>
funext fun (a : α) => roption.bind_some a (f x))
fun (β γ δ : Type u_2) (f : α →. β) (g : β → α →. γ) (k : γ → α →. δ) =>
funext fun (a : α) => roption.bind_assoc (f a) (fun (b : β) => g b a) fun (b : γ) => k b a
theorem pure_defined {α : Type u_1} {β : Type u_2} (p : set α) (x : β) : p ⊆ dom (pfun.pure x) :=
set.subset_univ p
theorem bind_defined {α : Type u_1} {β : Type u_2} {γ : Type u_2} (p : set α) {f : α →. β}
{g : β → α →. γ} (H1 : p ⊆ dom f) (H2 : ∀ (x : β), p ⊆ dom (g x)) : p ⊆ dom (f >>= g) :=
fun (a : α) (ha : a ∈ p) => Exists.intro (H1 ha) (H2 (roption.get (f a) (H1 ha)) ha)
def fix {α : Type u_1} {β : Type u_2} (f : α →. β ⊕ α) : α →. β :=
fun (a : α) =>
roption.assert (acc (fun (x y : α) => sum.inr x ∈ f y) a)
fun (h : acc (fun (x y : α) => sum.inr x ∈ f y) a) =>
well_founded.fix_F
(fun (a : α) (IH : (y : α) → sum.inr y ∈ f a → roption β) =>
roption.assert (roption.dom (f a))
fun (hf : roption.dom (f a)) =>
(fun (_x : β ⊕ α) (e : roption.get (f a) hf = _x) =>
sum.cases_on _x
(fun (b : β) (e : roption.get (f a) hf = sum.inl b) => roption.some b)
(fun (a' : α) (e : roption.get (f a) hf = sum.inr a') => IH a' sorry) e)
(roption.get (f a) hf) sorry)
a h
theorem dom_of_mem_fix {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β}
(h : b ∈ fix f a) : roption.dom (f a) :=
sorry
theorem mem_fix_iff {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β} :
b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ (a' : α), sum.inr a' ∈ f a ∧ b ∈ fix f a' :=
sorry
def fix_induction {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {b : β} {C : α → Sort u_3} {a : α}
(h : b ∈ fix f a)
(H : (a : α) → b ∈ fix f a → ((a' : α) → b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a :=
sorry
end pfun
namespace pfun
def image {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) : set β := rel.image (graph' f) s
theorem image_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) :
image f s = set_of fun (y : β) => ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=
rfl
theorem mem_image {α : Type u_1} {β : Type u_2} (f : α →. β) (y : β) (s : set α) :
y ∈ image f s ↔ ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=
iff.rfl
theorem image_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set α} {t : set α} (h : s ⊆ t) :
image f s ⊆ image f t :=
rel.image_mono (graph' f) h
theorem image_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) :
image f (s ∩ t) ⊆ image f s ∩ image f t :=
rel.image_inter (graph' f) s t
theorem image_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) :
image f (s ∪ t) = image f s ∪ image f t :=
rel.image_union (graph' f) s t
def preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α :=
rel.preimage (fun (x : α) (y : β) => y ∈ f x) s
theorem preimage_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
preimage f s = set_of fun (x : α) => ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=
rfl
theorem mem_preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (x : α) :
x ∈ preimage f s ↔ ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=
iff.rfl
theorem preimage_subset_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
preimage f s ⊆ dom f :=
sorry
theorem preimage_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β}
(h : s ⊆ t) : preimage f s ⊆ preimage f t :=
rel.preimage_mono (fun (x : α) (y : β) => y ∈ f x) h
theorem preimage_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :
preimage f (s ∩ t) ⊆ preimage f s ∩ preimage f t :=
rel.preimage_inter (fun (x : α) (y : β) => y ∈ f x) s t
theorem preimage_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :
preimage f (s ∪ t) = preimage f s ∪ preimage f t :=
rel.preimage_union (fun (x : α) (y : β) => y ∈ f x) s t
theorem preimage_univ {α : Type u_1} {β : Type u_2} (f : α →. β) : preimage f set.univ = dom f :=
sorry
def core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α := rel.core (graph' f) s
theorem core_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
core f s = set_of fun (x : α) => ∀ (y : β), y ∈ f x → y ∈ s :=
rfl
theorem mem_core {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (s : set β) :
x ∈ core f s ↔ ∀ (y : β), y ∈ f x → y ∈ s :=
iff.rfl
theorem compl_dom_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
dom fᶜ ⊆ core f s :=
fun (x : α) (hx : x ∈ (dom fᶜ)) (y : β) (fxy : graph' f x y) =>
absurd (iff.mpr (mem_dom f x) (Exists.intro y fxy)) hx
theorem core_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β} (h : s ⊆ t) :
core f s ⊆ core f t :=
rel.core_mono (graph' f) h
theorem core_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :
core f (s ∩ t) = core f s ∩ core f t :=
rel.core_inter (graph' f) s t
theorem mem_core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) (x : α) :
x ∈ core (res f s) t ↔ x ∈ s → f x ∈ t :=
sorry
theorem core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) :
core (res f s) t = sᶜ ∪ f ⁻¹' t :=
sorry
theorem core_restrict {α : Type u_1} {β : Type u_2} (f : α → β) (s : set β) :
core (↑f) s = f ⁻¹' s :=
sorry
theorem preimage_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
preimage f s ⊆ core f s :=
sorry
theorem preimage_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
preimage f s = core f s ∩ dom f :=
sorry
theorem core_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
core f s = preimage f s ∪ (dom fᶜ) :=
sorry
theorem preimage_as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :
as_subtype f ⁻¹' s = subtype.val ⁻¹' preimage f s :=
sorry
end Mathlib |
c6f8c975b3ae2309f4b16bb648d4fd5f93560fc8 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /tests/lean/370.lean | fa45c7a2134e39105695103b3054ef3090478ba6 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 394 | lean | #eval show Option String from do
s!"{← some 1}"
def f1 : Option Nat := do
return (← some 1)
def f2 : Option Nat := do
let x ← some 1
return none
def f3 : Option String := do
if let some x ← some 1 then
none
else
none
def f4 : Option String := do
let mut x := none
x ← some 1
return x
def f5 : Option String := do
let (x, y) ← some (1, 5)
return x
|
dd7dff6b6317e2b46d9cf85e229f9451e733fd80 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Group/adjunctions.lean | 8aa601a1973574063643e5d84f71cfcd10053bb4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,461 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl
-/
import algebra.category.Group.basic
import group_theory.free_abelian_group
/-!
# Adjunctions regarding the category of (abelian) groups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains construction of basic adjunctions concerning the category of groups and the
category of abelian groups.
## Main definitions
* `AddCommGroup.free`: constructs the functor associating to a type `X` the free abelian group with
generators `x : X`.
* `Group.free`: constructs the functor associating to a type `X` the free group with
generators `x : X`.
* `abelianize`: constructs the functor which associates to a group `G` its abelianization `Gᵃᵇ`.
## Main statements
* `AddCommGroup.adj`: proves that `AddCommGroup.free` is the left adjoint of the forgetful functor
from abelian groups to types.
* `Group.adj`: proves that `Group.free` is the left adjoint of the forgetful functor from groups to
types.
* `abelianize_adj`: proves that `abelianize` is left adjoint to the forgetful functor from
abelian groups to groups.
-/
noncomputable theory
universe u
open category_theory
namespace AddCommGroup
open_locale classical
/--
The free functor `Type u ⥤ AddCommGroup` sending a type `X` to the
free abelian group with generators `x : X`.
-/
def free : Type u ⥤ AddCommGroup :=
{ obj := λ α, of (free_abelian_group α),
map := λ X Y, free_abelian_group.map,
map_id' := λ X, add_monoid_hom.ext free_abelian_group.map_id_apply,
map_comp' := λ X Y Z f g, add_monoid_hom.ext free_abelian_group.map_comp_apply, }
@[simp] lemma free_obj_coe {α : Type u} :
(free.obj α : Type u) = (free_abelian_group α) := rfl
@[simp] lemma free_map_coe {α β : Type u} {f : α → β} (x : free_abelian_group α) :
(free.map f) x = f <$> x := rfl
/--
The free-forgetful adjunction for abelian groups.
-/
def adj : free ⊣ forget AddCommGroup.{u} :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X G, free_abelian_group.lift.symm,
hom_equiv_naturality_left_symm' :=
by { intros, ext, refl} }
instance : is_right_adjoint (forget AddCommGroup.{u}) := ⟨_, adj⟩
/--
As an example, we now give a high-powered proof that
the monomorphisms in `AddCommGroup` are just the injective functions.
(This proof works in all universes.)
-/
example {G H : AddCommGroup.{u}} (f : G ⟶ H) [mono f] : function.injective f :=
(mono_iff_injective f).1 (show mono ((forget AddCommGroup.{u}).map f), by apply_instance)
end AddCommGroup
namespace Group
/-- The free functor `Type u ⥤ Group` sending a type `X` to the free group with generators `x : X`.
-/
def free : Type u ⥤ Group :=
{ obj := λ α, of (free_group α),
map := λ X Y, free_group.map,
map_id' := by { intros, ext1, refl },
map_comp' := by { intros, ext1, refl } }
/-- The free-forgetful adjunction for groups.
-/
def adj : free ⊣ forget Group.{u} :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X G, free_group.lift.symm,
hom_equiv_naturality_left_symm' := λ X Y G f g, by { ext1, refl } }
instance : is_right_adjoint (forget Group.{u}) := ⟨_, adj⟩
end Group
section abelianization
/-- The abelianization functor `Group ⥤ CommGroup` sending a group `G` to its abelianization `Gᵃᵇ`.
-/
def abelianize : Group.{u} ⥤ CommGroup.{u} :=
{ obj := λ G, { α := abelianization G, str := by apply_instance },
map := λ G H f, abelianization.lift ( { to_fun := λ x, abelianization.of (f x),
map_one' := by simp,
map_mul' := by simp } ),
map_id' := by { intros, simp only [monoid_hom.mk_coe, coe_id], ext1, refl },
map_comp' := by { intros, simp only [coe_comp], ext1, refl } }
/-- The abelianization-forgetful adjuction from `Group` to `CommGroup`.-/
def abelianize_adj : abelianize ⊣ forget₂ CommGroup.{u} Group.{u} :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ G A, abelianization.lift.symm,
hom_equiv_naturality_left_symm' := λ G H A f g, by { ext1, refl } }
end abelianization
/-- The functor taking a monoid to its subgroup of units. -/
@[simps]
def Mon.units : Mon.{u} ⥤ Group.{u} :=
{ obj := λ R, Group.of Rˣ,
map := λ R S f, Group.of_hom $ units.map f,
map_id' := λ X, monoid_hom.ext (λ x, units.ext rfl),
map_comp' := λ X Y Z f g, monoid_hom.ext (λ x, units.ext rfl) }
/-- The forgetful-units adjunction between `Group` and `Mon`. -/
def Group.forget₂_Mon_adj : forget₂ Group Mon ⊣ Mon.units.{u} :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, monoid_hom.to_hom_units f,
inv_fun := λ f, (units.coe_hom Y).comp f,
left_inv := λ f, monoid_hom.ext $ λ _, rfl,
right_inv := λ f, monoid_hom.ext $ λ _, units.ext rfl },
unit :=
{ app := λ X, { ..(@to_units X _).to_monoid_hom },
naturality' := λ X Y f, monoid_hom.ext $ λ x, units.ext rfl },
counit :=
{ app := λ X, units.coe_hom X,
naturality' := λ X Y f, monoid_hom.ext $ λ x, rfl },
hom_equiv_unit' := λ X Y f, monoid_hom.ext $ λ _, units.ext rfl,
hom_equiv_counit' := λ X Y f, monoid_hom.ext $ λ _, rfl }
instance : is_right_adjoint Mon.units.{u} :=
⟨_, Group.forget₂_Mon_adj⟩
/-- The functor taking a monoid to its subgroup of units. -/
@[simps]
def CommMon.units : CommMon.{u} ⥤ CommGroup.{u} :=
{ obj := λ R, CommGroup.of Rˣ,
map := λ R S f, CommGroup.of_hom $ units.map f,
map_id' := λ X, monoid_hom.ext (λ x, units.ext rfl),
map_comp' := λ X Y Z f g, monoid_hom.ext (λ x, units.ext rfl) }
/-- The forgetful-units adjunction between `CommGroup` and `CommMon`. -/
def CommGroup.forget₂_CommMon_adj : forget₂ CommGroup CommMon ⊣ CommMon.units.{u} :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, monoid_hom.to_hom_units f,
inv_fun := λ f, (units.coe_hom Y).comp f,
left_inv := λ f, monoid_hom.ext $ λ _, rfl,
right_inv := λ f, monoid_hom.ext $ λ _, units.ext rfl },
unit :=
{ app := λ X, { ..(@to_units X _).to_monoid_hom },
naturality' := λ X Y f, monoid_hom.ext $ λ x, units.ext rfl },
counit :=
{ app := λ X, units.coe_hom X,
naturality' := λ X Y f, monoid_hom.ext $ λ x, rfl },
hom_equiv_unit' := λ X Y f, monoid_hom.ext $ λ _, units.ext rfl,
hom_equiv_counit' := λ X Y f, monoid_hom.ext $ λ _, rfl }
instance : is_right_adjoint CommMon.units.{u} :=
⟨_, CommGroup.forget₂_CommMon_adj⟩
|
d225bcc694c415f9c4c7e0928953685f809aca1b | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/LE.lean | 63df043f4614a28fdb159952e7ae7d0b67775d73 | [
"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 | 101 | lean | inductive LE' : Nat → Nat → Prop where
| refl (n : Nat) : LE' n n
#check @LE'.refl
#print LE'
|
f51e231df5fd63a77cc50973e10215d8b4b527c9 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Parser/Module.lean | 3a6846b3077a1cb209633d43e6405e018675dc7d | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 5,603 | 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.Message
import Lean.Parser.Command
namespace Lean
namespace Parser
namespace Module
def «prelude» := leading_parser "prelude"
def «import» := leading_parser "import " >> optional "runtime" >> ident
def header := leading_parser optional («prelude» >> ppLine) >> many («import» >> ppLine) >> ppLine
/--
Parser for a Lean module. We never actually run this parser but instead use the imperative definitions below that
return the same syntax tree structure, but add error recovery. Still, it is helpful to have a `Parser` definition
for it in order to auto-generate helpers such as the pretty printer. -/
@[runBuiltinParserAttributeHooks]
def module := leading_parser header >> many (commandParser >> ppLine >> ppLine)
def updateTokens (c : ParserContext) : ParserContext :=
{ c with
tokens := match addParserTokens c.tokens header.info with
| Except.ok tables => tables
| Except.error _ => unreachable! }
end Module
structure ModuleParserState where
pos : String.Pos := 0
recovering : Bool := false
deriving Inhabited
private def mkErrorMessage (c : ParserContext) (pos : String.Pos) (errorMsg : String) : Message :=
let pos := c.fileMap.toPosition pos
{ fileName := c.fileName, pos := pos, data := errorMsg }
def parseHeader (inputCtx : InputContext) : IO (Syntax × ModuleParserState × MessageLog) := do
let dummyEnv ← mkEmptyEnvironment
let ctx := mkParserContext inputCtx { env := dummyEnv, options := {} }
let ctx := Module.updateTokens ctx
let s := mkParserState ctx.input
let s := whitespace ctx s
let s := Module.header.fn ctx s
let stx := s.stxStack.back
match s.errorMsg with
| some errorMsg =>
let msg := mkErrorMessage ctx s.pos (toString errorMsg)
pure (stx, { pos := s.pos, recovering := true }, { : MessageLog }.add msg)
| none =>
pure (stx, { pos := s.pos }, {})
private def mkEOI (pos : String.Pos) : Syntax :=
let atom := mkAtom (SourceInfo.original "".toSubstring pos "".toSubstring) ""
Syntax.node `Lean.Parser.Module.eoi #[atom]
def isEOI (s : Syntax) : Bool :=
s.isOfKind `Lean.Parser.Module.eoi
def isExitCommand (s : Syntax) : Bool :=
s.isOfKind `Lean.Parser.Command.exit
private def consumeInput (c : ParserContext) (pos : String.Pos) : String.Pos :=
let s : ParserState := { cache := initCacheForInput c.input, pos := pos }
let s := tokenFn [] c s
match s.errorMsg with
| some _ => pos + 1
| none => s.pos
def topLevelCommandParserFn : ParserFn :=
commandParser.fn
partial def parseCommand (inputCtx : InputContext) (pmctx : ParserModuleContext) (s : ModuleParserState) (messages : MessageLog) : Syntax × ModuleParserState × MessageLog :=
let rec parse (s : ModuleParserState) (messages : MessageLog) :=
let { pos := pos, recovering := recovering } := s
if inputCtx.input.atEnd pos then
(mkEOI pos, s, messages)
else
let c := mkParserContext inputCtx pmctx
let s := { cache := initCacheForInput c.input, pos := pos : ParserState }
let s := whitespace c s
let s := topLevelCommandParserFn c s
match s.errorMsg with
| none =>
(s.stxStack.back, { pos := s.pos }, messages)
| some errorMsg =>
-- advance at least one token to prevent infinite loops
let pos := if s.pos == pos then consumeInput c s.pos else s.pos
let messages := if recovering && s.stxStack.isEmpty then messages else messages.add <| mkErrorMessage c s.pos (toString errorMsg)
/- We ignore commands where `getPos?` is none. This happens only on commands that have a prefix comprised of optional elements.
For example, unification hints start with `optional («scoped» <|> «local»)`.
We claim a syntatically incorrect command containing no token or identifier is irrelevant for intellisense and should be ignored. -/
if s.stxStack.isEmpty || s.stxStack.back.getPos?.isNone then
parse { pos := pos, recovering := true } messages
else
(s.stxStack.back, { pos := pos, recovering := true }, messages)
parse s messages
-- only useful for testing since most Lean files cannot be parsed without elaboration
partial def testParseModuleAux (env : Environment) (inputCtx : InputContext) (s : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) : IO (Array Syntax) :=
let rec parse (state : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) :=
match parseCommand inputCtx { env := env, options := {} } state msgs with
| (stx, state, msgs) =>
if isEOI stx then
if msgs.isEmpty then
pure stxs
else do
msgs.forM fun msg => msg.toString >>= IO.println
throw (IO.userError "failed to parse file")
else
parse state msgs (stxs.push stx)
parse s msgs stxs
def testParseModule (env : Environment) (fname contents : String) : IO Syntax := do
let fname ← IO.realPath fname
let inputCtx := mkInputContext contents fname
let (header, state, messages) ← parseHeader inputCtx
let cmds ← testParseModuleAux env inputCtx state messages #[]
let stx := Syntax.node `Lean.Parser.Module.module #[header, mkListNode cmds]
pure stx.updateLeading
def testParseFile (env : Environment) (fname : String) : IO Syntax := do
let contents ← IO.FS.readFile fname
testParseModule env fname contents
end Parser
end Lean
|
d11f2bf76a686eb9eb9475af68f5947c3a747ee5 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/ordered/compact.lean | 7fc47331556900cd7acf7ac64961c2d0e9314b97 | [
"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 | 11,149 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Yury Kudryashov
-/
import topology.algebra.ordered.intermediate_value
/-!
# Compactness of a closed interval
In this file we prove that a closed interval in a conditionally complete linear ordered type with
order topology (or a product of such types) is compact. We also prove the extreme value theorem
(`is_compact.exists_forall_le`, `is_compact.exists_forall_ge`): a continuous function on a compact
set takes its minimum and maximum values.
We also prove that the image of a closed interval under a continuous map is a closed interval, see
`continuous_on.image_Icc`.
## Tags
compact, extreme value theorem
-/
open classical filter order_dual topological_space function set
/-!
### Compactness of a closed interval
In this section we define a typeclass `compact_Icc_space α` saying that all closed intervals in `α`
are compact. Then we provide an instance for a `conditionally_complete_linear_order` and prove that
the product (both `α × β` and an indexed product) of spaces with this property inherits the
property.
We also prove some simple lemmas about spaces with this property.
-/
/-- This typeclass says that all closed intervals in `α` are compact. This is true for all
conditionally complete linear orders with order topology and products (finite or infinite)
of such spaces. -/
class compact_Icc_space (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_compact_Icc : ∀ {a b : α}, is_compact (Icc a b))
export compact_Icc_space (is_compact_Icc)
/-- A closed interval in a conditionally complete linear order is compact. -/
@[priority 100]
instance conditionally_complete_linear_order.to_compact_Icc_space
(α : Type*) [conditionally_complete_linear_order α] [topological_space α] [order_topology α] :
compact_Icc_space α :=
begin
refine ⟨λ a b, _⟩,
cases le_or_lt a b with hab hab, swap, { simp [hab] },
refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _),
contrapose! hf,
rw [le_principal_iff],
have hpt : ∀ x ∈ Icc a b, {x} ∉ f,
from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)),
set s := {x ∈ Icc a b | Icc a x ∉ f},
have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2,
have sbd : bdd_above s, from ⟨b, hsb⟩,
have ha : a ∈ s, by simp [hpt, hab],
rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 },
set c := Sup s,
have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd,
have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩,
specialize hf c hc,
have hcs : c ∈ s,
{ cases hc.1.eq_or_lt with heq hlt, { rwa ← heq },
refine ⟨hc, λ hcf, hf (λ U hU, _)⟩,
rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨x, hxc, hxU⟩,
rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually
(Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists
with ⟨y, ⟨hyab, hyf⟩, hy⟩,
refine mem_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU),
rw diff_subset_iff,
exact subset.trans Icc_subset_Icc_union_Ioc
(union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) },
cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 },
contrapose! hf,
intros U hU,
rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨y, hxy, hyU⟩,
refine mem_of_superset _ hyU, clear_dependent U,
have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩,
by_cases hay : Icc a y ∈ f,
{ refine mem_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _,
rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff],
exact Icc_subset_Icc_union_Icc },
{ exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim },
end
instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)]
[Π i, compact_Icc_space (α i)] : compact_Icc_space (Π i, α i) :=
⟨λ a b, pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc⟩
instance pi.compact_Icc_space' {α β : Type*} [preorder β] [topological_space β]
[compact_Icc_space β] : compact_Icc_space (α → β) :=
pi.compact_Icc_space
instance {α β : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
[preorder β] [topological_space β] [compact_Icc_space β] :
compact_Icc_space (α × β) :=
⟨λ a b, (Icc_prod_eq a b).symm ▸ is_compact_Icc.prod is_compact_Icc⟩
/-- An unordered closed interval in a conditionally complete linear order is compact. -/
lemma is_compact_interval {α : Type*} [conditionally_complete_linear_order α]
[topological_space α] [order_topology α]{a b : α} : is_compact (interval a b) :=
is_compact_Icc
/-- A complete linear order is a compact space.
We do not register an instance for a `[compact_Icc_space α]` because this would only add instances
for products (indexed or not) of complete linear orders, and we have instances with higher priority
that cover these cases. -/
@[priority 100] -- See note [lower instance priority]
instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α]
[topological_space α] [order_topology α] :
compact_space α :=
⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩
section
variables {α : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
instance compact_space_Icc (a b : α) : compact_space (Icc a b) :=
is_compact_iff_compact_space.mp is_compact_Icc
end
/-!
### Min and max elements of a compact set
-/
variables {α β : Type*} [conditionally_complete_linear_order α] [topological_space α]
[order_topology α] [topological_space β]
lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Inf s ∈ s :=
hs.is_closed.cInf_mem ne_s hs.bdd_below
lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Sup s ∈ s :=
@is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_glb s (Inf s) :=
is_glb_cInf ne_s hs.bdd_below
lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_lub s (Sup s) :=
@is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_least s (Inf s) :=
⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩
lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_greatest s (Sup s) :=
@is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_least s x :=
⟨_, hs.is_least_Inf ne_s⟩
lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_greatest s x :=
⟨_, hs.is_greatest_Sup ne_s⟩
lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_glb s x :=
⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩
lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_lub s x :=
⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩
lemma is_compact.exists_Inf_image_eq {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x :=
let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f)
in ⟨x, hxs, hx.symm⟩
lemma is_compact.exists_Sup_image_eq :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃ x ∈ s, Sup (f '' s) = f x :=
@is_compact.exists_Inf_image_eq (order_dual α) _ _ _ _ _
lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) :
s = Icc (Inf s) (Sup s) :=
eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed
/-!
### Extreme value theorem
-/
/-- The **extreme value theorem**: a continuous function realizes its minimum on a compact set. -/
lemma is_compact.exists_forall_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
rcases (hs.image_of_continuous_on hf).exists_is_least (ne_s.image f)
with ⟨_, ⟨x, hxs, rfl⟩, hx⟩,
exact ⟨x, hxs, ball_image_iff.1 hx⟩
end
/-- The **extreme value theorem**: a continuous function realizes its maximum on a compact set. -/
lemma is_compact.exists_forall_ge :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@is_compact.exists_forall_le (order_dual α) _ _ _ _ _
/-- The **extreme value theorem**: if a continuous function `f` tends to infinity away from compact
sets, then it has a global minimum. -/
lemma continuous.exists_forall_le [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_top) :
∃ x, ∀ y, f x ≤ f y :=
begin
inhabit β,
obtain ⟨s : set β, hsc : is_compact s, hsf : ∀ x ∉ s, f (default β) ≤ f x⟩ :=
(has_basis_cocompact.tendsto_iff at_top_basis).1 hlim (f $ default β) trivial,
obtain ⟨x, -, hx⟩ : ∃ x ∈ insert (default β) s, ∀ y ∈ insert (default β) s, f x ≤ f y :=
(hsc.insert (default β)).exists_forall_le (nonempty_insert _ _) hf.continuous_on,
refine ⟨x, λ y, _⟩,
by_cases hy : y ∈ s,
exacts [hx y (or.inr hy), (hx _ (or.inl rfl)).trans (hsf y hy)]
end
/-- The **extreme value theorem**: if a continuous function `f` tends to negative infinity away from
compact sets, then it has a global maximum. -/
lemma continuous.exists_forall_ge [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_bot) :
∃ x, ∀ y, f y ≤ f x :=
@continuous.exists_forall_le (order_dual α) _ _ _ _ _ _ _ hf hlim
/-!
### Image of a closed interval
-/
variables [densely_ordered α] [conditionally_complete_linear_order β] [order_topology β]
{f : α → β} {a b x y : α}
open_locale interval
lemma continuous_on.image_Icc (hab : a ≤ b) (h : continuous_on f $ Icc a b) :
f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) :=
eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩
(is_compact_Icc.image_of_continuous_on h)
lemma continuous_on.image_interval_eq_Icc (h : continuous_on f $ [a, b]) :
f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) :=
begin
cases le_total a b with h2 h2,
{ simp_rw [interval_of_le h2] at h ⊢, exact h.image_Icc h2 },
{ simp_rw [interval_of_ge h2] at h ⊢, exact h.image_Icc h2 },
end
lemma continuous_on.image_interval (h : continuous_on f $ [a, b]) :
f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] :=
begin
refine h.image_interval_eq_Icc.trans (interval_of_le _).symm,
refine cInf_le_cSup _ _ (nonempty_interval.image _); rw h.image_interval_eq_Icc,
exacts [bdd_below_Icc, bdd_above_Icc]
end
|
5fbe57c6758c462776f96fe4a08cc416acb2e503 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/char_zero/quotient.lean | 61ad45384b7d0a147304dc57a24fb0109d59b5db | [
"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,916 | lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import group_theory.quotient_group
/-!
# Lemmas about quotients in characteristic zero
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {R : Type*} [division_ring R] [char_zero R] {p : R}
namespace add_subgroup
/-- `z • r` is a multiple of `p` iff `r` is `pk/z` above a multiple of `p`, where `0 ≤ k < |z|`. -/
lemma zsmul_mem_zmultiples_iff_exists_sub_div {r : R} {z : ℤ} (hz : z ≠ 0) :
z • r ∈ add_subgroup.zmultiples p ↔
∃ k : fin z.nat_abs, r - (k : ℕ) • (p / z : R) ∈ add_subgroup.zmultiples p:=
begin
rw [add_subgroup.mem_zmultiples_iff],
simp_rw [add_subgroup.mem_zmultiples_iff, div_eq_mul_inv, ←smul_mul_assoc, eq_sub_iff_add_eq],
have hz' : (z : R) ≠ 0 := int.cast_ne_zero.mpr hz,
conv_rhs { simp only [←(mul_right_injective₀ hz').eq_iff] { single_pass := tt}, },
simp_rw [←zsmul_eq_mul, smul_add, ←mul_smul_comm, zsmul_eq_mul (z : R)⁻¹, mul_inv_cancel hz',
mul_one, ←coe_nat_zsmul, smul_smul, ←add_smul],
split,
{ rintro ⟨k, h⟩,
simp_rw ← h,
refine ⟨⟨(k % z).to_nat, _⟩, k / z, _⟩,
{ rw [←int.coe_nat_lt, int.to_nat_of_nonneg (int.mod_nonneg _ hz)],
exact (int.mod_lt _ hz).trans_eq (int.abs_eq_nat_abs _) },
rw [fin.coe_mk, int.to_nat_of_nonneg (int.mod_nonneg _ hz), int.div_add_mod] },
{ rintro ⟨k, n, h⟩,
exact ⟨_, h⟩, },
end
lemma nsmul_mem_zmultiples_iff_exists_sub_div {r : R} {n : ℕ} (hn : n ≠ 0) :
n • r ∈ add_subgroup.zmultiples p ↔
∃ k : fin n, r - (k : ℕ) • (p / n : R) ∈ add_subgroup.zmultiples p:=
begin
simp_rw [←coe_nat_zsmul r, zsmul_mem_zmultiples_iff_exists_sub_div (int.coe_nat_ne_zero.mpr hn),
int.cast_coe_nat],
refl,
end
end add_subgroup
namespace quotient_add_group
lemma zmultiples_zsmul_eq_zsmul_iff {ψ θ : R ⧸ add_subgroup.zmultiples p} {z : ℤ} (hz : z ≠ 0) :
z • ψ = z • θ ↔ (∃ k : fin z.nat_abs, ψ = θ + (k : ℕ) • (p / z : R)) :=
begin
induction ψ using quotient.induction_on',
induction θ using quotient.induction_on',
have : (quotient.mk' : R → R ⧸ add_subgroup.zmultiples p) = coe := rfl,
simp only [this],
simp_rw [←coe_zsmul, ←coe_nsmul, ←coe_add, quotient_add_group.eq_iff_sub_mem, ←smul_sub,
←sub_sub, add_subgroup.zsmul_mem_zmultiples_iff_exists_sub_div hz],
end
lemma zmultiples_nsmul_eq_nsmul_iff {ψ θ : R ⧸ add_subgroup.zmultiples p} {n : ℕ} (hz : n ≠ 0) :
n • ψ = n • θ ↔ (∃ k : fin n, ψ = θ + (k : ℕ) • (p / n : R)) :=
begin
simp_rw [←coe_nat_zsmul ψ, ←coe_nat_zsmul θ,
zmultiples_zsmul_eq_zsmul_iff (int.coe_nat_ne_zero.mpr hz), int.cast_coe_nat],
refl,
end
end quotient_add_group
|
8e30a9298f048714ba7a88ae200ceae54afa2b86 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/let1.lean | 1ab06778836fc4d3f1f9807d4222221d29be09fc | [
"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 | 161 | lean | #check
let f x y := x ∧ y,
g x := f x x,
a := g true
in λ (x : a),
let h x y := f x (g y),
b := h
in b
|
2d4248d000671ab56624717f16c205647ee975f1 | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /analytics.lean | 2b7af1ac67dc4017aa2ceb6b7613068e32ebb74c | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,589 | lean | import analysis.complex.polynomial
open declaration tactic
meta def list_constant (e : expr) : tactic (list name) :=
e.fold (return []) $ λ e _ cs,
do env ← get_env,
cs ← cs,
let n := e.const_name in
match (@option.none ℕ) with
| none := if e.is_constant ∧ n ∉ cs
then return (n :: cs)
else return cs
| _ := return cs
end
meta def const_in_def (n : name) : tactic (list name) :=
do d ← get_decl n,
match d with
| thm _ _ t v :=
do lv ← list_constant v.get,
lt ← list_constant t,
return (lv ∪ lt)
| defn _ _ t v _ _ :=
do lv ← list_constant v,
lt ← list_constant t,
return (lv ∪ lt)
| cnst _ _ t _ := list_constant t
| ax _ _ t := list_constant t
end
meta def const_in_def_trans_aux₁ : list name × list (name × list name) →
tactic (list name × list (name × list name))
| ([], l₂) := pure ([], l₂)
| (l₁, l₂) :=
do l' ← l₁.mmap (λ n, do l ← const_in_def n, return (n, l)),
let l2 := l' ++ l₂,
const_in_def_trans_aux₁ ((l'.map prod.snd).join.erase_dup.diff (l2.map prod.fst), l2)
meta def const_in_def_trans_aux₂ : list name × list name →
tactic (list name × list name)
| ([], l₂) := pure ([], l₂)
| (l₁, l₂) :=
do l' ← l₁.mmap const_in_def,
let l2 := l₁ ∪ l₂,
const_in_def_trans_aux₂ (l'.join.erase_dup.diff l2, l2)
meta def const_in_def_trans (n : name) : tactic unit :=
do l ← const_in_def_trans_aux₂ ([n], []),
trace l.2.length,
trace (list.insertion_sort (≤) (l.2.map to_string)),
return ()
set_option profiler true
#eval const_in_def_trans `complex.exists_root
#print environment.is_projection
-- #eval const_in_def_trans `zmodp.is_square_iff_is_square_of_mod_four_eq_one
#print int.le.dest
meta def list_all_consts : tactic (list name) :=
do e ← get_env,
let l : list name := environment.fold e []
(λ d l, match d with
| thm n _ _ _ := n :: l
| defn n _ _ _ _ _ := n :: l
| cnst n _ _ _ := n :: l
| ax n _ _ := n :: l end),
return l
#print unsigned_sz
meta def list_namespace : tactic unit :=
do l ← list_all_consts,
let m := l.filter (λ n, n.get_prefix = `polynomial),
trace m.length,
trace m,
return ()
#eval (name.get_prefix `nat.prime.mod_add_div).to_string
#eval (name.get_prefix (`nat.mod_add_div) = `polynomial : bool)
#eval list_namespace
-- meta def trans_def_all_aux : list name → rbmap name (rbtree name)
-- → rbmap name (rbtree name) → option (rbmap name (rbtree name))
-- | [] m₁ m₂ := pure m₂
-- | (n::l₁) m₁ m₂ :=
-- do l₁ ← m₁.find n,
-- l₂ ← l₁.mmap m₁.find,
-- let l₃ := l₂.join,
-- if l₃ = l₁ then trans_def_all_aux l₁ (m₁.erase n)
-- else sorry
-- meta def trans_def_list (l : list name) : tactic unit :=
-- do
-- map ← l.mmap (λ n, do l' ← const_in_def n, return (n, l)),
-- m ← trans_def_all_aux [`prod.swap] (pure (rbmap.from_list map)),
-- let result := m.to_list,
-- trace (result.map (λ n, (n.1, n.2.length))),
-- return ()
-- meta def trans_def_list_all : tactic unit :=
-- do l ← list_all_consts,
-- trans_def_list l,
-- return ()
#print if_ctx_simp_congr
-- #eval const_in_def_trans `zmodp.quadratic_reciprocity
#print algebra.sub
-- #eval trans_def_list_all
#exit
#print list.union
meta def const_in_def_trans_aux : Π (n : name), tactic (list name)
| n := do d ← get_decl n,
match d with
| thm _ _ t v := do
let v := v.get,
let l := list_constant v,
-- do m ← l.mmap const_in_def_trans_aux,
return (l).erase_dup
| defn _ _ t v _ _ := do
let l := list_constant v,
do m ← l.mmap const_in_def_trans_aux,
return (l).erase_dup
| d := pure []
end
meta def const_in_def_depth_aux : ℕ → name → list name → tactic (list name)
| 0 n p := pure []
| (m+1) n p :=
do d ← get_decl n,
match d with
| thm _ _ t v := do
let v := v.get,
let l := (list_constant v).diff p,
let q := p ++ l,
l' ← l.mmap (λ n, const_in_def_depth_aux m n q),
return (l ++ l'.bind id).erase_dup
| defn _ _ t v _ _ := do
let l := (list_constant v).diff p,
let q := p ++ l,
l' ← l.mmap (λ n, const_in_def_depth_aux m n q),
return (l ++ l'.bind id).erase_dup
| d := pure []
end
meta def const_in_def_depth_aux' : ℕ → Π n : name, tactic (list name)
| 0 n := pure []
| (m+1) n :=
do d ← get_decl n,
match d with
| thm _ _ t v := do
let v := v.get,
let l := list_constant v,
l' ← l.mmap (const_in_def_depth_aux' m),
return (l'.bind id ++ l).erase_dup
| defn _ _ t v _ _ := do
let l := list_constant v,
l' ← l.mmap (const_in_def_depth_aux' m),
return (l'.bind id ++ l).erase_dup
| d := pure []
end
meta def const_in_def_depth (m : ℕ) (n : name) : tactic unit :=
do l ← const_in_def_depth_aux m n [],
trace l.length,
trace l,
return ()
meta def const_in_def_depth' (m : ℕ) (n : name) : tactic unit :=
do l ← const_in_def_depth_aux' m n,
trace l.length,
trace l,
return ()
meta def const_in_def_trans (n : name) : tactic unit :=
do l ← const_in_def_trans_aux n,
trace l.length,
trace l,
return ()
set_option profiler true
-- #eval const_in_def_depth' 3 `polynomial.euclidean_domain
-- #eval const_in_def_depth 5 `polynomial.euclidean_domain
-- meta def const_in_def₂ (n : name) : tactic (list name) :=
-- do l ← const_in_def n,
-- m ← l.mmap const_in_def,
-- trace m,
-- return l
#print simp_config
#exit
data.zmod.basic data.polynomial tactic.norm_num data.rat
instance h {p : ℕ} (hp : nat.prime p) : has_repr (zmodp p hp) := fin.has_repr _
open polynomial
#eval (11 * X ^ 20 + 7 * X ^ 9 + 12 * X + 11 :
polynomial ℚ) / (22 * X ^ 2 - 1)
|
ba1f541867fa3b19040063043fdadec3d2e7471a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/anc1.lean | 581a45abff675b7034a7c5bd98cb2fe5b3c700f4 | [
"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 | 1,297 | lean | check (⟨1, 2⟩ : nat × nat)
check (⟨trivial, trivial⟩ : true ∧ true)
example : true := sorry
check (⟨1, sorry⟩ : Σ x : nat, x > 0)
open tactic
check show true, from ⟨⟩
check (⟨1, by intro1 >> contradiction⟩ : ∃ x : nat, 1 ≠ 0)
universe variables u v
check λ (A B C : Prop),
assume (Ha : A) (Hb : B) (Hc : C),
show B ∧ A, from
⟨Hb, Ha⟩
check λ (A B C : Prop),
assume (Ha : A) (Hb : B) (Hc : C),
show B ∧ A ∧ C ∧ A, from
⟨Hb, ⟨Ha, ⟨Hc, Ha⟩⟩⟩
check λ (A B C : Prop),
assume (Ha : A) (Hb : B) (Hc : C),
show B ∧ A ∧ C ∧ A, from
⟨Hb, Ha, Hc, Ha⟩
check λ (A B C : Prop),
assume (Ha : A) (Hb : B) (Hc : C),
show ((B ∧ true) ∧ A) ∧ (C ∧ A), from
⟨⟨⟨Hb, ⟨⟩⟩, Ha⟩, ⟨Hc, Ha⟩⟩
check λ (A : Type u) (P : A → Prop) (Q : A → Prop),
take (a : A), assume (H1 : P a) (H2 : Q a),
show ∃ x, P x ∧ Q x, from
⟨a, ⟨H1, H2⟩⟩
check λ (A : Type u) (P : A → Prop) (Q : A → Prop),
take (a : A) (b : A), assume (H1 : P a) (H2 : Q b),
show ∃ x y, P x ∧ Q y, from
⟨a, ⟨b, ⟨H1, H2⟩⟩⟩
check λ (A : Type u) (P : A → Prop) (Q : A → Prop),
take (a : A) (b : A), assume (H1 : P a) (H2 : Q b),
show ∃ x y, P x ∧ Q y, from
⟨a, b, H1, H2⟩
|
efad7ce0c69a54a8898bf57429cef14042fad6fd | 6f4750ff03c8be1d6c0b1b809ff6ac541b9d5a22 | /MOC.lean | 4eee9815ff713973d4cbc7c10ccec5da24fb342c | [] | no_license | benating/Lean_Test | 1809b5e15df9edcdf4a3388f53d2205f29c89ac2 | c07099804a86347b4ec836f54530f62e22534bdb | refs/heads/master | 1,628,468,905,337 | 1,510,426,597,000 | 1,510,426,597,000 | 108,762,297 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 706 | lean | namespace hidden
inductive exp : Type
| num : ℕ → exp
| add : exp → exp → exp
namespace exp
infixl `+` := add
def eval : exp → ℕ
| (num x) := x
| (exp1 + exp2) := eval exp1 + eval exp2
theorem normal_forms (e : exp) : (∃ x : ℕ, eval e = x) :=
begin
induction e,
-- Base case
case num a
{ exact ⟨eval (num a), by refl⟩ },
-- Recursive case
case add exp1 exp2
{ have inductive_step : ∃ x : ℕ, eval exp1 + eval exp2 = x,
from
match ih_1, ih_2 with
⟨y, exp1_norm⟩, ⟨z, exp2_norm⟩ := ⟨(y + z), by rw [exp1_norm, exp2_norm]⟩
end,
exact ⟨eval (exp1 + exp2), by refl⟩,
},
end
end exp
end hidden |
dc3e54552a25f5e9ebb806a0a03038fe91b01eb9 | 717dd237d6a1fdd246152ec47f261c5244f9eba6 | /imo/src/imo1969-q1.lean | 664faec287ae46a422dcef6931fb3808f6f4342a | [] | no_license | lacker/kata | 32866813a6097218878f0ce327040d65a0aeb145 | 96b1d63e395c8cf02dc6abbbb5253f4cfe5fded6 | refs/heads/master | 1,692,275,692,563 | 1,691,955,719,000 | 1,691,955,719,000 | 87,217,280 | 19 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,364 | lean | import tactic
import tactic.basic
import tactic.linarith
import tactic.norm_cast
import tactic.ring
open int
open nat
/-
The 1969 IMO, problem 1:
Prove that there are infinitely many natural numbers $a$ with the following property:
the number $z = n^4 + a$ is not prime for any natural number $n$.
The key to the solution is that you can factor this into the product of two polynomials, if a = 4*m^4.
-/
lemma factorization (m n: ℤ): (n^2 + 2*m^2 - 2*n*m) * (n^2 + 2*m^2 + 2*n*m) = n^4 + 4*m^4
:= by ring
/-
To show that the product is not prime, we need to show each of the factors is at least 2, which we can
do with a sum-of-squares expression.
-/
lemma left_factor_large (m n: ℤ) (h: m > 1): (n^2 + 2*m^2 - 2*n*m) > 1 :=
have h: (n^2 + 2*m^2 - 2*n*m) = (m-n)^2 + m^2, by ring,
begin
rw h,
nlinarith,
end
lemma right_factor_large (m n: ℤ) (h: m > 1): (n^2 + 2*m^2 + 2*n*m) > 1 :=
have h: (n^2 + 2*m^2 + 2*n*m) = (m+n)^2 + m^2, by ring,
begin
rw h,
nlinarith,
end
/-
The factorization is over the integers, but we need the nonprimality over the natural numbers.
-/
lemma int_large (a: ℤ) (h: a > 1) : a.nat_abs > 1 :=
have a = ↑(a.nat_abs) ∨ a = -↑(a.nat_abs), from nat_abs_eq a,
or.elim this
(assume: a = ↑(a.nat_abs), by linarith)
(assume: a = -↑(a.nat_abs), by linarith)
lemma int_not_prime (a b: ℤ) (c: ℕ) (h1: a > 1) (h2: b > 1) (h3: a*b = ↑c) : ¬ prime c :=
have h4: (a*b).nat_abs = a.nat_abs * b.nat_abs, from nat_abs_mul a b,
have h5: a.nat_abs * b.nat_abs = c, by finish,
norm_num.not_prime_helper a.nat_abs b.nat_abs c h5 (int_large a h1) (int_large b h2)
lemma polynomial_not_prime (m n: ℕ) (h1: m > 1) : ¬ prime (n^4 + 4*m^4) :=
have h2: of_nat m > 1, from coe_nat_lt.mpr h1,
begin
refine int_not_prime _ _ _ (left_factor_large ↑m ↑n h2) (right_factor_large ↑m ↑n h2) _,
rw factorization,
norm_cast
end
/-
Now we just need to show this works for an arbitrarily large a, to prove there are infinitely many of them.
a = 4*(2+b)^4 should do. So m = 2+b.
-/
theorem imo1969_q1: ∀ b: ℕ, ∃ a: ℕ, a ≥ b ∧ ∀ n: ℕ, ¬ prime (n^4 + a) :=
assume b,
have h1: 2+b > 1, by linarith,
have b^2 ≥ b, by nlinarith,
have h2: 4*(2+b)^4 ≥ b, by nlinarith,
begin
fapply exists.intro,
exact 4*(2+b)^4,
apply and.intro h2,
assume n,
exact polynomial_not_prime (2+b) n h1
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.