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
ec4f49f4680edf06390407d2054bf8aa4beb4ec9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/metric_space/completion.lean
15c20b610c288162f43f618de05fe5d9b085aa34
[ "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
8,648
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.completion import topology.metric_space.isometry import topology.instances.real /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space uniform_space.completion open_locale filter noncomputable theory universes u variables {α : Type u} [pseudo_metric_space α] namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma completion.uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma completion.dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact (completion.uniform_continuous_dist.continuous.comp (continuous.prod_mk continuous_id continuous_id : _) : _) }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { refine is_closed_eq completion.uniform_continuous_dist.continuous _, exact completion.uniform_continuous_dist.continuous.comp (@continuous_swap (completion α) (completion α) _ _) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _), { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) := continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) := continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) := continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous.comp continuous_snd continuous_snd), exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed.union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_sets_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated_space (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma completion.uniformity_dist' : uniformity (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a pseudo_metric space. -/ instance completion.metric_space : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma completion.coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq end metric
e3ccc24c81349a79d65ca4d22b788ee5cc0aad94
367134ba5a65885e863bdc4507601606690974c1
/src/data/qpf/multivariate/constructions/const.lean
e4a0f2b452770cf96c52b89f12799af5274decca
[ "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
1,915
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import control.functor.multivariate import data.qpf.multivariate.basic /-! # Constant functors are QPFs Constant functors map every type vectors to the same target type. This is a useful device for constructing data types from more basic types that are not actually functorial. For instance `const n nat` makes `nat` into a functor that can be used in a functor-based data type specification. -/ universes u namespace mvqpf open_locale mvfunctor variables (n : ℕ) /-- Constant multivariate functor -/ @[nolint unused_arguments] def const (A : Type*) (v : typevec.{u} n) : Type* := A instance const.inhabited {A α} [inhabited A] : inhabited (const n A α) := ⟨ (default A : A) ⟩ namespace const open mvfunctor mvpfunctor variables {n} {A : Type u} {α β : typevec.{u} n} (f : α ⟹ β) /-- Constructor for constant functor -/ protected def mk (x : A) : (const n A) α := x /-- Destructor for constant functor -/ protected def get (x : (const n A) α) : A := x @[simp] protected lemma mk_get (x : (const n A) α) : const.mk (const.get x) = x := rfl @[simp] protected lemma get_mk (x : A) : const.get (const.mk x : const n A α) = x := rfl /-- `map` for constant functor -/ protected def map : (const n A) α → (const n A) β := λ x, x instance : mvfunctor (const n A) := { map := λ α β f, const.map } lemma map_mk (x : A) : f <$$> const.mk x = const.mk x := rfl lemma get_map (x : (const n A) α) : const.get (f <$$> x) = const.get x := rfl instance mvqpf : @mvqpf _ (const n A) (mvqpf.const.mvfunctor) := { P := mvpfunctor.const n A, abs := λ α x, mvpfunctor.const.get x, repr := λ α x, mvpfunctor.const.mk n x, abs_repr := by intros; simp, abs_map := by intros; simp; refl, } end const end mvqpf
229f2a847f13c910c0162a5d13e18e5bdca18007
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/Tactic/Subst.lean
950fb439f2f8c1f6700271db77c3b20de3e06f84
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,349
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) : MetaM (FVarSubst × MVarId) := withMVarContext mvarId do let tag ← getMVarTag mvarId checkNotAssigned mvarId `subst let hFVarIdOriginal := hFVarId let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (α, lhs, rhs) => do let a := if symm then rhs else lhs let b := if symm then lhs else rhs let a ← whnf a match a with | Expr.fvar aFVarId _ => do let aFVarIdOriginal := aFVarId trace[Meta.Tactic.subst]! "substituting {a} (id: {aFVarId} with {b}" let mctx ← getMCtx if mctx.exprDependsOn b aFVarId then throwTacticEx `subst mvarId msg!"'{a}' occurs at{indentExpr b}" let aLocalDecl ← getLocalDecl aFVarId let (vars, mvarId) ← revert mvarId #[aFVarId, hFVarId] true let (twoVars, mvarId) ← introNP mvarId 2 trace[Meta.Tactic.subst]! "reverted variables {vars}" let aFVarId := twoVars[0] let a := mkFVar aFVarId let hFVarId := twoVars[1] let h := mkFVar hFVarId withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId let type := mvarDecl.type let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => unreachable! | some (α, lhs, rhs) => do let b := if symm then lhs else rhs let mctx ← getMCtx let depElim := mctx.exprDependsOn mvarDecl.type hFVarId let cont (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do let major ← if symm then pure h else mkEqSymm h let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let minor := newMVar let newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major assignExprMVar mvarId newVal let mvarId := newMVar.mvarId! let mvarId ← if clearH then let mvarId ← clear mvarId hFVarId clear mvarId aFVarId else pure mvarId let (newFVars, mvarId) ← introNP mvarId (vars.size - 2) let fvarSubst ← newFVars.size.foldM (init := fvarSubst) fun i (fvarSubst : FVarSubst) => let var := vars[i+2] let newFVar := newFVars[i] pure $ fvarSubst.insert var (mkFVar newFVar) let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId) let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId) pure (fvarSubst, mvarId) if depElim then do let newType := type.replaceFVar a b let reflB ← mkEqRefl b let newType := newType.replaceFVar h reflB if symm then let motive ← mkLambdaFVars #[a, h] type cont motive newType else /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ let hAuxType ← mkEq b a let motive ← withLocalDeclD `_h hAuxType fun hAux => do let hAuxSymm ← mkEqSymm hAux /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm mkLambdaFVars #[a, hAux] newType cont motive newType else let motive ← mkLambdaFVars #[a] type let newType := type.replaceFVar a b cont motive newType | _ => let eqMsg := if symm then "(t = x)" else "(x = t)" throwTacticEx `subst mvarId msg!"invalid equality proof, it is not of the form {eqMsg}{indentExpr hLocalDecl.type}\nafter WHNF, variable expected, but obtained{indentExpr a}" def subst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := withMVarContext mvarId do let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | some (α, lhs, rhs) => let rhs ← whnf rhs if rhs.isFVar then (·.2) <$> substCore mvarId hFVarId true else do let lhs ← whnf lhs if lhs.isFVar then (·.2) <$> substCore mvarId hFVarId else do throwTacticEx `subst mvarId msg!"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr hLocalDecl.type}" | none => let mctx ← getMCtx let lctx ← getLCtx let some (fvarId, symm) ← lctx.findDeclM? fun localDecl => do if localDecl.isAuxDecl then pure none else match (← matchEq? localDecl.type) with | some (α, lhs, rhs) => if rhs.isFVar && rhs.fvarId! == hFVarId && !mctx.exprDependsOn lhs hFVarId then pure $ some (localDecl.fvarId, true) else if lhs.isFVar && lhs.fvarId! == hFVarId && !mctx.exprDependsOn rhs hFVarId then pure $ some (localDecl.fvarId, false) else pure none | _ => pure none | throwTacticEx `subst mvarId msg!"did not find equation for eliminating '{mkFVar hFVarId}'" (·.2) <$> substCore mvarId fvarId symm builtin_initialize registerTraceClass `Meta.Tactic.subst end Meta end Lean
26ad1396b9b27561bc54bd168fa32a67bbb8e3f9
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Elab/MutualDef.lean
4d68cccc1e6c8cbe51334261f4181adf9dc331e5
[ "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
28,278
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Meta.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /- DefView after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers kind : DefKind shortDeclName : Name declName : Name levelNames : List Name numParams : Nat type : Expr -- including the parameters valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | Exception.error ref msg => throw (Exception.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" private def elabFunType {α} (ref : Syntax) (xs : Array Expr) (view : DefView) (k : Array Expr → Expr → TermElabM α) : TermElabM α := do match view.type? with | some typeStx => elabTypeWithAutoBoundImplicit typeStx fun type => do synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type registerFailedToInferDefTypeInfo type typeStx k xs (← mkForallFVars xs type) | none => let hole := mkHole ref let type ← elabType hole registerFailedToInferDefTypeInfo type ref k xs (← mkForallFVars xs type) def isAutoImplicit (fvarId : FVarId) : TermElabM Bool := return (← read).autoBoundImplicits.any fun x => x.fvarId! == fvarId private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let mut headers := #[] for view in views do let newHeader ← withRef view.ref do let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration withDeclName declName <| withAutoBoundImplicitLocal <| withLevelNames levelNames <| elabBinders (catchAutoBoundImplicit := true) view.binders.getArgs fun xs => do let refForElabFunType := view.value elabFunType refForElabFunType xs view fun xs type => do let mut type ← mkForallFVars (← read).autoBoundImplicits.toArray type let xs ← addAutoBoundImplicits xs let levelNames ← getLevelNames if view.type?.isSome then Term.synthesizeSyntheticMVarsNoPostponing type ← instantiateMVars type let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds let newHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, numParams := xs.size, type := type, valueStx := view.value : DefViewElabHeader } check headers newHeader pure newHeader headers := headers.push newHeader pure headers private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereDeclsAsStructInst : Macro | `(whereDecls|where $[$decls:letRecDecl$[;]?]*) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letRecDecl|$attrs:attributes $decl:letDecl) => Macro.throwErrorAt stx "attributes are 'where' elements are currently not supported here" | `(letRecDecl|$decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letRecDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl | `(letRecDecl|$decl:letIdDecl) => pure decl | _ => unreachable! let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) val ← `(fun $[$binders]* => $val:term) `(structInstField|$id:ident := $val) | _ => unreachable! `({ $[$structInstFields,]* }) | _ => unreachable! /- Recall that ``` def declValSimple := parser! " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := parser! Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind `Lean.Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind `Lean.Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind `Lean.Parser.Term.whereDecls then expandWhereDeclsAsStructInst declVal else Macro.throwErrorAt declVal "unexpected definition value" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do let valStx ← liftMacroM $ declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State TermElabM Unit := do headers.forM fun header => collectUsedFVars header.type values.forM collectUsedFVars toLift.forM fun letRecToLift => do collectUsedFVars letRecToLift.type collectUsedFVars letRecToLift.val private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts $ k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← findLocalDecl? fvarId) with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt! toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := NameMap NameSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set pure usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : NameSet) : M NameSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then pure s₁ else markModified pure $ s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := NameMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds pure freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) } pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => trace[Elab.definition.mkClosure]! "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => let toProcess ← pushLocalDecl toProcess fvarId userName type bi mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls } pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl closed : Expr -- expression used to replace occurrences of the let-rec FVarId toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId! let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs assignExprMVar toLift.mvarId c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val := val, type := type } } private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := NameMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert (mainFVars.get! i).fvarId! (mkAppN (Lean.mkConst (mainHeaders.get! i).declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i] let val ← mkLambdaFVars sectionVars mainVals[i] let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName lparams := [], -- we set it later modifiers := header.modifiers type := type value := val } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (init := preDefs) fun preDefs c => let type := Closure.mkForall c.localDecls c.toLift.type let val := Closure.mkLambda c.localDecls c.toLift.val preDefs.push { ref := c.ref kind := kind declName := c.toLift.declName lparams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } type := type value := val } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable, isPartial := mainHeaders.any fun h => h.modifiers.isPartial, isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mctx ← getMCtx let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing if isExample views then pure () else let values ← values.mapM (instantiateMVars ·) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift let preDefs ← levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames addPreDefinitions preDefs end Term namespace Command def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] mkDefView modifiers d[1] runTermElabM none fun vars => Term.elabMutualDef vars views end Command end Lean.Elab
15d128258de4185249a457f6a9076316b59dd2ff
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/buffer/basic_auto.lean
b3d83ef82bf4fb3585640a87bd80d197dcdb09ca
[]
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
2,111
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon General utility functions for buffers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.buffer import Mathlib.data.array.lemmas import Mathlib.control.traversable.instances import Mathlib.PostPort universes u_1 namespace Mathlib namespace buffer protected instance inhabited {α : Type u_1} : Inhabited (buffer α) := { default := nil } theorem ext {α : Type u_1} {b₁ : buffer α} {b₂ : buffer α} : to_list b₁ = to_list b₂ → b₁ = b₂ := sorry protected instance decidable_eq (α : Type u_1) [DecidableEq α] : DecidableEq (buffer α) := id fun (_v : buffer α) => sigma.cases_on _v fun (fst : ℕ) (snd : array fst α) (w : buffer α) => sigma.cases_on w fun (w_fst : ℕ) (w_snd : array w_fst α) => decidable.by_cases (fun (ᾰ : fst = w_fst) => Eq._oldrec (fun (w_snd : array fst α) => decidable.by_cases (fun (ᾰ : snd = w_snd) => Eq._oldrec (is_true sorry) ᾰ) fun (ᾰ : ¬snd = w_snd) => isFalse sorry) ᾰ w_snd) fun (ᾰ : ¬fst = w_fst) => isFalse sorry @[simp] theorem to_list_append_list {α : Type u_1} {xs : List α} {b : buffer α} : to_list (append_list b xs) = to_list b ++ xs := sorry @[simp] theorem append_list_mk_buffer {α : Type u_1} {xs : List α} : append_list mk_buffer xs = array.to_buffer (list.to_array xs) := sorry /-- The natural equivalence between lists and buffers, using `list.to_buffer` and `buffer.to_list`. -/ def list_equiv_buffer (α : Type u_1) : List α ≃ buffer α := equiv.mk list.to_buffer to_list sorry sorry protected instance traversable : traversable buffer := equiv.traversable list_equiv_buffer protected instance is_lawful_traversable : is_lawful_traversable buffer := equiv.is_lawful_traversable list_equiv_buffer end Mathlib
c88dff4f7a5c3ae9d4e926750355f8b42dcdaa2b
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/super/clause_ops.lean
6f42e1742de8df292996a70f3007d148cb0d382e
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,378
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 open monad tactic expr namespace super local attribute [instance] has_monad_lift_to_has_coe meta def on_left_at {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a type and returns a list of proofs of that type (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c.open_constn (c.num_quants + i), @guard tactic _ (op.1.get_lit 0).is_neg _, new_hyps ← f (op.1.get_lit 0).formula, return $ new_hyps.map (λnew_hyp, (op.1.inst new_hyp.2).close_constn (op.2 ++ new_hyp.1)) meta def on_left_at_dn {m} [monad m] [alternative m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis of ¬type and returns a list of proofs of false (f : expr → m (list (list expr × expr))) : m (list clause) := do qf ← c.open_constn c.num_quants, op ← qf.1.open_constn c.num_lits, lci ← (op.2.nth i).to_monad, @guard tactic _ (qf.1.get_lit i).is_neg _, h ← mk_local_def `h $ imp (qf.1.get_lit i).formula c.local_false, new_hyps ← f h, return $ new_hyps.map $ λnew_hyp, (((clause.mk 0 0 new_hyp.2 c.local_false c.local_false).close_const h).inst (op.1.close_const lci).proof).close_constn (qf.2 ++ op.2.remove_nth i ++ new_hyp.1) meta def on_right_at {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis and returns a list of proofs of false (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c.open_constn (c.num_quants + i), @guard tactic _ ((op.1.get_lit 0).is_pos) _, h ← mk_local_def `h (op.1.get_lit 0).formula, new_hyps ← f h, return $ new_hyps.map (λnew_hyp, (op.1.inst (lambdas [h] new_hyp.2)).close_constn (op.2 ++ new_hyp.1)) meta def on_right_at' {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis and returns a list of proofs (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c.open_constn (c.num_quants + i), @guard tactic _ ((op.1.get_lit 0).is_pos) _, h ← mk_local_def `h (op.1.get_lit 0).formula, new_hyps ← f h, for new_hyps (λnew_hyp, do type ← infer_type new_hyp.2, nh ← mk_local_def `nh $ imp type c.local_false, return $ (op.1.inst (lambdas [h] (app nh new_hyp.2))).close_constn (op.2 ++ new_hyp.1 ++ [nh])) meta def on_first_right (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c.num_lits, [on_right_at c i f] meta def on_first_right' (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c.num_lits, [on_right_at' c i f] meta def on_first_left (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c.num_lits, [on_left_at c i f] meta def on_first_left_dn (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c.num_lits, [on_left_at_dn c i f] end super
f1a975f864ff5319814d031a0d72559f1da43ed7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/dilation.lean
d9b8ecdeb9dc626b98f93db27ccc9a90e1eadcd1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,799
lean
/- Copyright (c) 2022 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Dilations of emetric and metric spaces Authors: Hanting Zhang -/ import topology.metric_space.antilipschitz import data.fun_like.basic /-! # Dilations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define dilations, i.e., maps between emetric spaces that satisfy `edist (f x) (f y) = r * edist x y` for some `r ∉ {0, ∞}`. The value `r = 0` is not allowed because we want dilations of (e)metric spaces to be automatically injective. The value `r = ∞` is not allowed because this way we can define `dilation.ratio f : ℝ≥0`, not `dilation.ratio f : ℝ≥0∞`. Also, we do not often need maps sending distinct points to points at infinite distance. ## Main defintions * `dilation.ratio f : ℝ≥0`: the value of `r` in the relation above, defaulting to 1 in the case where it is not well-defined. ## Implementation notes The type of dilations defined in this file are also referred to as "similarities" or "similitudes" by other authors. The name `dilation` was choosen to match the Wikipedia name. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `pseudo_emetric_space` and we specialize to `pseudo_metric_space` and `metric_space` when needed. ## TODO - Introduce dilation equivs. - Refactor the `isometry` API to match the `*_hom_class` API below. ## References - https://en.wikipedia.org/wiki/Dilation_(metric_space) - [Marcel Berger, *Geometry*][berger1987] -/ noncomputable theory open function set open_locale topology ennreal nnreal classical section defs variables (α : Type*) (β : Type*) [pseudo_emetric_space α] [pseudo_emetric_space β] /-- A dilation is a map that uniformly scales the edistance between any two points. -/ structure dilation := (to_fun : α → β) (edist_eq' : ∃ r : ℝ≥0, r ≠ 0 ∧ ∀ x y : α, edist (to_fun x) (to_fun y) = r * edist x y) /-- `dilation_class F α β r` states that `F` is a type of `r`-dilations. You should extend this typeclass when you extend `dilation`. -/ class dilation_class (F : Type*) (α β : out_param $ Type*) [pseudo_emetric_space α] [pseudo_emetric_space β] extends fun_like F α (λ _, β) := (edist_eq' : ∀ (f : F), ∃ r : ℝ≥0, r ≠ 0 ∧ ∀ (x y : α), edist (f x) (f y) = r * edist x y) end defs namespace dilation variables {α : Type*} {β : Type*} {γ : Type*} {F : Type*} {G : Type*} section setup variables [pseudo_emetric_space α] [pseudo_emetric_space β] instance to_dilation_class : dilation_class (dilation α β) α β := { coe := to_fun, coe_injective' := λ f g h, by { cases f; cases g; congr', }, edist_eq' := λ f, edist_eq' f } instance : has_coe_to_fun (dilation α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : dilation α β} : f.to_fun = (f : α → β) := rfl @[simp] lemma coe_mk (f : α → β) (h) : ⇑(⟨f, h⟩ : dilation α β) = f := rfl lemma congr_fun {f g : dilation α β} (h : f = g) (x : α) : f x = g x := fun_like.congr_fun h x lemma congr_arg (f : dilation α β) {x y : α} (h : x = y) : f x = f y := fun_like.congr_arg f h @[ext] theorem ext {f g : dilation α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h lemma ext_iff {f g : dilation α β} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff @[simp] lemma mk_coe (f : dilation α β) (h) : dilation.mk f h = f := ext $ λ _, rfl /-- Copy of a `dilation` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[simps { fully_applied := ff }] protected def copy (f : dilation α β) (f' : α → β) (h : f' = ⇑f) : dilation α β := { to_fun := f', edist_eq' := h.symm ▸ f.edist_eq' } lemma copy_eq_self (f : dilation α β) {f' : α → β} (h : f' = f) : f.copy f' h = f := fun_like.ext' h /-- The ratio of a dilation `f`. If the ratio is undefined (i.e., the distance between any two points in `α` is either zero or infinity), then we choose one as the ratio. -/ def ratio [dilation_class F α β] (f : F) : ℝ≥0 := if ∀ x y : α, edist x y = 0 ∨ edist x y = ⊤ then 1 else (dilation_class.edist_eq' f).some lemma ratio_ne_zero [dilation_class F α β] (f : F) : ratio f ≠ 0 := begin rw ratio, split_ifs, { exact one_ne_zero, }, exact (dilation_class.edist_eq' f).some_spec.1, end lemma ratio_pos [dilation_class F α β] (f : F) : 0 < ratio f := (ratio_ne_zero f).bot_lt @[simp] lemma edist_eq [dilation_class F α β] (f : F) (x y : α) : edist (f x) (f y) = ratio f * edist x y := begin rw ratio, split_ifs with key, { rcases dilation_class.edist_eq' f with ⟨r, hne, hr⟩, replace hr := hr x y, cases key x y, { simp only [hr, h, mul_zero] }, { simp [hr, h, hne] } }, exact (dilation_class.edist_eq' f).some_spec.2 x y, end @[simp] lemma nndist_eq {α β F : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [dilation_class F α β] (f : F) (x y : α) : nndist (f x) (f y) = ratio f * nndist x y := by simp only [← ennreal.coe_eq_coe, ← edist_nndist, ennreal.coe_mul, edist_eq] @[simp] lemma dist_eq {α β F : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [dilation_class F α β] (f : F) (x y : α) : dist (f x) (f y) = ratio f * dist x y := by simp only [dist_nndist, nndist_eq, nnreal.coe_mul] /-- The `ratio` is equal to the distance ratio for any two points with nonzero finite distance. `dist` and `nndist` versions below -/ lemma ratio_unique [dilation_class F α β] {f : F} {x y : α} {r : ℝ≥0} (h₀ : edist x y ≠ 0) (htop : edist x y ≠ ⊤) (hr : edist (f x) (f y) = r * edist x y) : r = ratio f := by simpa only [hr, ennreal.mul_eq_mul_right h₀ htop, ennreal.coe_eq_coe] using edist_eq f x y /-- The `ratio` is equal to the distance ratio for any two points with nonzero finite distance; `nndist` version -/ lemma ratio_unique_of_nndist_ne_zero {α β F : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [dilation_class F α β] {f : F} {x y : α} {r : ℝ≥0} (hxy : nndist x y ≠ 0) (hr : nndist (f x) (f y) = r * nndist x y) : r = ratio f := ratio_unique (by rwa [edist_nndist, ennreal.coe_ne_zero]) (edist_ne_top x y) (by rw [edist_nndist, edist_nndist, hr, ennreal.coe_mul]) /-- The `ratio` is equal to the distance ratio for any two points with nonzero finite distance; `dist` version -/ lemma ratio_unique_of_dist_ne_zero {α β} {F : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [dilation_class F α β] {f : F} {x y : α} {r : ℝ≥0} (hxy : dist x y ≠ 0) (hr : dist (f x) (f y) = r * dist x y) : r = ratio f := ratio_unique_of_nndist_ne_zero (nnreal.coe_ne_zero.1 hxy) $ nnreal.eq $ by rw [coe_nndist, hr, nnreal.coe_mul, coe_nndist] /-- Alternative `dilation` constructor when the distance hypothesis is over `nndist` -/ def mk_of_nndist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : α → β) (h : ∃ (r : ℝ≥0), r ≠ 0 ∧ ∀ (x y : α), nndist (f x) (f y) = r * nndist x y) : dilation α β := { to_fun := f, edist_eq' := begin rcases h with ⟨r, hne, h⟩, refine ⟨r, hne, λ x y, _⟩, rw [edist_nndist, edist_nndist, ← ennreal.coe_mul, h x y], end } @[simp] lemma coe_mk_of_nndist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : α → β) (h) : ⇑(mk_of_nndist_eq f h : dilation α β) = f := rfl @[simp] lemma mk_coe_of_nndist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : dilation α β) (h) : dilation.mk_of_nndist_eq f h = f := ext $ λ _, rfl /-- Alternative `dilation` constructor when the distance hypothesis is over `dist` -/ def mk_of_dist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : α → β) (h : ∃ (r : ℝ≥0), r ≠ 0 ∧ ∀ (x y : α), dist (f x) (f y) = r * dist x y) : dilation α β := mk_of_nndist_eq f $ h.imp $ λ r hr, ⟨hr.1, λ x y, nnreal.eq $ by rw [coe_nndist, hr.2, nnreal.coe_mul, coe_nndist]⟩ @[simp] lemma coe_mk_of_dist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : α → β) (h) : ⇑(mk_of_dist_eq f h : dilation α β) = f := rfl @[simp] lemma mk_coe_of_dist_eq {α β} [pseudo_metric_space α] [pseudo_metric_space β] (f : dilation α β) (h) : dilation.mk_of_dist_eq f h = f := ext $ λ _, rfl end setup section pseudo_emetric_dilation variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables [dilation_class F α β] [dilation_class G β γ] variables (f : F) (g : G) {x y z : α} {s : set α} lemma lipschitz : lipschitz_with (ratio f) (f : α → β) := λ x y, (edist_eq f x y).le lemma antilipschitz : antilipschitz_with (ratio f)⁻¹ (f : α → β) := λ x y, have hr : ratio f ≠ 0 := ratio_ne_zero f, by exact_mod_cast (ennreal.mul_le_iff_le_inv (ennreal.coe_ne_zero.2 hr) ennreal.coe_ne_top).1 (edist_eq f x y).ge /-- A dilation from an emetric space is injective -/ protected lemma injective {α : Type*} [emetric_space α] [dilation_class F α β] (f : F) : injective f := (antilipschitz f).injective /-- The identity is a dilation -/ protected def id (α) [pseudo_emetric_space α] : dilation α α := { to_fun := _root_.id, edist_eq' := ⟨1, one_ne_zero, λ x y, by simp only [id.def, ennreal.coe_one, one_mul]⟩ } instance : inhabited (dilation α α) := ⟨dilation.id α⟩ @[simp, protected] lemma coe_id : ⇑(dilation.id α) = id := rfl lemma id_ratio : ratio (dilation.id α) = 1 := begin by_cases h : ∀ x y : α, edist x y = 0 ∨ edist x y = ∞, { rw [ratio, if_pos h] }, { push_neg at h, rcases h with ⟨x, y, hne⟩, refine (ratio_unique hne.1 hne.2 _).symm, simp } end /-- The composition of dilations is a dilation -/ def comp (g : dilation β γ) (f : dilation α β) : dilation α γ := { to_fun := g ∘ f, edist_eq' := ⟨ratio g * ratio f, mul_ne_zero (ratio_ne_zero g) (ratio_ne_zero f), λ x y, by { simp only [edist_eq, ennreal.coe_mul], ring, }⟩ } lemma comp_assoc {δ : Type*} [pseudo_emetric_space δ] (f : dilation α β) (g : dilation β γ) (h : dilation γ δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (g : dilation β γ) (f : dilation α β) : (g.comp f : α → γ) = g ∘ f := rfl lemma comp_apply (g : dilation β γ) (f : dilation α β) (x : α) : (g.comp f : α → γ) x = (g (f x)) := rfl /-- Ratio of the composition `g.comp f` of two dilations is the product of their ratios. We assume that the domain `α` of `f` is nontrivial, otherwise `ratio f = ratio (g.comp f) = 1` but `ratio g` may have any value. -/ @[simp] lemma comp_ratio {g : dilation β γ} {f : dilation α β} (hne : ∃ x y : α, edist x y ≠ 0 ∧ edist x y ≠ ⊤) : ratio (g.comp f) = ratio g * ratio f := begin rcases hne with ⟨x, y, hα⟩, have hgf := (edist_eq (g.comp f) x y).symm, simp only [dist_eq, coe_comp, ← mul_assoc, mul_eq_mul_right_iff] at hgf, rw [edist_eq, edist_eq, ← mul_assoc, ennreal.mul_eq_mul_right hα.1 hα.2] at hgf, rwa [← ennreal.coe_eq_coe, ennreal.coe_mul], end @[simp] lemma comp_id (f : dilation α β) : f.comp (dilation.id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : dilation α β) : (dilation.id β).comp f = f := ext $ λ x, rfl instance : monoid (dilation α α) := { one := dilation.id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : dilation α α) = dilation.id α := rfl lemma mul_def (f g : dilation α α) : f * g = f.comp g := rfl @[simp] lemma coe_one : ⇑(1 : dilation α α) = _root_.id := rfl @[simp] lemma coe_mul (f g : dilation α α) : ⇑(f * g) = f ∘ g := rfl lemma cancel_right {g₁ g₂ : dilation β γ} {f : dilation α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, dilation.ext $ hf.forall.2 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : dilation β γ} {f₁ f₂ : dilation α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, dilation.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ /-- A dilation from a metric space is a uniform inducing map -/ protected theorem uniform_inducing : uniform_inducing (f : α → β) := (antilipschitz f).uniform_inducing (lipschitz f).uniform_continuous lemma tendsto_nhds_iff {ι : Type*} {g : ι → α} {a : filter ι} {b : α} : filter.tendsto g a (𝓝 b) ↔ filter.tendsto ((f : α → β) ∘ g) a (𝓝 (f b)) := (dilation.uniform_inducing f).inducing.tendsto_nhds_iff /-- A dilation is continuous. -/ lemma to_continuous : continuous (f : α → β) := (lipschitz f).continuous /-- Dilations scale the diameter by `ratio f` in pseudoemetric spaces. -/ lemma ediam_image (s : set α) : emetric.diam ((f : α → β) '' s) = ratio f * emetric.diam s := begin refine ((lipschitz f).ediam_image_le s).antisymm _, apply ennreal.mul_le_of_le_div', rw [div_eq_mul_inv, mul_comm, ← ennreal.coe_inv], exacts [(antilipschitz f).le_mul_ediam_image s, ratio_ne_zero f], end /-- A dilation scales the diameter of the range by `ratio f`. -/ lemma ediam_range : emetric.diam (range (f : α → β)) = ratio f * emetric.diam (univ : set α) := by { rw ← image_univ, exact ediam_image f univ } /-- A dilation maps balls to balls and scales the radius by `ratio f`. -/ lemma maps_to_emetric_ball (x : α) (r : ℝ≥0∞) : maps_to (f : α → β) (emetric.ball x r) (emetric.ball (f x) (ratio f * r)) := λ y hy, (edist_eq f y x).trans_lt $ (ennreal.mul_lt_mul_left (ennreal.coe_ne_zero.2 $ ratio_ne_zero f) ennreal.coe_ne_top).2 hy /-- A dilation maps closed balls to closed balls and scales the radius by `ratio f`. -/ lemma maps_to_emetric_closed_ball (x : α) (r' : ℝ≥0∞) : maps_to (f : α → β) (emetric.closed_ball x r') (emetric.closed_ball (f x) (ratio f * r')) := λ y hy, (edist_eq f y x).trans_le $ mul_le_mul_left' hy _ lemma comp_continuous_on_iff {γ} [topological_space γ] {g : γ → α} {s : set γ} : continuous_on ((f : α → β) ∘ g) s ↔ continuous_on g s := (dilation.uniform_inducing f).inducing.continuous_on_iff.symm lemma comp_continuous_iff {γ} [topological_space γ] {g : γ → α} : continuous ((f : α → β) ∘ g) ↔ continuous g := (dilation.uniform_inducing f).inducing.continuous_iff.symm end pseudo_emetric_dilation --section section emetric_dilation variables [emetric_space α] /-- A dilation from a metric space is a uniform embedding -/ protected theorem uniform_embedding [pseudo_emetric_space β] [dilation_class F α β] (f : F) : uniform_embedding f := (antilipschitz f).uniform_embedding (lipschitz f).uniform_continuous /-- A dilation from a metric space is an embedding -/ protected theorem embedding [pseudo_emetric_space β] [dilation_class F α β] (f : F) : embedding (f : α → β) := (dilation.uniform_embedding f).embedding /-- A dilation from a complete emetric space is a closed embedding -/ protected theorem closed_embedding [complete_space α] [emetric_space β] [dilation_class F α β] (f : F) : closed_embedding f := (antilipschitz f).closed_embedding (lipschitz f).uniform_continuous end emetric_dilation --section section pseudo_metric_dilation variables [pseudo_metric_space α] [pseudo_metric_space β] [dilation_class F α β] (f : F) /-- A dilation scales the diameter by `ratio f` in pseudometric spaces. -/ lemma diam_image (s : set α) : metric.diam ((f : α → β) '' s) = ratio f * metric.diam s := by { simp [metric.diam, ediam_image, ennreal.to_real_mul], } lemma diam_range : metric.diam (range (f : α → β)) = ratio f * metric.diam (univ : set α) := by rw [← image_univ, diam_image] /-- A dilation maps balls to balls and scales the radius by `ratio f`. -/ lemma maps_to_ball (x : α) (r' : ℝ) : maps_to (f : α → β) (metric.ball x r') (metric.ball (f x) (ratio f * r')) := λ y hy, (dist_eq f y x).trans_lt $ (mul_lt_mul_left $ nnreal.coe_pos.2 $ ratio_pos f).2 hy /-- A dilation maps spheres to spheres and scales the radius by `ratio f`. -/ lemma maps_to_sphere (x : α) (r' : ℝ) : maps_to (f : α → β) (metric.sphere x r') (metric.sphere (f x) (ratio f * r')) := λ y hy, metric.mem_sphere.mp hy ▸ dist_eq f y x /-- A dilation maps closed balls to closed balls and scales the radius by `ratio f`. -/ lemma maps_to_closed_ball (x : α) (r' : ℝ) : maps_to (f : α → β) (metric.closed_ball x r') (metric.closed_ball (f x) (ratio f * r')) := λ y hy, (dist_eq f y x).trans_le $ mul_le_mul_of_nonneg_left hy (nnreal.coe_nonneg _) end pseudo_metric_dilation -- section end dilation
dfeb16e93de8b07cf0fdff6206779d1296b1893f
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/group/inj_surj.lean
bf1fdfa80c2364ce696edef35173dda6c19bd7aa
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
10,056
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.defs import logic.function.basic /-! # Lifting algebraic data classes along injective/surjective maps This file provides definitions that are meant to deal with situations such as the following: Suppose that `G` is a group, and `H` is a type endowed with `has_one H`, `has_mul H`, and `has_inv H`. Suppose furthermore, that `f : G → H` is a surjective map that respects the multiplication, and the unit elements. Then `H` satisfies the group axioms. The relevant definition in this case is `function.surjective.group`. Dually, there is also `function.injective.group`. And there are versions for (additive) (commutative) semigroups/monoids. -/ namespace function /-! ### Injective -/ namespace injective variables {M₁ : Type*} {M₂ : Type*} [has_mul M₁] /-- A type endowed with `*` is a semigroup, if it admits an injective map that preserves `*` to a semigroup. -/ @[to_additive add_semigroup "A type endowed with `+` is an additive semigroup, if it admits an injective map that preserves `+` to an additive semigroup."] protected def semigroup [semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : semigroup M₁ := { mul_assoc := λ x y z, hf $ by erw [mul, mul, mul, mul, mul_assoc], ..‹has_mul M₁› } /-- A type endowed with `*` is a commutative semigroup, if it admits an injective map that preserves `*` to a commutative semigroup. -/ @[to_additive add_comm_semigroup "A type endowed with `+` is an additive commutative semigroup, if it admits an injective map that preserves `+` to an additive commutative semigroup."] protected def comm_semigroup [comm_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semigroup M₁ := { mul_comm := λ x y, hf $ by erw [mul, mul, mul_comm], .. hf.semigroup f mul } /-- A type endowed with `*` is a left cancel semigroup, if it admits an injective map that preserves `*` to a left cancel semigroup. -/ @[to_additive add_left_cancel_semigroup "A type endowed with `+` is an additive left cancel semigroup, if it admits an injective map that preserves `+` to an additive left cancel semigroup."] protected def left_cancel_semigroup [left_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : left_cancel_semigroup M₁ := { mul := (*), mul_left_cancel := λ x y z H, hf $ (mul_right_inj (f x)).1 $ by erw [← mul, ← mul, H]; refl, .. hf.semigroup f mul } /-- A type endowed with `*` is a right cancel semigroup, if it admits an injective map that preserves `*` to a right cancel semigroup. -/ @[to_additive add_right_cancel_semigroup "A type endowed with `+` is an additive right cancel semigroup, if it admits an injective map that preserves `+` to an additive right cancel semigroup."] protected def right_cancel_semigroup [right_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f) (mul : ∀ x y, f (x * y) = f x * f y) : right_cancel_semigroup M₁ := { mul := (*), mul_right_cancel := λ x y z H, hf $ (mul_left_inj (f y)).1 $ by erw [← mul, ← mul, H]; refl, .. hf.semigroup f mul } variables [has_one M₁] /-- A type endowed with `1` and `*` is a monoid, if it admits an injective map that preserves `1` and `*` to a monoid. -/ @[to_additive add_monoid "A type endowed with `0` and `+` is an additive monoid, if it admits an injective map that preserves `0` and `+` to an additive monoid."] protected def monoid [monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid M₁ := { one_mul := λ x, hf $ by erw [mul, one, one_mul], mul_one := λ x, hf $ by erw [mul, one, mul_one], .. hf.semigroup f mul, ..‹has_one M₁› } /-- A type endowed with `1` and `*` is a left cancel monoid, if it admits an injective map that preserves `1` and `*` to a left cancel monoid. -/ @[to_additive add_left_cancel_monoid "A type endowed with `0` and `+` is an additive left cancel monoid, if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid."] protected def left_cancel_monoid [left_cancel_monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : left_cancel_monoid M₁ := { .. hf.left_cancel_semigroup f mul, .. hf.monoid f one mul } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits an injective map that preserves `1` and `*` to a commutative monoid. -/ @[to_additive add_comm_monoid "A type endowed with `0` and `+` is an additive commutative monoid, if it admits an injective map that preserves `0` and `+` to an additive commutative monoid."] protected def comm_monoid [comm_monoid M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid M₁ := { .. hf.comm_semigroup f mul, .. hf.monoid f one mul } variables [has_inv M₁] /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a group. -/ @[to_additive add_group "A type endowed with `0` and `+` is an additive group, if it admits an injective map that preserves `0` and `+` to an additive group."] protected def group [group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : group M₁ := { mul_left_inv := λ x, hf $ by erw [mul, inv, mul_left_inv, one], .. hf.monoid f one mul, ..‹has_inv M₁› } /-- A type endowed with `1`, `*` and `⁻¹` is a commutative group, if it admits an injective map that preserves `1`, `*` and `⁻¹` to a commutative group. -/ @[to_additive add_comm_group "A type endowed with `0` and `+` is an additive commutative group, if it admits an injective map that preserves `0` and `+` to an additive commutative group."] protected def comm_group [comm_group M₂] (f : M₁ → M₂) (hf : injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : comm_group M₁ := { .. hf.comm_monoid f one mul, .. hf.group f one mul inv } end injective /-! ### Surjective -/ namespace surjective variables {M₁ : Type*} {M₂ : Type*} [has_mul M₂] /-- A type endowed with `*` is a semigroup, if it admits a surjective map that preserves `*` from a semigroup. -/ @[to_additive add_semigroup "A type endowed with `+` is an additive semigroup, if it admits a surjective map that preserves `+` from an additive semigroup."] protected def semigroup [semigroup M₁] (f : M₁ → M₂) (hf : surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : semigroup M₂ := { mul_assoc := hf.forall₃.2 $ λ x y z, by simp only [← mul, mul_assoc], ..‹has_mul M₂› } /-- A type endowed with `*` is a commutative semigroup, if it admits a surjective map that preserves `*` from a commutative semigroup. -/ @[to_additive add_comm_semigroup "A type endowed with `+` is an additive commutative semigroup, if it admits a surjective map that preserves `+` from an additive commutative semigroup."] protected def comm_semigroup [comm_semigroup M₁] (f : M₁ → M₂) (hf : surjective f) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semigroup M₂ := { mul_comm := hf.forall₂.2 $ λ x y, by erw [← mul, ← mul, mul_comm], .. hf.semigroup f mul } variables [has_one M₂] /-- A type endowed with `1` and `*` is a monoid, if it admits a surjective map that preserves `1` and `*` from a monoid. -/ @[to_additive add_monoid "A type endowed with `0` and `+` is an additive monoid, if it admits a surjective map that preserves `0` and `+` to an additive monoid."] protected def monoid [monoid M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid M₂ := { one_mul := hf.forall.2 $ λ x, by erw [← one, ← mul, one_mul], mul_one := hf.forall.2 $ λ x, by erw [← one, ← mul, mul_one], ..‹has_one M₂›, .. hf.semigroup f mul } /-- A type endowed with `1` and `*` is a commutative monoid, if it admits a surjective map that preserves `1` and `*` from a commutative monoid. -/ @[to_additive add_comm_monoid "A type endowed with `0` and `+` is an additive commutative monoid, if it admits a surjective map that preserves `0` and `+` to an additive commutative monoid."] protected def comm_monoid [comm_monoid M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid M₂ := { .. hf.comm_semigroup f mul, .. hf.monoid f one mul } variables [has_inv M₂] /-- A type endowed with `1`, `*` and `⁻¹` is a group, if it admits a surjective map that preserves `1`, `*` and `⁻¹` from a group. -/ @[to_additive add_group "A type endowed with `0` and `+` is an additive group, if it admits a surjective map that preserves `0` and `+` to an additive group."] protected def group [group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : group M₂ := { mul_left_inv := hf.forall.2 $ λ x, by erw [← inv, ← mul, mul_left_inv, one]; refl, ..‹has_inv M₂›, .. hf.monoid f one mul } /-- A type endowed with `1`, `*` and `⁻¹` is a commutative group, if it admits a surjective map that preserves `1`, `*` and `⁻¹` from a commutative group. -/ @[to_additive add_comm_group "A type endowed with `0` and `+` is an additive commutative group, if it admits a surjective map that preserves `0` and `+` to an additive commutative group."] protected def comm_group [comm_group M₁] (f : M₁ → M₂) (hf : surjective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) : comm_group M₂ := { .. hf.comm_monoid f one mul, .. hf.group f one mul inv } end surjective end function
096347cc46e785367a956ad90638ab1d43fa99b6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/inseparable.lean
2ad7c59a4d8d9cd4cf0cd1fe1764c17e765d3e75
[ "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
19,894
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Yury G. Kudryashov -/ import topology.continuous_on import data.setoid.basic import tactic.tfae /-! # Inseparable points in a topological space In this file we define * `specializes` (notation: `x ⤳ y`) : a relation saying that `𝓝 x ≤ 𝓝 y`; * `inseparable`: a relation saying that two points in a topological space have the same neighbourhoods; equivalently, they can't be separated by an open set; * `inseparable_setoid X`: same relation, as a `setoid`; * `separation_quotient X`: the quotient of `X` by its `inseparable_setoid`. We also prove various basic properties of the relation `inseparable`. ## Notations - `x ⤳ y`: notation for `specializes x y`; - `x ~ y` is used as a local notation for `inseparable x y`; - `𝓝 x` is the neighbourhoods filter `nhds x` of a point `x`, defined elsewhere. ## Tags topological space, separation setoid -/ open set filter function open_locale topological_space filter variables {X Y Z α ι : Type*} {π : ι → Type*} [topological_space X] [topological_space Y] [topological_space Z] [∀ i, topological_space (π i)] {x y z : X} {s : set X} {f : X → Y} /-! ### `specializes` relation -/ /-- `x` specializes to `y` (notation: `x ⤳ y`) if either of the following equivalent properties hold: * `𝓝 x ≤ 𝓝 y`; this property is used as the definition; * `pure x ≤ 𝓝 y`; in other words, any neighbourhood of `y` contains `x`; * `y ∈ closure {x}`; * `closure {y} ⊆ closure {x}`; * for any closed set `s` we have `x ∈ s → y ∈ s`; * for any open set `s` we have `y ∈ s → x ∈ s`; * `y` is a cluster point of the filter `pure x = 𝓟 {x}`. This relation defines a `preorder` on `X`. If `X` is a T₀ space, then this preorder is a partial order. If `X` is a T₁ space, then this partial order is trivial : `x ⤳ y ↔ x = y`. -/ def specializes (x y : X) : Prop := 𝓝 x ≤ 𝓝 y infix ` ⤳ `:300 := specializes /-- A collection of equivalent definitions of `x ⤳ y`. The public API is given by `iff` lemmas below. -/ lemma specializes_tfae (x y : X) : tfae [x ⤳ y, pure x ≤ 𝓝 y, ∀ s : set X, is_open s → y ∈ s → x ∈ s, ∀ s : set X, is_closed s → x ∈ s → y ∈ s, y ∈ closure ({x} : set X), closure ({y} : set X) ⊆ closure {x}, cluster_pt y (pure x)] := begin tfae_have : 1 → 2, from (pure_le_nhds _).trans, tfae_have : 2 → 3, from λ h s hso hy, h (hso.mem_nhds hy), tfae_have : 3 → 4, from λ h s hsc hx, of_not_not $ λ hy, h sᶜ hsc.is_open_compl hy hx, tfae_have : 4 → 5, from λ h, h _ is_closed_closure (subset_closure $ mem_singleton _), tfae_have : 6 ↔ 5, from is_closed_closure.closure_subset_iff.trans singleton_subset_iff, tfae_have : 5 ↔ 7, by rw [mem_closure_iff_cluster_pt, principal_singleton], tfae_have : 5 → 1, { refine λ h, (nhds_basis_opens _).ge_iff.2 _, rintro s ⟨hy, ho⟩, rcases mem_closure_iff.1 h s ho hy with ⟨z, hxs, (rfl : z = x)⟩, exact ho.mem_nhds hxs }, tfae_finish end lemma specializes_iff_nhds : x ⤳ y ↔ 𝓝 x ≤ 𝓝 y := iff.rfl lemma specializes_iff_pure : x ⤳ y ↔ pure x ≤ 𝓝 y := (specializes_tfae x y).out 0 1 alias specializes_iff_nhds ↔ specializes.nhds_le_nhds _ alias specializes_iff_pure ↔ specializes.pure_le_nhds _ lemma specializes_iff_forall_open : x ⤳ y ↔ ∀ s : set X, is_open s → y ∈ s → x ∈ s := (specializes_tfae x y).out 0 2 lemma specializes.mem_open (h : x ⤳ y) (hs : is_open s) (hy : y ∈ s) : x ∈ s := specializes_iff_forall_open.1 h s hs hy lemma is_open.not_specializes (hs : is_open s) (hx : x ∉ s) (hy : y ∈ s) : ¬ x ⤳ y := λ h, hx $ h.mem_open hs hy lemma specializes_iff_forall_closed : x ⤳ y ↔ ∀ s : set X, is_closed s → x ∈ s → y ∈ s := (specializes_tfae x y).out 0 3 lemma specializes.mem_closed (h : x ⤳ y) (hs : is_closed s) (hx : x ∈ s) : y ∈ s := specializes_iff_forall_closed.1 h s hs hx lemma is_closed.not_specializes (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬ x ⤳ y := λ h, hy $ h.mem_closed hs hx lemma specializes_iff_mem_closure : x ⤳ y ↔ y ∈ closure ({x} : set X) := (specializes_tfae x y).out 0 4 alias specializes_iff_mem_closure ↔ specializes.mem_closure _ lemma specializes_iff_closure_subset : x ⤳ y ↔ closure ({y} : set X) ⊆ closure {x} := (specializes_tfae x y).out 0 5 alias specializes_iff_closure_subset ↔ specializes.closure_subset _ lemma filter.has_basis.specializes_iff {ι} {p : ι → Prop} {s : ι → set X} (h : (𝓝 y).has_basis p s) : x ⤳ y ↔ ∀ i, p i → x ∈ s i := specializes_iff_pure.trans h.ge_iff lemma specializes_rfl : x ⤳ x := le_rfl @[refl] lemma specializes_refl (x : X) : x ⤳ x := specializes_rfl @[trans] lemma specializes.trans : x ⤳ y → y ⤳ z → x ⤳ z := le_trans lemma specializes_of_nhds_within (h₁ : 𝓝[s] x ≤ 𝓝[s] y) (h₂ : x ∈ s) : x ⤳ y := specializes_iff_pure.2 $ calc pure x ≤ 𝓝[s] x : le_inf (pure_le_nhds _) (le_principal_iff.2 h₂) ... ≤ 𝓝[s] y : h₁ ... ≤ 𝓝 y : inf_le_left lemma specializes.map_of_continuous_at (h : x ⤳ y) (hy : continuous_at f y) : f x ⤳ f y := specializes_iff_pure.2 $ λ s hs, mem_pure.2 $ mem_preimage.1 $ mem_of_mem_nhds $ hy.mono_left h hs lemma specializes.map (h : x ⤳ y) (hf : continuous f) : f x ⤳ f y := h.map_of_continuous_at hf.continuous_at lemma inducing.specializes_iff (hf : inducing f) : f x ⤳ f y ↔ x ⤳ y := by simp only [specializes_iff_mem_closure, hf.closure_eq_preimage_closure_image, image_singleton, mem_preimage] lemma subtype_specializes_iff {p : X → Prop} (x y : subtype p) : x ⤳ y ↔ (x : X) ⤳ y := inducing_coe.specializes_iff.symm @[simp] lemma specializes_prod {x₁ x₂ : X} {y₁ y₂ : Y} : (x₁, y₁) ⤳ (x₂, y₂) ↔ x₁ ⤳ x₂ ∧ y₁ ⤳ y₂ := by simp only [specializes, nhds_prod_eq, prod_le_prod] lemma specializes.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ⤳ x₂) (hy : y₁ ⤳ y₂) : (x₁, y₁) ⤳ (x₂, y₂) := specializes_prod.2 ⟨hx, hy⟩ @[simp] lemma specializes_pi {f g : Π i, π i} : f ⤳ g ↔ ∀ i, f i ⤳ g i := by simp only [specializes, nhds_pi, pi_le_pi] lemma not_specializes_iff_exists_open : ¬ x ⤳ y ↔ ∃ (S : set X), is_open S ∧ y ∈ S ∧ x ∉ S := by { rw [specializes_iff_forall_open], push_neg, refl } lemma not_specializes_iff_exists_closed : ¬ x ⤳ y ↔ ∃ (S : set X), is_closed S ∧ x ∈ S ∧ y ∉ S := by { rw [specializes_iff_forall_closed], push_neg, refl } variable (X) /-- Specialization forms a preorder on the topological space. -/ def specialization_preorder : preorder X := { le := λ x y, y ⤳ x, lt := λ x y, y ⤳ x ∧ ¬(x ⤳ y), .. preorder.lift (order_dual.to_dual ∘ 𝓝) } variable {X} /-- A continuous function is monotone with respect to the specialization preorders on the domain and the codomain. -/ lemma continuous.specialization_monotone (hf : continuous f) : @monotone _ _ (specialization_preorder X) (specialization_preorder Y) f := λ x y h, h.map hf /-! ### `inseparable` relation -/ /-- Two points `x` and `y` in a topological space are `inseparable` if any of the following equivalent properties hold: - `𝓝 x = 𝓝 y`; we use this property as the definition; - for any open set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_open`; - for any closed set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_closed`; - `x ∈ closure {y}` and `y ∈ closure {x}`, see `inseparable_iff_mem_closure`; - `closure {x} = closure {y}`, see `inseparable_iff_closure_eq`. -/ def inseparable (x y : X) : Prop := 𝓝 x = 𝓝 y local infix ` ~ ` := inseparable lemma inseparable_def : x ~ y ↔ 𝓝 x = 𝓝 y := iff.rfl lemma inseparable_iff_specializes_and : x ~ y ↔ x ⤳ y ∧ y ⤳ x := le_antisymm_iff lemma inseparable.specializes (h : x ~ y) : x ⤳ y := h.le lemma inseparable.specializes' (h : x ~ y) : y ⤳ x := h.ge lemma specializes.antisymm (h₁ : x ⤳ y) (h₂ : y ⤳ x) : x ~ y := le_antisymm h₁ h₂ lemma inseparable_iff_forall_open : x ~ y ↔ ∀ s : set X, is_open s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_open, ← forall_and_distrib, ← iff_def, iff.comm] lemma not_inseparable_iff_exists_open : ¬(x ~ y) ↔ ∃ s : set X, is_open s ∧ xor (x ∈ s) (y ∈ s) := by simp [inseparable_iff_forall_open, ← xor_iff_not_iff] lemma inseparable_iff_forall_closed : x ~ y ↔ ∀ s : set X, is_closed s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_closed, ← forall_and_distrib, ← iff_def] lemma inseparable_iff_mem_closure : x ~ y ↔ x ∈ closure ({y} : set X) ∧ y ∈ closure ({x} : set X) := inseparable_iff_specializes_and.trans $ by simp only [specializes_iff_mem_closure, and_comm] lemma inseparable_iff_closure_eq : x ~ y ↔ closure ({x} : set X) = closure {y} := by simp only [inseparable_iff_specializes_and, specializes_iff_closure_subset, ← subset_antisymm_iff, eq_comm] lemma inseparable_of_nhds_within_eq (hx : x ∈ s) (hy : y ∈ s) (h : 𝓝[s] x = 𝓝[s] y) : x ~ y := (specializes_of_nhds_within h.le hx).antisymm (specializes_of_nhds_within h.ge hy) lemma inducing.inseparable_iff (hf : inducing f) : f x ~ f y ↔ x ~ y := by simp only [inseparable_iff_specializes_and, hf.specializes_iff] lemma subtype_inseparable_iff {p : X → Prop} (x y : subtype p) : x ~ y ↔ (x : X) ~ y := inducing_coe.inseparable_iff.symm @[simp] lemma inseparable_prod {x₁ x₂ : X} {y₁ y₂ : Y} : (x₁, y₁) ~ (x₂, y₂) ↔ x₁ ~ x₂ ∧ y₁ ~ y₂ := by simp only [inseparable, nhds_prod_eq, prod_inj] lemma inseparable.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ~ x₂) (hy : y₁ ~ y₂) : (x₁, y₁) ~ (x₂, y₂) := inseparable_prod.2 ⟨hx, hy⟩ @[simp] lemma inseparable_pi {f g : Π i, π i} : f ~ g ↔ ∀ i, f i ~ g i := by simp only [inseparable, nhds_pi, funext_iff, pi_inj] namespace inseparable @[refl] lemma refl (x : X) : x ~ x := eq.refl (𝓝 x) lemma rfl : x ~ x := refl x @[symm] lemma symm (h : x ~ y) : y ~ x := h.symm @[trans] lemma trans (h₁ : x ~ y) (h₂ : y ~ z) : x ~ z := h₁.trans h₂ lemma nhds_eq (h : x ~ y) : 𝓝 x = 𝓝 y := h lemma mem_open_iff (h : x ~ y) (hs : is_open s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_open.1 h s hs lemma mem_closed_iff (h : x ~ y) (hs : is_closed s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_closed.1 h s hs lemma map_of_continuous_at (h : x ~ y) (hx : continuous_at f x) (hy : continuous_at f y) : f x ~ f y := (h.specializes.map_of_continuous_at hy).antisymm (h.specializes'.map_of_continuous_at hx) lemma map (h : x ~ y) (hf : continuous f) : f x ~ f y := h.map_of_continuous_at hf.continuous_at hf.continuous_at end inseparable lemma is_closed.not_inseparable (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y := λ h, hy $ (h.mem_closed_iff hs).1 hx lemma is_open.not_inseparable (hs : is_open s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y := λ h, hy $ (h.mem_open_iff hs).1 hx /-! ### Separation quotient In this section we define the quotient of a topological space by the `inseparable` relation. -/ variable (X) /-- A `setoid` version of `inseparable`, used to define the `separation_quotient`. -/ def inseparable_setoid : setoid X := { r := (~), .. setoid.comap 𝓝 ⊥ } /-- The quotient of a topological space by its `inseparable_setoid`. This quotient is guaranteed to be a T₀ space. -/ @[derive topological_space] def separation_quotient := quotient (inseparable_setoid X) variables {X} {t : set (separation_quotient X)} namespace separation_quotient /-- The natural map from a topological space to its separation quotient. -/ def mk : X → separation_quotient X := quotient.mk' lemma quotient_map_mk : quotient_map (mk : X → separation_quotient X) := quotient_map_quot_mk lemma continuous_mk : continuous (mk : X → separation_quotient X) := continuous_quot_mk @[simp] lemma mk_eq_mk : mk x = mk y ↔ x ~ y := quotient.eq' lemma surjective_mk : surjective (mk : X → separation_quotient X) := surjective_quot_mk _ @[simp] lemma range_mk : range (mk : X → separation_quotient X) = univ := surjective_mk.range_eq instance [nonempty X] : nonempty (separation_quotient X) := nonempty.map mk ‹_› instance [inhabited X] : inhabited (separation_quotient X) := ⟨mk default⟩ instance [subsingleton X] : subsingleton (separation_quotient X) := surjective_mk.subsingleton lemma preimage_image_mk_open (hs : is_open s) : mk ⁻¹' (mk '' s) = s := begin refine subset.antisymm _ (subset_preimage_image _ _), rintro x ⟨y, hys, hxy⟩, exact ((mk_eq_mk.1 hxy).mem_open_iff hs).1 hys end lemma is_open_map_mk : is_open_map (mk : X → separation_quotient X) := λ s hs, quotient_map_mk.is_open_preimage.1 $ by rwa preimage_image_mk_open hs lemma preimage_image_mk_closed (hs : is_closed s) : mk ⁻¹' (mk '' s) = s := begin refine subset.antisymm _ (subset_preimage_image _ _), rintro x ⟨y, hys, hxy⟩, exact ((mk_eq_mk.1 hxy).mem_closed_iff hs).1 hys end lemma inducing_mk : inducing (mk : X → separation_quotient X) := ⟨le_antisymm (continuous_iff_le_induced.1 continuous_mk) (λ s hs, ⟨mk '' s, is_open_map_mk s hs, preimage_image_mk_open hs⟩)⟩ lemma is_closed_map_mk : is_closed_map (mk : X → separation_quotient X) := inducing_mk.is_closed_map $ by { rw [range_mk], exact is_closed_univ } @[simp] lemma comap_mk_nhds_mk : comap mk (𝓝 (mk x)) = 𝓝 x := (inducing_mk.nhds_eq_comap _).symm @[simp] lemma comap_mk_nhds_set_image : comap mk (𝓝ˢ (mk '' s)) = 𝓝ˢ s := (inducing_mk.nhds_set_eq_comap _).symm lemma map_mk_nhds : map mk (𝓝 x) = 𝓝 (mk x) := by rw [← comap_mk_nhds_mk, map_comap_of_surjective surjective_mk] lemma map_mk_nhds_set : map mk (𝓝ˢ s) = 𝓝ˢ (mk '' s) := by rw [← comap_mk_nhds_set_image, map_comap_of_surjective surjective_mk] lemma comap_mk_nhds_set : comap mk (𝓝ˢ t) = 𝓝ˢ (mk ⁻¹' t) := by conv_lhs { rw [← image_preimage_eq t surjective_mk, comap_mk_nhds_set_image] } lemma preimage_mk_closure : mk ⁻¹' (closure t) = closure (mk ⁻¹' t) := is_open_map_mk.preimage_closure_eq_closure_preimage continuous_mk t lemma preimage_mk_interior : mk ⁻¹' (interior t) = interior (mk ⁻¹' t) := is_open_map_mk.preimage_interior_eq_interior_preimage continuous_mk t lemma preimage_mk_frontier : mk ⁻¹' (frontier t) = frontier (mk ⁻¹' t) := is_open_map_mk.preimage_frontier_eq_frontier_preimage continuous_mk t lemma image_mk_closure : mk '' closure s = closure (mk '' s) := (image_closure_subset_closure_image continuous_mk).antisymm $ is_closed_map_mk.closure_image_subset _ lemma map_prod_map_mk_nhds (x : X) (y : Y) : map (prod.map mk mk) (𝓝 (x, y)) = 𝓝 (mk x, mk y) := by rw [nhds_prod_eq, ← prod_map_map_eq', map_mk_nhds, map_mk_nhds, nhds_prod_eq] lemma map_mk_nhds_within_preimage (s : set (separation_quotient X)) (x : X) : map mk (𝓝[mk ⁻¹' s] x) = 𝓝[s] (mk x) := by rw [nhds_within, ← comap_principal, filter.push_pull, nhds_within, map_mk_nhds] /-- Lift a map `f : X → α` such that `inseparable x y → f x = f y` to a map `separation_quotient X → α`. -/ def lift (f : X → α) (hf : ∀ x y, x ~ y → f x = f y) : separation_quotient X → α := λ x, quotient.lift_on' x f hf @[simp] lemma lift_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) (x : X) : lift f hf (mk x) = f x := rfl @[simp] lemma lift_comp_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) : lift f hf ∘ mk = f := rfl @[simp] lemma tendsto_lift_nhds_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X} {l : filter α} : tendsto (lift f hf) (𝓝 $ mk x) l ↔ tendsto f (𝓝 x) l := by simp only [← map_mk_nhds, tendsto_map'_iff, lift_comp_mk] @[simp] lemma tendsto_lift_nhds_within_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X} {s : set (separation_quotient X)} {l : filter α} : tendsto (lift f hf) (𝓝[s] (mk x)) l ↔ tendsto f (𝓝[mk ⁻¹' s] x) l := by simp only [← map_mk_nhds_within_preimage, tendsto_map'_iff, lift_comp_mk] @[simp] lemma continuous_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {x : X} : continuous_at (lift f hf) (mk x) ↔ continuous_at f x := tendsto_lift_nhds_mk @[simp] lemma continuous_within_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {s : set (separation_quotient X)} {x : X} : continuous_within_at (lift f hf) s (mk x) ↔ continuous_within_at f (mk ⁻¹' s) x := tendsto_lift_nhds_within_mk @[simp] lemma continuous_on_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {s : set (separation_quotient X)} : continuous_on (lift f hf) s ↔ continuous_on f (mk ⁻¹' s) := by simp only [continuous_on, surjective_mk.forall, continuous_within_at_lift, mem_preimage] @[simp] lemma continuous_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} : continuous (lift f hf) ↔ continuous f := by simp only [continuous_iff_continuous_on_univ, continuous_on_lift, preimage_univ] /-- Lift a map `f : X → Y → α` such that `inseparable a b → inseparable c d → f a c = f b d` to a map `separation_quotient X → separation_quotient Y → α`. -/ def lift₂ (f : X → Y → α) (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) : separation_quotient X → separation_quotient Y → α := λ x y, quotient.lift_on₂' x y f hf @[simp] lemma lift₂_mk {f : X → Y → α} (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) (x : X) (y : Y) : lift₂ f hf (mk x) (mk y) = f x y := rfl @[simp] lemma tendsto_lift₂_nhds {f : X → Y → α} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} {l : filter α} : tendsto (uncurry $ lift₂ f hf) (𝓝 (mk x, mk y)) l ↔ tendsto (uncurry f) (𝓝 (x, y)) l := by { rw [← map_prod_map_mk_nhds, tendsto_map'_iff], refl } @[simp] lemma tendsto_lift₂_nhds_within {f : X → Y → α} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} {s : set (separation_quotient X × separation_quotient Y)} {l : filter α} : tendsto (uncurry $ lift₂ f hf) (𝓝[s] (mk x, mk y)) l ↔ tendsto (uncurry f) (𝓝[prod.map mk mk ⁻¹' s] (x, y)) l := by { rw [nhds_within, ← map_prod_map_mk_nhds, ← filter.push_pull, comap_principal], refl } @[simp] lemma continuous_at_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} : continuous_at (uncurry $ lift₂ f hf) (mk x, mk y) ↔ continuous_at (uncurry f) (x, y) := tendsto_lift₂_nhds @[simp] lemma continuous_within_at_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {s : set (separation_quotient X × separation_quotient Y)} {x : X} {y : Y} : continuous_within_at (uncurry $ lift₂ f hf) s (mk x, mk y) ↔ continuous_within_at (uncurry f) (prod.map mk mk ⁻¹' s) (x, y) := tendsto_lift₂_nhds_within @[simp] lemma continuous_on_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {s : set (separation_quotient X × separation_quotient Y)} : continuous_on (uncurry $ lift₂ f hf) s ↔ continuous_on (uncurry f) (prod.map mk mk ⁻¹' s) := begin simp_rw [continuous_on, (surjective_mk.prod_map surjective_mk).forall, prod.forall, prod.map, continuous_within_at_lift₂], refl end @[simp] lemma continuous_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} : continuous (uncurry $ lift₂ f hf) ↔ continuous (uncurry f) := by simp only [continuous_iff_continuous_on_univ, continuous_on_lift₂, preimage_univ] end separation_quotient
44d051ef7af90d17ac286eecd2a6c13b969f79c7
6e41ee3ac9b96e8980a16295cc21f131e731884f
/hott/algebra/precategory/functor.hlean
5b1fc5b3ce4b48f53c122a87c791e79302376de0
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,988
hlean
-- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Floris van Doorn, Jakob von Raumer import .basic types.pi open function precategory eq prod equiv is_equiv sigma sigma.ops truncation open pi structure functor (C D : Precategory) : Type := (obF : C → D) (homF : Π ⦃a b : C⦄, hom a b → hom (obF a) (obF b)) (respect_id : Π (a : C), homF (ID a) = ID (obF a)) (respect_comp : Π {a b c : C} (g : hom b c) (f : hom a b), homF (g ∘ f) = homF g ∘ homF f) infixl `⇒`:25 := functor namespace functor variables {C D E : Precategory} persistent attribute obF [coercion] persistent attribute homF [coercion] -- "functor C D" is equivalent to a certain sigma type set_option unifier.max_steps 38500 protected definition sigma_char : (Σ (obF : C → D) (homF : Π ⦃a b : C⦄, hom a b → hom (obF a) (obF b)), (Π (a : C), homF (ID a) = ID (obF a)) × (Π {a b c : C} (g : hom b c) (f : hom a b), homF (g ∘ f) = homF g ∘ homF f)) ≃ (functor C D) := begin fapply equiv.mk, intro S, fapply functor.mk, exact (S.1), exact (S.2.1), exact (pr₁ S.2.2), exact (pr₂ S.2.2), fapply adjointify, intro F, apply (functor.rec_on F), intros (d1, d2, d3, d4), exact (sigma.mk d1 (sigma.mk d2 (pair d3 (@d4)))), intro F, apply (functor.rec_on F), intros (d1, d2, d3, d4), apply idp, intro S, apply (sigma.rec_on S), intros (d1, S2), apply (sigma.rec_on S2), intros (d2, P1), apply (prod.rec_on P1), intros (d3, d4), apply idp, end protected definition strict_cat_has_functor_hset [HD : is_hset (objects D)] : is_hset (functor C D) := begin apply trunc_equiv, apply equiv.to_is_equiv, apply sigma_char, apply trunc_sigma, apply trunc_pi, intros, exact HD, intro F, apply trunc_sigma, apply trunc_pi, intro a, apply trunc_pi, intro b, apply trunc_pi, intro c, apply !homH, intro H, apply trunc_prod, apply trunc_pi, intro a, apply succ_is_trunc, apply trunc_succ, apply !homH, apply trunc_pi, intro a, apply trunc_pi, intro b, apply trunc_pi, intro c, apply trunc_pi, intro g, apply trunc_pi, intro f, apply succ_is_trunc, apply trunc_succ, apply !homH, end -- The following lemmas will later be used to prove that the type of -- precategories formes a precategory itself protected definition compose (G : functor D E) (F : functor C D) : functor C E := functor.mk (λ x, G (F x)) (λ a b f, G (F f)) (λ a, calc G (F (ID a)) = G (ID (F a)) : {respect_id F a} ... = ID (G (F a)) : respect_id G (F a)) (λ a b c g f, calc G (F (g ∘ f)) = G (F g ∘ F f) : respect_comp F g f ... = G (F g) ∘ G (F f) : respect_comp G (F g) (F f)) infixr `∘f`:60 := compose protected theorem congr {C : Precategory} {D : Precategory} (F : C → D) (foo2 : Π ⦃a b : C⦄, hom a b → hom (F a) (F b)) (foo3a foo3b : Π (a : C), foo2 (ID a) = ID (F a)) (foo4a foo4b : Π {a b c : C} (g : @hom C C b c) (f : @hom C C a b), foo2 (g ∘ f) = foo2 g ∘ foo2 f) (p3 : foo3a = foo3b) (p4 : @foo4a = @foo4b) : functor.mk F foo2 foo3a @foo4a = functor.mk F foo2 foo3b @foo4b := begin apply (eq.rec_on p3), intros, apply (eq.rec_on p4), intros, apply idp, end protected theorem assoc {A B C D : Precategory} (H : functor C D) (G : functor B C) (F : functor A B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := begin apply (functor.rec_on H), intros (H1, H2, H3, H4), apply (functor.rec_on G), intros (G1, G2, G3, G4), apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, apply funext.path_pi, intro a, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end protected definition id {C : Precategory} : functor C C := mk (λa, a) (λ a b f, f) (λ a, idp) (λ a b c f g, idp) protected definition ID (C : Precategory) : functor C C := id protected theorem id_left (F : functor C D) : id ∘f F = F := begin apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end protected theorem id_right (F : functor C D) : F ∘f id = F := begin apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end end functor namespace precategory open functor definition precat_of_strict_precats : precategory (Σ (C : Precategory), is_hset (objects C)) := precategory.mk (λ a b, functor a.1 b.1) (λ a b, @functor.strict_cat_has_functor_hset a.1 b.1 b.2) (λ a b c g f, functor.compose g f) (λ a, functor.id) (λ a b c d h g f, !functor.assoc) (λ a b f, !functor.id_left) (λ a b f, !functor.id_right) definition Precat_of_strict_cats := Mk precat_of_strict_precats namespace ops notation `PreCat`:max := Precat_of_strict_cats persistent attribute precat_of_strict_precats [instance] end ops end precategory namespace functor -- open category.ops -- universes l m variables {C D : Precategory} -- check hom C D -- variables (F : C ⟶ D) (G : D ⇒ C) -- check G ∘ F -- check F ∘f G -- variables (a b : C) (f : a ⟶ b) -- check F a -- check F b -- check F f -- check G (F f) -- print "---" -- -- check (G ∘ F) f --error -- check (λ(x : functor C C), x) (G ∘ F) f -- check (G ∘f F) f -- print "---" -- -- check (G ∘ F) a --error -- check (G ∘f F) a -- print "---" -- -- check λ(H : hom C D) (x : C), H x --error -- check λ(H : @hom _ Cat C D) (x : C), H x -- check λ(H : C ⇒ D) (x : C), H x -- print "---" -- -- variables {obF obG : C → D} (Hob : ∀x, obF x = obG x) (homF : Π(a b : C) (f : a ⟶ b), obF a ⟶ obF b) (homG : Π(a b : C) (f : a ⟶ b), obG a ⟶ obG b) -- -- check eq.rec_on (funext Hob) homF = homG /-theorem mk_heq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) (Hmor : ∀(a b : C) (f : a ⟶ b), homF a b f == homG a b f) : mk obF homF idF compF = mk obG homG idG compG := hddcongr_arg4 mk (funext Hob) (hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor)))) !proof_irrel !proof_irrel protected theorem hequal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) (Hmor : ∀a b (f : a ⟶ b), F f == G f), F = G := functor.rec (λ obF homF idF compF, functor.rec (λ obG homG idG compG Hob Hmor, mk_heq Hob Hmor) G) F-/ -- theorem mk_eq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) -- (Hmor : ∀(a b : C) (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f) -- = homG a b f) -- : mk obF homF idF compF = mk obG homG idG compG := -- dcongr_arg4 mk -- (funext Hob) -- (funext (λ a, funext (λ b, funext (λ f, sorry ⬝ Hmor a b f)))) -- -- to fill this sorry use (a generalization of) cast_pull -- !proof_irrel -- !proof_irrel -- protected theorem equal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) -- (Hmor : ∀a b (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (F f) = G f), F = G := -- functor.rec -- (λ obF homF idF compF, -- functor.rec -- (λ obG homG idG compG Hob Hmor, mk_eq Hob Hmor) -- G) -- F end functor
1462d4403c4cfc07c019b222ee6f5d66dba28204
1ef4deeea51820641ddc8460f5b3f901a91a4db2
/sf/imp.lean
7535b2a56cacdca4f6c43b593fc57d977b18338c
[ "Apache-2.0" ]
permissive
pnwamk/misc-lean
6fdafce6297987ba506b20c692fedd77fcf3edd1
5b8807cfee8f22ab6f3b2c5d8ea678c02e67825b
refs/heads/master
1,618,236,715,815
1,585,341,762,000
1,585,342,291,000
249,083,647
0
0
null
null
null
null
UTF-8
Lean
false
false
11,704
lean
-- Some simple programming language modeling, using lean4 -- commit 4296e1d83e734b18b4787329e4195569c0518325 -- from Fri Mar 20 18:32:04 2020 -0700 import Init.Data.String -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Data definitions -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- def Var := String -- Arithmetic unary operations inductive Ty : Type | int : Ty | bool : Ty --|sum : Ty → Ty → Ty -- Arithmetic binary operations inductive Const : Type | int : Int → Const | bool : Bool → Const --|left : Const → Ty → Const --|right : Ty → Const → Const instance intToConst : HasCoe Int Const := ⟨Const.int⟩ instance boolToConst : HasCoe Bool Const := ⟨Const.bool⟩ inductive UOp : Type | inc | dec | neg | zero? | not inductive BOp : Type | add | sub | mul -- Arithmetic expressions inductive Exp : Type | var : Var → Exp | const : Const → Exp | uop : UOp → Exp → Exp | bop : BOp → Exp → Exp → Exp | cond : Exp → Exp → Exp → Exp | letvar : Var → Exp → Exp → Exp --|left : Exp → Ty → Exp --|right : Ty → Exp → Exp --|elim : Exp → Ty → Ty → Var namespace Exp open UOp BOp Const private def ci := λ n => const $ int n private def cb := λ b => const $ bool b def ex1 : Exp := (ci 42) def ex2 : Exp := (cb true) def ex3 : Exp := (uop inc (ci 41)) def ex4 : Exp := (uop dec (const (int 43))) def ex5 : Exp := (uop neg (bop sub (ci 0) (ci 42))) def ex6 : Exp := (uop zero? (ci 0)) def ex7 : Exp := (bop add (ci 41) (ci 1)) def ex8 : Exp := (bop sub (ci 43) (ci 1)) def ex9 : Exp := (bop mul (ci 21) (ci 2)) def ex10 : Exp := (uop not (uop zero? (ci 1))) def ex11 : Exp := (cond (uop not (uop zero? (ci 42))) (ci 42) (ci 0)) def ex12 : Exp := (cond (uop not (uop zero? (ci 0))) (ci 0) (ci 42)) def ex13 : Exp := (letvar "x" (cb true) (cond (var "x") (ci 42) (ci 0))) def ex14 : Exp := (letvar "x" (uop inc (ci 41)) (cond (cb true) (var "x") (ci 0))) def ex15 : Exp := (letvar "x" (uop inc (ci 39)) (letvar "x" (uop inc (var "x")) (uop inc (var "x")))) end Exp def Env : Type := Var → Option Const namespace Env def empty : Env := λ _ => none def extend (ρ : Env) (x : Var) (c:Const) : Env := λ y => if x == y then some c else (ρ y) end Env -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Interpreter -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- namespace UOp def interp : UOp → Const → Option Const | inc, (Const.int n) => some $ Const.int $ n + 1 | dec, (Const.int n) => some $ Const.int $ n - 1 | neg, (Const.int n) => some $ Const.int $ 0 - n | zero?, (Const.int n) => some $ Const.bool $ n == 0 | not, (Const.bool b) => some $ Const.bool $ ¬ b | _,_ => none end UOp namespace BOp def interp : BOp → Const → Const → Option Const | add, (Const.int x), (Const.int y) => some $ Const.int $ x + y | sub, (Const.int x), (Const.int y) => some $ Const.int $ x - y | mul, (Const.int x), (Const.int y) => some $ Const.int $ x * y | _,_,_ => none end BOp namespace Exp def interp : Env → Exp → Option Const | ρ, var x => ρ x | ρ, const c => c | ρ, uop op e => do v ← interp ρ e; UOp.interp op v | ρ, bop op e₁ e₂ => do v₁ ← interp ρ e₁; v₂ ← interp ρ e₂; BOp.interp op v₁ v₂ | ρ, cond e₁ e₂ e₃ => match interp ρ e₁ with | some (Const.bool true) => interp ρ e₂ | some (Const.bool false) => interp ρ e₃ | _ => none | ρ, letvar x e₁ e₂ => do v₁ ← interp ρ e₁; let ρ' := Env.extend ρ x v₁; interp ρ' e₂ end Exp def TyEnv : Type := Var → Option Ty namespace TyEnv def empty : TyEnv := λ _ => none def extend (Γ : TyEnv) (x : Var) (t:Ty) : TyEnv := λ y => if x == y then some t else (Γ y) end TyEnv namespace Const def typeof : Const → Ty | int _ => Ty.int | bool _ => Ty.bool end Const namespace UOp def typeof : UOp → (Ty × Ty) | inc => (Ty.int, Ty.int) | dec => (Ty.int, Ty.int) | neg => (Ty.int, Ty.int) | zero? => (Ty.int, Ty.bool) | not => (Ty.bool, Ty.bool) end UOp namespace BOp def typeof : BOp → (Ty × Ty × Ty) | add => (Ty.int, Ty.int, Ty.int) | sub => (Ty.int, Ty.int, Ty.int) | mul => (Ty.int, Ty.int, Ty.int) end BOp inductive TypeOf : TyEnv → Exp → Ty → Prop | var (Γ:TyEnv) x t : (Γ x) = (some t) → TypeOf Γ (Exp.var x) t | const Γ c t : Const.typeof c = t → TypeOf Γ (Exp.const c) t | uop Γ op e t t' : TypeOf Γ e t → UOp.typeof op = (t, t') → TypeOf Γ (Exp.uop op e) t' | bop Γ op e₁ e₂ t₁ t₂ t₃ : TypeOf Γ e₁ t₁ → TypeOf Γ e₂ t₂ → BOp.typeof op = (t₁, t₂, t₃) → TypeOf Γ (Exp.bop op e₁ e₂) t₃ | cond Γ e₁ e₂ e₃ t : TypeOf Γ e₁ Ty.bool → TypeOf Γ e₂ t → TypeOf Γ e₃ t → TypeOf Γ (Exp.cond e₁ e₂ e₃) t | letvar Γ x e₁ e₂ t₁ t₂ : TypeOf Γ e₁ t₁ → TypeOf (TyEnv.extend Γ x t₁) e₂ t₂ → TypeOf Γ (Exp.letvar x e₁ e₂) t₂ -- In the given expression, substitute -- the constant for the variable. def subst : Exp → Const → Var → Exp | Exp.var y, c, x => if x == y then (Exp.const c) else Exp.var y | Exp.const c, _, _ => Exp.const c | Exp.uop op e, c, x => Exp.uop op (subst e c x) | Exp.bop op e₁ e₂, c, x => Exp.bop op (subst e₁ c x) (subst e₂ c x) | Exp.cond e₁ e₂ e₃, c, x => Exp.cond (subst e₁ c x) (subst e₂ c x) (subst e₃ c x) | Exp.letvar y e₁ e₂, c, x => let e₁' := (subst e₁ c x); if x == y then Exp.letvar y e₁' e₂ else Exp.letvar y e₁' (subst e₂ c x) -- A single reduction step. inductive Step : Exp → Exp → Prop | uop_red op c₁ c₂ : UOp.interp op c₁ = some c₂ → Step (Exp.uop op (Exp.const c₁)) (Exp.const c₂) | bop_red op c₁ c₂ c₃ : BOp.interp op c₁ c₂ = some c₃ → Step (Exp.bop op (Exp.const c₁) (Exp.const c₂)) (Exp.const c₃) | cond_congr e₁ e₁' e₂ e₃ : Step e₁ e₁' → Step (Exp.cond e₁ e₂ e₃) (Exp.cond e₁' e₂ e₃) | cond_red e₁ e₂ : Step (Exp.cond (Exp.const true) e₁ e₂) e₁ | letvar_congr x e₁ e₁' e₂ : Step e₁ e₁' → Step (Exp.letvar x e₁ e₂) (Exp.letvar x e₁' e₂) | letvar_red x c e : Step (Exp.letvar x (Exp.const c) e) (subst e c x) -- | Zero or more steps of reduction. inductive Steps : Exp → Exp → Prop | nil e : Steps e e | cons e₁ e₂ e₃ : Step e₁ e₂ → Steps e₂ e₃ → Steps e₁ e₃ def env_sat (Γ:TyEnv) (ρ:Env) : Prop := forall x t, (Γ x) = some t → Exists (λ c => (ρ x) = some c ∧ Const.typeof c = t) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Theorems (N.B., seems like tactics have to -- come after `new_frontend`... need to look -- more into what it entails.) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- new_frontend macro try t:tactic : tactic => `($t <|> skip) syntax "repeat" tactic : tactic macro_rules | `(tactic| repeat $t) => `(tactic| try ($t; repeat $t)) -- TODO there's got to be a way to just apply all -- the known constructors for a type, right? -- oooh, check out src/Init/Lean/Meta/Tactic macro constr_TypeOf : tactic => `((apply TypeOf.var) <|> (apply TypeOf.const) <|> (apply TypeOf.uop) <|> (apply TypeOf.bop) <|> (apply TypeOf.cond) <|> (apply TypeOf.letvar)) macro typecheck : tactic => `(repeat (constr_TypeOf <|> (exact rfl))) open Exp -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Example evaluation tests -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- def test_eval : Exp → Option Const := interp Env.empty private theorem test_ex1 : test_eval ex1 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex2 : test_eval ex2 = some (Const.bool true) := Eq.refl (some (Const.bool true)) private theorem test_ex3 : test_eval ex3 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex4 : test_eval ex4 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex5 : test_eval ex5 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex6 : test_eval ex6 = some (Const.bool true) := Eq.refl (some (Const.bool true)) private theorem test_ex7 : test_eval ex7 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex8 : test_eval ex8 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex8 : test_eval ex8 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex9 : test_eval ex9 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex10 : test_eval ex10 = some (Const.bool true) := Eq.refl (some (Const.bool true)) private theorem test_ex11 : test_eval ex11 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex12 : test_eval ex12 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex13 : test_eval ex13 = some (Const.int 42) := Eq.refl (some (Const.int 42)) private theorem test_ex14 : test_eval ex14 = some (Const.int 42) := Eq.refl (some (Const.int 42)) theorem test_ex15 : test_eval ex15 = some (Const.int 42) := begin exact rfl end -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Example type checking tests -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- namespace Exp open UOp BOp Const theorem test_ex1 : TypeOf TyEnv.empty ex1 Ty.int := begin typecheck end theorem test_ex2 : TypeOf TyEnv.empty ex2 Ty.bool := begin typecheck end theorem test_ex3 : TypeOf TyEnv.empty ex3 Ty.int := begin typecheck end theorem test_ex4 : TypeOf TyEnv.empty ex4 Ty.int := begin typecheck end theorem test_ex5 : TypeOf TyEnv.empty ex5 Ty.int := begin typecheck end theorem test_ex6 : TypeOf TyEnv.empty ex6 Ty.bool := begin typecheck end theorem test_ex7 : TypeOf TyEnv.empty ex7 Ty.int := begin typecheck end theorem test_ex8 : TypeOf TyEnv.empty ex8 Ty.int := begin typecheck end theorem test_ex9 : TypeOf TyEnv.empty ex9 Ty.int := begin typecheck end theorem test_ex10 : TypeOf TyEnv.empty ex10 Ty.bool := begin typecheck end theorem test_ex11 : TypeOf TyEnv.empty ex11 Ty.int := begin typecheck end theorem test_ex12 : TypeOf TyEnv.empty ex12 Ty.int := begin typecheck end theorem test_ex13 : TypeOf TyEnv.empty ex13 Ty.int := begin typecheck end theorem test_ex14 : TypeOf TyEnv.empty ex14 Ty.int := begin typecheck end theorem test_ex15 : TypeOf TyEnv.empty ex15 Ty.int := begin typecheck end end Exp -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Type safety theorems -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- namespace UOp open Const def interp_safe : forall op t₁ t₂ c, typeof op = (t₁, t₂) → Const.typeof c = t₁ → Exists (λ c' => interp op c = some c' ∧ Const.typeof c' = t₂) := begin intros op t₁ t₂ c Hop Hc; cases op; cases c; apply (Exists.intro (Const.int $ a + 1)); apply And.intro; exact rfl; end end UOp -- UOp.interp is type safe -- BOp.interp is type safe -- BOp.interp is type safe
3d909f497591b186c4fd49c406b61c361d42cdb5
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/submonoid/center.lean
991460494c72574227f89384ca21c635d1969e0c
[ "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
1,916
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.submonoid.operations import group_theory.subsemigroup.center import data.fintype.basic /-! # Centers of monoids ## Main definitions * `submonoid.center`: the center of a monoid * `add_submonoid.center`: the center of an additive monoid We provide `subgroup.center`, `add_subgroup.center`, `subsemiring.center`, and `subring.center` in other files. -/ namespace submonoid section variables (M : Type*) [monoid M] /-- The center of a monoid `M` is the set of elements that commute with everything in `M` -/ @[to_additive "The center of a monoid `M` is the set of elements that commute with everything in `M`"] def center : submonoid M := { carrier := set.center M, one_mem' := set.one_mem_center M, mul_mem' := λ a b, set.mul_mem_center } @[to_additive] lemma coe_center : ↑(center M) = set.center M := rfl @[simp] lemma center_to_subsemigroup : (center M).to_subsemigroup = subsemigroup.center M := rfl lemma _root_.add_submonoid.center_to_add_subsemigroup (M) [add_monoid M] : (add_submonoid.center M).to_add_subsemigroup = add_subsemigroup.center M := rfl attribute [to_additive add_submonoid.center_to_add_subsemigroup] submonoid.center_to_subsemigroup variables {M} @[to_additive] lemma mem_center_iff {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [decidable_eq M] [fintype M] : decidable_pred (∈ center M) := λ _, decidable_of_iff' _ mem_center_iff /-- The center of a monoid is commutative. -/ instance : comm_monoid (center M) := { mul_comm := λ a b, subtype.ext $ b.prop _, .. (center M).to_monoid } end section variables (M : Type*) [comm_monoid M] @[simp] lemma center_eq_top : center M = ⊤ := set_like.coe_injective (set.center_eq_univ M) end end submonoid
ea4d25cd93f00cd96908a70adf0fd2a8371f61bc
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/limits/over.lean
a4af1dc5d2fa9e4768c06264ca59e79b468fd219
[ "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
10,443
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.comma import category_theory.limits.preserves import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variable {X : C} namespace category_theory.functor @[simps] def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget) := { X := X, ι := { app := λ j, (F.obj j).hom } } @[simps] def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget) := { X := X, π := { app := λ j, (F.obj j).hom } } end category_theory.functor namespace category_theory.over @[simps] def colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : cocone F := { X := mk $ colimit.desc (F ⋙ forget) F.to_cocone, ι := { app := λ j, hom_mk $ colimit.ι (F ⋙ forget) j, naturality' := begin intros j j' f, have := colimit.w (F ⋙ forget) f, tidy end } } def forget_colimit_is_colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : is_colimit (forget.map_cocone (colimit F)) := is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ forget)) (cocones.ext (iso.refl _) (by tidy)) instance : reflects_colimits (forget : over X ⥤ C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ F, by constructor; exactI λ t ht, { desc := λ s, hom_mk (ht.desc (forget.map_cocone s)) begin apply ht.hom_ext, intro j, rw [←category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.ι.app j), -- TODO: How to write (s.ι.app j).w? exact (w (t.ι.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cocone s) j -- TODO: Ask Simon about multiple ext lemmas for defeq types (comma_morphism & over.category.hom) end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j)) end } } } instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget)] : has_colimit F := { cocone := colimit F, is_colimit := reflects_colimit.reflects (forget_colimit_is_colimit F) } instance has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := { has_colimit := λ F, by apply_instance } instance has_colimits [has_colimits.{v} C] : has_colimits.{v} (over X) := { has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_colimits [has_colimits.{v} C] {X : C} : preserves_colimits (forget : over X ⥤ C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (forget_colimit_is_colimit F) } } /-- Given the appropriate pullback in C, construct a product in the over category -/ def over_product_of_pullbacks (B : C) (F : discrete walking_pair ⥤ over B) [q : has_limit (cospan (F.obj walking_pair.left).hom (F.obj walking_pair.right).hom)] : has_limit F := { cone := begin refine ⟨_, _⟩, exact @over.mk _ _ B (pullback (F.obj walking_pair.left).hom (F.obj walking_pair.right).hom) (pullback.fst ≫ (F.obj walking_pair.left).hom), apply nat_trans.of_homs, intro i, cases i, apply over.hom_mk _ _, apply pullback.fst, dsimp, refl, apply over.hom_mk _ _, apply pullback.snd, exact pullback.condition.symm end, is_limit := { lift := λ s, begin apply over.hom_mk _ _, apply pullback.lift _ _ _, exact (s.π.app walking_pair.left).left, exact (s.π.app walking_pair.right).left, erw over.w (s.π.app walking_pair.left), erw over.w (s.π.app walking_pair.right), refl, dsimp, erw ← category.assoc, simp, end, fac' := λ s j, begin ext, cases j; simp [nat_trans.of_homs] end, uniq' := λ s m j, begin ext, { erw ← j walking_pair.left, simp }, { erw ← j walking_pair.right, simp } end } } /-- Construct terminal object in the over category. -/ instance (B : C) : has_terminal.{v} (over B) := { has_limits_of_shape := { has_limit := λ F, { cone := { X := over.mk (𝟙 _), π := { app := λ p, pempty.elim p } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } } -- TODO: this should work for any connected limit, not just pullbacks /-- Given pullbacks in C, we have pullbacks in C/B -/ instance {B : C} [has_pullbacks.{v} C] : has_pullbacks.{v} (over B) := { has_limits_of_shape := { has_limit := λ F, let X : over B := F.obj walking_cospan.one in let Y : over B := F.obj walking_cospan.left in let Z : over B := F.obj walking_cospan.right in let f : Y ⟶ X := (F.map walking_cospan.hom.inl) in let g : Z ⟶ X := (F.map walking_cospan.hom.inr) in let L : over B := over.mk (pullback.fst ≫ Y.hom : pullback f.left g.left ⟶ B) in let π₁ : L ⟶ Y := over.hom_mk pullback.fst in let π₂ : L ⟶ Z := @over.hom_mk _ _ _ L Z (pullback.snd : L.left ⟶ Z.left) (by {dsimp, rw [← over.w f, ← category.assoc, pullback.condition, category.assoc, over.w g]}) in { cone := cone.of_pullback_cone (pullback_cone.mk π₁ π₂ (by { ext, rw [over.comp_left, over.hom_mk_left, pullback.condition], refl, })), is_limit := { lift := λ s, begin apply over.hom_mk _ _, { apply pullback.lift (s.π.app walking_cospan.left).left (s.π.app walking_cospan.right).left, rw [← over.comp_left, ← over.comp_left, s.w, s.w], }, { show pullback.lift _ _ _ ≫ (pullback.fst ≫ Y.hom) = (s.X).hom, rw [limit.lift_π_assoc, pullback_cone.mk_π_app_left, over.w], refl, } end, fac' := λ s j, begin ext1, dsimp, cases j; simp only [limit.lift_π, limit.lift_π_assoc, over.hom_mk_left, over.id_left, over.comp_left, pullback_cone.mk_π_app_one, pullback_cone.mk_π_app_left, pullback_cone.mk_π_app_right, eq_to_hom_refl, category.comp_id], rw [← over.comp_left, ← s.w walking_cospan.hom.inl], end, uniq' := λ s m J, over.over_morphism.ext begin simp only [over.hom_mk_left], apply pullback.hom_ext, { rw [limit.lift_π, pullback_cone.mk_π_app_left, ←(J walking_cospan.left)], dsimp, rw [category.comp_id], }, { rw [limit.lift_π, pullback_cone.mk_π_app_right, ←(J walking_cospan.right)], dsimp, rw [category.comp_id], } end } }, } } /-- Given pullbacks in C, we have binary products in any over category -/ instance over_has_prods_of_pullback [has_pullbacks.{v} C] (B : C) : has_binary_products.{v} (over B) := {has_limits_of_shape := {has_limit := λ F, over_product_of_pullbacks B F}} /-! A collection of lemmas to decompose products in the over category -/ @[simp] lemma over_prod_pair_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (f ⨯ g).left = pullback f.hom g.hom := rfl @[simp] lemma over_prod_pair_hom [has_pullbacks.{v} C] {B : C} (f g : over B) : (f ⨯ g).hom = pullback.fst ≫ f.hom := rfl @[simp] lemma over_prod_fst_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (limits.prod.fst : f ⨯ g ⟶ f).left = pullback.fst := rfl @[simp] lemma over_prod_snd_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (limits.prod.snd : f ⨯ g ⟶ g).left = pullback.snd := rfl lemma over_prod_map_left [has_pullbacks.{v} C] {B : C} (f g h k : over B) (α : f ⟶ g) (β : h ⟶ k) : (limits.prod.map α β).left = pullback.lift (pullback.fst ≫ α.left) (pullback.snd ≫ β.left) (by { simp only [category.assoc], convert pullback.condition; apply over.w }) := rfl end category_theory.over namespace category_theory.under @[simps] def limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : cone F := { X := mk $ limit.lift (F ⋙ forget) F.to_cone, π := { app := λ j, hom_mk $ limit.π (F ⋙ forget) j, naturality' := begin intros j j' f, have := (limit.w (F ⋙ forget) f).symm, tidy end } } def forget_limit_is_limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : is_limit (forget.map_cone (limit F)) := is_limit.of_iso_limit (limit.is_limit (F ⋙ forget)) (cones.ext (iso.refl _) (by tidy)) instance : reflects_limits (forget : under X ⥤ C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ F, by constructor; exactI λ t ht, { lift := λ s, hom_mk (ht.lift (forget.map_cone s)) begin apply ht.hom_ext, intro j, rw [category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.π.app j), exact (w (t.π.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cone s) j end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j)) end } } } instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget)] : has_limit F := { cone := limit F, is_limit := reflects_limit.reflects (forget_limit_is_limit F) } instance has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (under X) := { has_limit := λ F, by apply_instance } instance has_limits [has_limits.{v} C] : has_limits.{v} (under X) := { has_limits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_limits [has_limits.{v} C] {X : C} : preserves_limits (forget : under X ⥤ C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (forget_limit_is_limit F) } } end category_theory.under
0e09745974d0f8891ba4cb4bab429067329fcd3b
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/nat/bitwise.lean
99be49bc987517cf9d25454d11bf513b3b41db8c
[ "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
10,072
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ prelude import init.data.nat.lemmas init.meta.well_founded_tactics universe u namespace nat def bodd_div2 : ℕ → bool × ℕ | 0 := (ff, 0) | (succ n) := match bodd_div2 n with | (ff, m) := (tt, m) | (tt, m) := (ff, succ m) end def div2 (n : ℕ) : ℕ := (bodd_div2 n).2 def bodd (n : ℕ) : bool := (bodd_div2 n).1 @[simp] lemma bodd_zero : bodd 0 = ff := rfl lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_succ (n : ℕ) : bodd (succ n) = bnot (bodd n) := by unfold bodd bodd_div2; cases bodd_div2 n; cases fst; refl @[simp] lemma bodd_add (m n : ℕ) : bodd (m + n) = bxor (bodd m) (bodd n) := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [IH], cases bodd m; cases bodd n; refl } end @[simp] lemma bodd_mul (m n : ℕ) : bodd (m * n) = bodd m && bodd n := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [mul_succ, IH], cases bodd m; cases bodd n; refl } end lemma mod_two_of_bodd (n : ℕ) : n % 2 = cond (bodd n) 1 0 := begin have := congr_arg bodd (mod_add_div n 2), simp [bnot] at this, rw [show ∀ b, ff && b = ff, by intros; cases b; refl, show ∀ b, bxor b ff = b, by intros; cases b; refl] at this, rw [← this], cases mod_two_eq_zero_or_one n with h h; rw h; refl end @[simp] lemma div2_zero : div2 0 = 0 := rfl lemma div2_one : div2 1 = 0 := rfl lemma div2_two : div2 2 = 1 := rfl @[simp] lemma div2_succ (n : ℕ) : div2 (succ n) = cond (bodd n) (succ (div2 n)) (div2 n) := by unfold bodd div2 bodd_div2; cases bodd_div2 n; cases fst; refl local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | 0 := rfl | (succ n) := begin simp, refine eq.trans _ (congr_arg succ (bodd_add_div2 n)), cases bodd n; simp [cond, bnot], { rw [nat.add_comm, nat.zero_add], }, { rw [succ_mul, nat.add_comm 1, nat.zero_add] } end theorem div2_val (n) : div2 n = n / 2 := begin refine eq_of_mul_eq_mul_left dec_trivial (nat.add_left_cancel (eq.trans _ (nat.mod_add_div n 2).symm)), rw [mod_two_of_bodd, bodd_add_div2] end def bit (b : bool) : ℕ → ℕ := cond b bit1 bit0 lemma bit0_val (n : nat) : bit0 n = 2 * n := calc n + n = 0 + n + n : by rw nat.zero_add ... = n * 2 : rfl ... = 2 * n : nat.mul_comm _ _ lemma bit1_val (n : nat) : bit1 n = 2 * n + 1 := congr_arg succ (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply bit0_val, apply bit1_val } lemma bit_decomp (n : nat) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (nat.add_comm _ _).trans $ bodd_add_div2 _ def bit_cases_on {C : nat → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h lemma bit_zero : bit ff 0 = 0 := rfl def shiftl' (b : bool) (m : ℕ) : ℕ → ℕ | 0 := m | (n+1) := bit b (shiftl' n) def shiftl : ℕ → ℕ → ℕ := shiftl' ff @[simp] theorem shiftl_zero (m) : shiftl m 0 = m := rfl @[simp] theorem shiftl_succ (m n) : shiftl m (n + 1) = bit0 (shiftl m n) := rfl def shiftr : ℕ → ℕ → ℕ | m 0 := m | m (n+1) := div2 (shiftr m n) def test_bit (m n : ℕ) : bool := bodd (shiftr m n) def binary_rec {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : Π n, C n | n := if n0 : n = 0 then by rw n0; exact z else let n' := div2 n in have n' < n, begin change div2 n < n, rw div2_val, apply (div_lt_iff_lt_mul _ _ (succ_pos 1)).2, have := nat.mul_lt_mul_of_pos_left (lt_succ_self 1) (lt_of_le_of_ne (zero_le _) (ne.symm n0)), rwa nat.mul_one at this end, by rw [← show bit (bodd n) n' = n, from bit_decomp n]; exact f (bodd n) n' (binary_rec n') def size : ℕ → ℕ := binary_rec 0 (λ_ _, succ) def bits : ℕ → list bool := binary_rec [] (λb _ IH, b :: IH) def bitwise (f : bool → bool → bool) : ℕ → ℕ → ℕ := binary_rec (λn, cond (f ff tt) n 0) (λa m Ia, binary_rec (cond (f tt ff) (bit a m) 0) (λb n _, bit (f a b) (Ia n))) def lor : ℕ → ℕ → ℕ := bitwise bor def land : ℕ → ℕ → ℕ := bitwise band def ldiff : ℕ → ℕ → ℕ := bitwise (λ a b, a && bnot b) def lxor : ℕ → ℕ → ℕ := bitwise bxor @[simp] lemma binary_rec_zero {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : binary_rec z f 0 = z := by {rw [binary_rec], refl} /- bitwise ops -/ lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl lemma div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, nat.add_comm, add_mul_div_left, div_eq_of_lt, nat.zero_add]; cases b; exact dec_trivial lemma shiftl'_add (b m n) : ∀ k, shiftl' b m (n + k) = shiftl' b (shiftl' b m n) k | 0 := rfl | (k+1) := congr_arg (bit b) (shiftl'_add k) lemma shiftl_add : ∀ m n k, shiftl m (n + k) = shiftl (shiftl m n) k := shiftl'_add _ lemma shiftr_add (m n) : ∀ k, shiftr m (n + k) = shiftr (shiftr m n) k | 0 := rfl | (k+1) := congr_arg div2 (shiftr_add k) lemma shiftl'_sub (b m) : ∀ {n k}, k ≤ n → shiftl' b m (n - k) = shiftr (shiftl' b m n) k | n 0 h := rfl | (n+1) (k+1) h := begin simp [shiftl'], rw [nat.add_comm, shiftr_add], simp [shiftr, div2_bit], apply shiftl'_sub (nat.le_of_succ_le_succ h) end lemma shiftl_sub : ∀ m {n k}, k ≤ n → shiftl m (n - k) = shiftr (shiftl m n) k := shiftl'_sub _ @[simp] lemma test_bit_zero (b n) : test_bit (bit b n) 0 = b := bodd_bit _ _ lemma test_bit_succ (m b n) : test_bit (bit b n) (succ m) = test_bit n m := have bodd (shiftr (shiftr (bit b n) 1) m) = bodd (shiftr n m), by dsimp [shiftr]; rw div2_bit, by rw [← shiftr_add, nat.add_comm] at this; exact this lemma binary_rec_eq {C : nat → Sort u} {z : C 0} {f : ∀ b n, C n → C (bit b n)} (h : f ff 0 z = z) (b n) : binary_rec z f (bit b n) = f b n (binary_rec z f n) := begin rw [binary_rec], with_cases { by_cases bit b n = 0 }, case pos : h' { simp [dif_pos h'], generalize : binary_rec._main._pack._proof_1 (bit b n) h' = e, revert e, have bf := bodd_bit b n, have n0 := div2_bit b n, rw h' at bf n0, simp at bf n0, rw [← bf, ← n0, binary_rec_zero], intros, exact h.symm }, case neg : h' { simp [dif_neg h'], generalize : binary_rec._main._pack._proof_2 (bit b n) = e, revert e, rw [bodd_bit, div2_bit], intros, refl} end lemma bitwise_bit_aux {f : bool → bool → bool} (h : f ff ff = ff) : @binary_rec (λ_, ℕ) (cond (f tt ff) (bit ff 0) 0) (λ b n _, bit (f ff b) (cond (f ff tt) n 0)) = λ (n : ℕ), cond (f ff tt) n 0 := begin funext n, apply bit_cases_on n, intros b n, rw [binary_rec_eq], { cases b; try {rw h}; induction fft : f ff tt; simp [cond]; refl }, { rw [h, show cond (f ff tt) 0 0 = 0, by cases f ff tt; refl, show cond (f tt ff) (bit ff 0) 0 = 0, by cases f tt ff; refl]; refl } end @[simp] lemma bitwise_zero_left (f : bool → bool → bool) (n) : bitwise f 0 n = cond (f ff tt) n 0 := by unfold bitwise; rw [binary_rec_zero] @[simp] lemma bitwise_zero_right (f : bool → bool → bool) (h : f ff ff = ff) (m) : bitwise f m 0 = cond (f tt ff) m 0 := by unfold bitwise; apply bit_cases_on m; intros; rw [binary_rec_eq, binary_rec_zero]; exact bitwise_bit_aux h @[simp] lemma bitwise_zero (f : bool → bool → bool) : bitwise f 0 0 = 0 := by rw bitwise_zero_left; cases f ff tt; refl @[simp] lemma bitwise_bit {f : bool → bool → bool} (h : f ff ff = ff) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin unfold bitwise, rw [binary_rec_eq, binary_rec_eq], { induction ftf : f tt ff; dsimp [cond], rw [show f a ff = ff, by cases a; assumption], apply @congr_arg _ _ _ 0 (bit ff), tactic.swap, rw [show f a ff = a, by cases a; assumption], apply congr_arg (bit a), all_goals { apply bit_cases_on m, intros a m, rw [binary_rec_eq, binary_rec_zero], rw [← bitwise_bit_aux h, ftf], refl } }, { exact bitwise_bit_aux h } end theorem bitwise_swap {f : bool → bool → bool} (h : f ff ff = ff) : bitwise (function.swap f) = function.swap (bitwise f) := begin funext m n, revert n, dsimp [function.swap], apply binary_rec _ (λ a m' IH, _) m; intro n, { rw [bitwise_zero_left, bitwise_zero_right], exact h }, apply bit_cases_on n; intros b n', rw [bitwise_bit, bitwise_bit, IH]; exact h end @[simp] lemma lor_bit : ∀ (a m b n), lor (bit a m) (bit b n) = bit (a || b) (lor m n) := bitwise_bit rfl @[simp] lemma land_bit : ∀ (a m b n), land (bit a m) (bit b n) = bit (a && b) (land m n) := bitwise_bit rfl @[simp] lemma ldiff_bit : ∀ (a m b n), ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := bitwise_bit rfl @[simp] lemma lxor_bit : ∀ (a m b n), lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := bitwise_bit rfl @[simp] lemma test_bit_bitwise {f : bool → bool → bool} (h : f ff ff = ff) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin revert m n; induction k with k IH; intros m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit h, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor : ∀ (m n k), test_bit (lor m n) k = test_bit m k || test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_land : ∀ (m n k), test_bit (land m n) k = test_bit m k && test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_ldiff : ∀ (m n k), test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := test_bit_bitwise rfl @[simp] lemma test_bit_lxor : ∀ (m n k), test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := test_bit_bitwise rfl end nat
e3a86fd6e4607c33fa1fd4b21aed2286cd4d8625
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/objects/string.lean
1f4fb17c54eed3df4bf158e7807535dccbe56f50
[]
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
48
lean
/- Strings -/ #eval "Hello, " #eval "Logic!"
df2d8a12fa985fd1d1167ffb45e38f3c36be5975
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/polynomial/chebyshev/basic.lean
0e6bb13842cf95fe39f76145c52fef2e4ea845f9
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,580
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.polynomial.chebyshev.defs import analysis.special_functions.trigonometric import ring_theory.localization import data.zmod.basic import algebra.invertible /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `ℕ`, with integral coefficients. In this file, we only consider Chebyshev polynomials of the first kind. ## Main declarations * `polynomial.chebyshev₁_mul`, the `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th Chebyshev polynomials. * `polynomial.lambdashev_mul`, the `(m * n)`-th lambdashev polynomial is the composition of the `m`-th and `n`-th lambdashev polynomials. * `polynomial.lambdashev_char_p`, for a prime number `p`, the `p`-th lambdashev polynomial is congruent to `X ^ p` modulo `p`. ## Implementation details Since Chebyshev polynomials have interesting behaviour over the complex numbers and modulo `p`, we define them to have coefficients in an arbitrary commutative ring, even though technically `ℤ` would suffice. The benefit of allowing arbitrary coefficient rings, is that the statements afterwards are clean, and do not have `map (int.cast_ring_hom R)` interfering all the time. -/ noncomputable theory namespace polynomial open complex variables (R S : Type*) [comm_ring R] [comm_ring S] /-- The `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th -/ lemma chebyshev₁_mul (m n : ℕ) : chebyshev₁ R (m * n) = (chebyshev₁ R m).comp (chebyshev₁ R n) := begin simp only [← map_comp, ← map_chebyshev₁ (int.cast_ring_hom R)], congr' 1, apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, simp only [map_comp, map_chebyshev₁], apply polynomial.funext, intro z, obtain ⟨θ, rfl⟩ := cos_surjective z, simp only [chebyshev₁_complex_cos, nat.cast_mul, eval_comp, mul_assoc], end section lambdashev /-! ### A Lambda structure on `polynomial ℤ` Mathlib doesn't currently know what a Lambda ring is. But once it does, we can endow `polynomial ℤ` with a Lambda structure in terms of the `lambdashev` polynomials defined below. There is exactly one other Lambda structure on `polynomial ℤ` in terms of binomial polynomials. -/ variables {R} lemma lambdashev_eval_add_inv (x y : R) (h : x * y = 1) : ∀ n, (lambdashev R n).eval (x + y) = x ^ n + y ^ n | 0 := by simp only [bit0, eval_one, eval_add, pow_zero, lambdashev_zero] | 1 := by simp only [eval_X, lambdashev_one, pow_one] | (n + 2) := begin simp only [eval_sub, eval_mul, lambdashev_eval_add_inv, eval_X, lambdashev_add_two], conv_lhs { simp only [pow_succ, add_mul, mul_add, h, ← mul_assoc, mul_comm y x, one_mul] }, ring_exp end variables (R) lemma lambdashev_eq_chebyshev₁ [invertible (2 : R)] : ∀ n, lambdashev R n = 2 * (chebyshev₁ R n).comp (C (⅟2) * X) | 0 := by simp only [chebyshev₁_zero, mul_one, one_comp, lambdashev_zero] | 1 := by rw [lambdashev_one, chebyshev₁_one, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, mul_inv_of_self, C_1, one_mul] | (n + 2) := begin simp only [lambdashev_add_two, chebyshev₁_add_two, lambdashev_eq_chebyshev₁ (n + 1), lambdashev_eq_chebyshev₁ n, sub_comp, mul_comp, add_comp, X_comp, bit0_comp, one_comp], simp only [← C_1, ← C_bit0, ← mul_assoc, ← C_mul, mul_inv_of_self], rw [C_1, one_mul], ring end lemma chebyshev₁_eq_lambdashev [invertible (2 : R)] (n : ℕ) : chebyshev₁ R n = C (⅟2) * (lambdashev R n).comp (2 * X) := begin rw lambdashev_eq_chebyshev₁, simp only [comp_assoc, mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul], rw [inv_of_mul_self, C_1, one_mul, one_mul, comp_X] end /-- the `(m * n)`-th lambdashev polynomial is the composition of the `m`-th and `n`-th -/ lemma lambdashev_mul (m n : ℕ) : lambdashev R (m * n) = (lambdashev R m).comp (lambdashev R n) := begin simp only [← map_lambdashev (int.cast_ring_hom R), ← map_comp], congr' 1, apply map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_lambdashev, map_comp, lambdashev_eq_chebyshev₁, chebyshev₁_mul, two_mul, ← add_comp], simp only [← two_mul, ← comp_assoc], apply eval₂_congr rfl rfl, rw [comp_assoc], apply eval₂_congr rfl _ rfl, rw [mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, inv_of_mul_self, C_1, one_mul] end lemma lambdashev_comp_comm (m n : ℕ) : (lambdashev R m).comp (lambdashev R n) = (lambdashev R n).comp (lambdashev R m) := by rw [← lambdashev_mul, mul_comm, lambdashev_mul] lemma lambdashev_zmod_p (p : ℕ) [fact p.prime] : lambdashev (zmod p) p = X ^ p := begin -- Recall that `lambdashev_eval_add_inv` characterises `lambdashev R p` -- as a polynomial that maps `x + x⁻¹` to `x ^ p + (x⁻¹) ^ p`. -- Since `X ^ p` also satisfies this property in characteristic `p`, -- we can use a variant on `polynomial.funext` to conclude that these polynomials are equal. -- For this argument, we need an arbitrary infinite field of characteristic `p`. obtain ⟨K, _, _, H⟩ : ∃ (K : Type) [field K], by exactI ∃ [char_p K p], infinite K, { let K := fraction_ring (polynomial (zmod p)), let f : zmod p →+* K := (fraction_ring.of _).to_map.comp C, haveI : char_p K p := by { rw ← f.char_p_iff_char_p, apply_instance }, haveI : infinite K := by { apply infinite.of_injective _ (fraction_ring.of _).injective, apply_instance }, refine ⟨K, _, _, _⟩; apply_instance }, resetI, apply map_injective (zmod.cast_hom (dvd_refl p) K) (ring_hom.injective _), rw [map_lambdashev, map_pow, map_X], apply eq_of_infinite_eval_eq, -- The two polynomials agree on all `x` of the form `x = y + y⁻¹`. apply @set.infinite_mono _ {x : K | ∃ y, x = y + y⁻¹ ∧ y ≠ 0}, { rintro _ ⟨x, rfl, hx⟩, simp only [eval_X, eval_pow, set.mem_set_of_eq, @add_pow_char K _ p, lambdashev_eval_add_inv _ _ (mul_inv_cancel hx)] }, -- Now we need to show that the set of such `x` is infinite. -- If the set is finite, then we will show that `K` is also finite. { intro h, rw ← set.infinite_univ_iff at H, apply H, -- To each `x` of the form `x = y + y⁻¹` -- we `bind` the set of `y` that solve the equation `x = y + y⁻¹`. -- For every `x`, that set is finite (since it is governed by a quadratic equation). -- For the moment, we claim that all these sets together cover `K`. suffices : (set.univ : set K) = {x : K | ∃ (y : K), x = y + y⁻¹ ∧ y ≠ 0} >>= (λ x, {y | x = y + y⁻¹ ∨ y = 0}), { rw this, clear this, apply set.finite_bUnion h, rintro x hx, -- The following quadratic polynomial has as solutions the `y` for which `x = y + y⁻¹`. let φ : polynomial K := X ^ 2 - C x * X + 1, have hφ : φ ≠ 0, { intro H, have : φ.eval 0 = 0, by rw [H, eval_zero], simpa [eval_X, eval_one, eval_pow, eval_sub, sub_zero, eval_add, eval_mul, mul_zero, pow_two, zero_add, one_ne_zero] }, classical, convert (φ.roots ∪ {0}).to_finset.finite_to_set using 1, ext1 y, simp only [multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe, multiset.mem_union, mem_roots hφ, is_root, eval_add, eval_sub, eval_pow, eval_mul, eval_X, eval_C, eval_one, multiset.mem_singleton, multiset.singleton_eq_singleton], by_cases hy : y = 0, { simp only [hy, eq_self_iff_true, or_true] }, apply or_congr _ iff.rfl, rw [← mul_left_inj' hy, eq_comm, ← sub_eq_zero, add_mul, inv_mul_cancel hy], apply eq_iff_eq_cancel_right.mpr, ring }, -- Finally, we prove the claim that our finite union of finite sets covers all of `K`. { apply (set.eq_univ_of_forall _).symm, intro x, simp only [exists_prop, set.mem_Union, set.bind_def, ne.def, set.mem_set_of_eq], by_cases hx : x = 0, { simp only [hx, and_true, eq_self_iff_true, inv_zero, or_true], exact ⟨_, 1, rfl, one_ne_zero⟩ }, { simp only [hx, or_false, exists_eq_right], exact ⟨_, rfl, hx⟩ } } } end lemma lambdashev_char_p (p : ℕ) [fact p.prime] [char_p R p] : lambdashev R p = X ^ p := by rw [← map_lambdashev (zmod.cast_hom (dvd_refl p) R), lambdashev_zmod_p, map_pow, map_X] end lambdashev end polynomial
2ccb9b45daced19bd59ef5add253f7b581ca16c2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/pullbacks.lean
4576f31bfad73509158773c135a5c76e8e295c80
[ "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
83,484
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta, Andrew Yang -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. ## References * [Stacks: Fibre products](https://stacks.math.columbia.edu/tag/001U) * [Stacks: Pushouts](https://stacks.math.columbia.edu/tag/0025) -/ noncomputable theory open category_theory namespace category_theory.limits universes v₁ v₂ v u u₂ local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ @[pattern] abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ @[pattern] abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ @[pattern] abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ @[pattern] abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ @[pattern] abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ @[pattern] abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ @[pattern] abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ @[pattern] abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ @[pattern] abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span section open walking_cospan /-- The functor between two `walking_cospan`s in different universes. -/ def walking_cospan_functor : walking_cospan.{v₁} ⥤ walking_cospan.{v₂} := { obj := by { rintro (_|_|_), exacts [one, left, right] }, map := by { rintro _ _ (_|_|_), exacts [hom.id _, hom.inl, hom.inr] }, map_id' := λ X, rfl, map_comp' := λ _ _ _ _ _, subsingleton.elim _ _ } @[simp] lemma walking_cospan_functor_one : walking_cospan_functor.obj one = one := rfl @[simp] lemma walking_cospan_functor_left : walking_cospan_functor.obj left = left := rfl @[simp] lemma walking_cospan_functor_right : walking_cospan_functor.obj right = right := rfl @[simp] lemma walking_cospan_functor_id (X) : walking_cospan_functor.map (𝟙 X) = 𝟙 _ := rfl @[simp] lemma walking_cospan_functor_inl : walking_cospan_functor.map hom.inl = hom.inl := rfl @[simp] lemma walking_cospan_functor_inr : walking_cospan_functor.map hom.inr = hom.inr := rfl /-- The equivalence between two `walking_cospan`s in different universes. -/ def walking_cospan_equiv : walking_cospan.{v₁} ≌ walking_cospan.{v₂} := { functor := walking_cospan_functor, inverse := walking_cospan_functor, unit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }), counit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }) } end section open walking_span /-- The functor between two `walking_span`s in different universes. -/ def walking_span_functor : walking_span.{v₁} ⥤ walking_span.{v₂} := { obj := by { rintro (_|_|_), exacts [zero, left, right] }, map := by { rintro _ _ (_|_|_), exacts [hom.id _, hom.fst, hom.snd] }, map_id' := λ X, rfl, map_comp' := λ _ _ _ _ _, subsingleton.elim _ _ } @[simp] lemma walking_span_functor_zero : walking_span_functor.obj zero = zero := rfl @[simp] lemma walking_span_functor_left : walking_span_functor.obj left = left := rfl @[simp] lemma walking_span_functor_right : walking_span_functor.obj right = right := rfl @[simp] lemma walking_span_functor_id (X) : walking_span_functor.map (𝟙 X) = 𝟙 _ := rfl @[simp] lemma walking_span_functor_fst : walking_span_functor.map hom.fst = hom.fst := rfl @[simp] lemma walking_span_functor_snd : walking_span_functor.map hom.snd = hom.snd := rfl /-- The equivalence between two `walking_span`s in different universes. -/ def walking_span_equiv : walking_span.{v₁} ≌ walking_span.{v₂} := { functor := walking_span_functor, inverse := walking_span_functor, unit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }), counit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }) } end open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ @[simps {rhs_md := semireducible}] def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ @[simps {rhs_md := semireducible}] def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {W X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Π (s : pullback_cone f g), s.X ⟶ t.X) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ lemma mono_snd_of_is_pullback_of_mono {t : pullback_cone f g} (ht : is_limit t) [mono f] : mono t.snd := ⟨λ W h k i, is_limit.hom_ext ht (by simp [←cancel_mono f, t.condition, reassoc_of i]) i⟩ lemma mono_fst_of_is_pullback_of_mono {t : pullback_cone f g} (ht : is_limit t) [mono g] : mono t.fst := ⟨λ W h k i, is_limit.hom_ext ht i (by simp [←cancel_mono g, ←t.condition, reassoc_of i])⟩ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} {fst : W ⟶ X} {snd : W ⟶ Y} (eq : fst ≫ f = snd ≫ g) (lift : Π (s : pullback_cone f g), s.X ⟶ W) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end /-- The pullback cone `(𝟙 X, 𝟙 X)` for the pair `(f, f)` is a limit if `f` is a mono. The converse is shown in `mono_of_pullback_is_id`. -/ def is_limit_mk_id_id (f : X ⟶ Y) [mono f] : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f) := is_limit.mk _ (λ s, s.fst) (λ s, category.comp_id _) (λ s, by rw [←cancel_mono f, category.comp_id, s.condition]) (λ s m m₁ m₂, by simpa using m₁) /-- `f` is a mono if the pullback cone `(𝟙 X, 𝟙 X)` is a limit for the pair `(f, f)`. The converse is given in `pullback_cone.is_id_of_mono`. -/ lemma mono_of_is_limit_mk_id_id (f : X ⟶ Y) (t : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f)) : mono f := ⟨λ Z g h eq, by { rcases pullback_cone.is_limit.lift' t _ _ eq with ⟨_, rfl, rfl⟩, refl } ⟩ /-- Suppose `f` and `g` are two morphisms with a common codomain and `s` is a limit cone over the diagram formed by `f` and `g`. Suppose `f` and `g` both factor through a monomorphism `h` via `x` and `y`, respectively. Then `s` is also a limit cone over the diagram formed by `x` and `y`. -/ def is_limit_of_factors (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ Z) [mono h] (x : X ⟶ W) (y : Y ⟶ W) (hxh : x ≫ h = f) (hyh : y ≫ h = g) (s : pullback_cone f g) (hs : is_limit s) : is_limit (pullback_cone.mk _ _ (show s.fst ≫ x = s.snd ≫ y, from (cancel_mono h).1 $ by simp only [category.assoc, hxh, hyh, s.condition])) := pullback_cone.is_limit_aux' _ $ λ t, ⟨hs.lift (pullback_cone.mk t.fst t.snd $ by rw [←hxh, ←hyh, reassoc_of t.condition]), ⟨hs.fac _ walking_cospan.left, hs.fac _ walking_cospan.right, λ r hr hr', begin apply pullback_cone.is_limit.hom_ext hs; simp only [pullback_cone.mk_fst, pullback_cone.mk_snd] at ⊢ hr hr'; simp only [hr, hr']; symmetry, exacts [hs.fac _ walking_cospan.left, hs.fac _ walking_cospan.right] end⟩⟩ /-- If `W` is the pullback of `f, g`, it is also the pullback of `f ≫ i, g ≫ i` for any mono `i`. -/ def is_limit_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] (s : pullback_cone f g) (H : is_limit s) : is_limit (pullback_cone.mk _ _ (show s.fst ≫ f ≫ i = s.snd ≫ g ≫ i, by rw [← category.assoc, ← category.assoc, s.condition])) := begin apply pullback_cone.is_limit_aux', intro s, rcases pullback_cone.is_limit.lift' H s.fst s.snd ((cancel_mono i).mp (by simpa using s.condition)) with ⟨l, h₁, h₂⟩, refine ⟨l,h₁,h₂,_⟩, intros m hm₁ hm₂, exact (pullback_cone.is_limit.hom_ext H (hm₁.trans h₁.symm) (hm₂.trans h₂.symm) : _) end end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Π (s : pushout_cocone f g), t.X ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ lemma epi_inr_of_is_pushout_of_epi {t : pushout_cocone f g} (ht : is_colimit t) [epi f] : epi t.inr := ⟨λ W h k i, is_colimit.hom_ext ht (by simp [←cancel_epi f, t.condition_assoc, i]) i⟩ lemma epi_inl_of_is_pushout_of_epi {t : pushout_cocone f g} (ht : is_colimit t) [epi g] : epi t.inl := ⟨λ W h k i, is_colimit.hom_ext ht i (by simp [←cancel_epi g, ←t.condition_assoc, i])⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} {inl : Y ⟶ W} {inr : Z ⟶ W} (eq : f ≫ inl = g ≫ inr) (desc : Π (s : pushout_cocone f g), W ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end /-- The pushout cocone `(𝟙 X, 𝟙 X)` for the pair `(f, f)` is a colimit if `f` is an epi. The converse is shown in `epi_of_is_colimit_mk_id_id`. -/ def is_colimit_mk_id_id (f : X ⟶ Y) [epi f] : is_colimit (mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) := is_colimit.mk _ (λ s, s.inl) (λ s, category.id_comp _) (λ s, by rw [←cancel_epi f, category.id_comp, s.condition]) (λ s m m₁ m₂, by simpa using m₁) /-- `f` is an epi if the pushout cocone `(𝟙 X, 𝟙 X)` is a colimit for the pair `(f, f)`. The converse is given in `pushout_cocone.is_colimit_mk_id_id`. -/ lemma epi_of_is_colimit_mk_id_id (f : X ⟶ Y) (t : is_colimit (mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f := ⟨λ Z g h eq, by { rcases pushout_cocone.is_colimit.desc' t _ _ eq with ⟨_, rfl, rfl⟩, refl }⟩ /-- Suppose `f` and `g` are two morphisms with a common domain and `s` is a colimit cocone over the diagram formed by `f` and `g`. Suppose `f` and `g` both factor through an epimorphism `h` via `x` and `y`, respectively. Then `s` is also a colimit cocone over the diagram formed by `x` and `y`. -/ def is_colimit_of_factors (f : X ⟶ Y) (g : X ⟶ Z) (h : X ⟶ W) [epi h] (x : W ⟶ Y) (y : W ⟶ Z) (hhx : h ≫ x = f) (hhy : h ≫ y = g) (s : pushout_cocone f g) (hs : is_colimit s) : is_colimit (pushout_cocone.mk _ _ (show x ≫ s.inl = y ≫ s.inr, from (cancel_epi h).1 $ by rw [reassoc_of hhx, reassoc_of hhy, s.condition])) := pushout_cocone.is_colimit_aux' _ $ λ t, ⟨hs.desc (pushout_cocone.mk t.inl t.inr $ by rw [←hhx, ←hhy, category.assoc, category.assoc, t.condition]), ⟨hs.fac _ walking_span.left, hs.fac _ walking_span.right, λ r hr hr', begin apply pushout_cocone.is_colimit.hom_ext hs; simp only [pushout_cocone.mk_inl, pushout_cocone.mk_inr] at ⊢ hr hr'; simp only [hr, hr']; symmetry, exacts [hs.fac _ walking_span.left, hs.fac _ walking_span.right] end⟩⟩ /-- If `W` is the pushout of `f, g`, it is also the pushout of `h ≫ f, h ≫ g` for any epi `h`. -/ def is_colimit_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] (s : pushout_cocone f g) (H : is_colimit s) : is_colimit (pushout_cocone.mk _ _ (show (h ≫ f) ≫ s.inl = (h ≫ g) ≫ s.inr, by rw [category.assoc, category.assoc, s.condition])) := begin apply pushout_cocone.is_colimit_aux', intro s, rcases pushout_cocone.is_colimit.desc' H s.inl s.inr ((cancel_epi h).mp (by simpa using s.condition)) with ⟨l, h₁, h₂⟩, refine ⟨l,h₁,h₂,_⟩, intros m hm₁ hm₂, exact (pushout_cocone.is_colimit.hom_ext H (hm₁.trans h₁.symm) (hm₂.trans h₂.symm) : _) end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- A diagram `walking_cospan ⥤ C` is isomorphic to some `pullback_cone.mk` after composing with `diagram_iso_cospan`. -/ @[simps] def pullback_cone.iso_mk {F : walking_cospan ⥤ C} (t : cone F) : (cones.postcompose (diagram_iso_cospan.{v} _).hom).obj t ≅ pullback_cone.mk (t.π.app walking_cospan.left) (t.π.app walking_cospan.right) ((t.π.naturality inl).symm.trans (t.π.naturality inr : _)) := cones.ext (iso.refl _) $ by rintro (_|(_|_)); { dsimp, simp } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- A diagram `walking_span ⥤ C` is isomorphic to some `pushout_cocone.mk` after composing with `diagram_iso_span`. -/ @[simps] def pushout_cocone.iso_mk {F : walking_span ⥤ C} (t : cocone F) : (cocones.precompose (diagram_iso_span.{v} _).inv).obj t ≅ pushout_cocone.mk (t.ι.app walking_span.left) (t.ι.app walking_span.right) ((t.ι.naturality fst).trans (t.ι.naturality snd).symm) := cocones.ext (iso.refl _) $ by rintro (_|(_|_)); { dsimp, simp } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟶ Y` and `g : X ⟶ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Given such a diagram, then there is a natural morphism `W ×ₛ X ⟶ Y ×ₜ Z`. W ⟶ Y ↘ ↘ S ⟶ T ↗ ↗ X ⟶ Z -/ abbreviation pullback.map {W X Y Z S T : C} (f₁ : W ⟶ S) (f₂ : X ⟶ S) [has_pullback f₁ f₂] (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) [has_pullback g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) : pullback f₁ f₂ ⟶ pullback g₁ g₂ := pullback.lift (pullback.fst ≫ i₁) (pullback.snd ≫ i₂) (by simp [← eq₁, ← eq₂, pullback.condition_assoc]) /-- Given such a diagram, then there is a natural morphism `W ⨿ₛ X ⟶ Y ⨿ₜ Z`. W ⟶ Y ↗ ↗ S ⟶ T ↘ ↘ X ⟶ Z -/ abbreviation pushout.map {W X Y Z S T : C} (f₁ : S ⟶ W) (f₂ : S ⟶ X) [has_pushout f₁ f₂] (g₁ : T ⟶ Y) (g₂ : T ⟶ Z) [has_pushout g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₁ = i₃ ≫ g₁) (eq₂ : f₂ ≫ i₂ = i₃ ≫ g₂) : pushout f₁ f₂ ⟶ pushout g₁ g₂ := pushout.desc (i₁ ≫ pushout.inl) (i₂ ≫ pushout.inr) (by { simp only [← category.assoc, eq₁, eq₂], simp [pushout.condition] }) /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback cone built from the pullback projections is a pullback. -/ def pullback_is_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] : is_limit (pullback_cone.mk (pullback.fst : pullback f g ⟶ _) pullback.snd pullback.condition) := pullback_cone.is_limit.mk _ (λ s, pullback.lift s.fst s.snd s.condition) (by simp) (by simp) (by tidy) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := pullback_cone.mono_fst_of_is_pullback_of_mono (limit.is_limit _) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := pullback_cone.mono_snd_of_is_pullback_of_mono (limit.is_limit _) /-- The map `X ×[Z] Y ⟶ X × Y` is mono. -/ instance mono_pullback_to_prod {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_binary_product X Y] : mono (prod.lift pullback.fst pullback.snd : pullback f g ⟶ _) := ⟨λ W i₁ i₂ h, begin ext, { simpa using congr_arg (λ f, f ≫ prod.fst) h }, { simpa using congr_arg (λ f, f ≫ prod.snd) h } end⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout cocone built from the pushout coprojections is a pushout. -/ def pushout_is_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] : is_colimit (pushout_cocone.mk (pushout.inl : _ ⟶ pushout f g) pushout.inr pushout.condition) := pushout_cocone.is_colimit.mk _ (λ s, pushout.desc s.inl s.inr s.condition) (by simp) (by simp) (by tidy) /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := pushout_cocone.epi_inl_of_is_pushout_of_epi (colimit.is_colimit _) /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := pushout_cocone.epi_inr_of_is_pushout_of_epi (colimit.is_colimit _) /-- The map ` X ⨿ Y ⟶ X ⨿[Z] Y` is epi. -/ instance epi_coprod_to_pushout {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_binary_coproduct Y Z] : epi (coprod.desc pushout.inl pushout.inr : _ ⟶ pushout f g) := ⟨λ W i₁ i₂ h, begin ext, { simpa using congr_arg (λ f, coprod.inl ≫ f) h }, { simpa using congr_arg (λ f, coprod.inr ≫ f) h } end⟩ instance pullback.map_is_iso {W X Y Z S T : C} (f₁ : W ⟶ S) (f₂ : X ⟶ S) [has_pullback f₁ f₂] (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) [has_pullback g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) [is_iso i₁] [is_iso i₂] [is_iso i₃] : is_iso (pullback.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) := begin refine ⟨⟨pullback.map _ _ _ _ (inv i₁) (inv i₂) (inv i₃) _ _, _, _⟩⟩, { rw [is_iso.comp_inv_eq, category.assoc, eq₁, is_iso.inv_hom_id_assoc] }, { rw [is_iso.comp_inv_eq, category.assoc, eq₂, is_iso.inv_hom_id_assoc] }, tidy end /-- If `f₁ = f₂` and `g₁ = g₂`, we may construct a canonical isomorphism `pullback f₁ g₁ ≅ pullback f₂ g₂` -/ @[simps hom] def pullback.congr_hom {X Y Z : C} {f₁ f₂ : X ⟶ Z} {g₁ g₂ : Y ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pullback f₁ g₁] [has_pullback f₂ g₂] : pullback f₁ g₁ ≅ pullback f₂ g₂ := as_iso $ pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) @[simp] lemma pullback.congr_hom_inv {X Y Z : C} {f₁ f₂ : X ⟶ Z} {g₁ g₂ : Y ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pullback f₁ g₁] [has_pullback f₂ g₂] : (pullback.congr_hom h₁ h₂).inv = pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) := begin apply pullback.hom_ext, { erw pullback.lift_fst, rw iso.inv_comp_eq, erw pullback.lift_fst_assoc, rw [category.comp_id, category.comp_id] }, { erw pullback.lift_snd, rw iso.inv_comp_eq, erw pullback.lift_snd_assoc, rw [category.comp_id, category.comp_id] }, end instance pushout.map_is_iso {W X Y Z S T : C} (f₁ : S ⟶ W) (f₂ : S ⟶ X) [has_pushout f₁ f₂] (g₁ : T ⟶ Y) (g₂ : T ⟶ Z) [has_pushout g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₁ = i₃ ≫ g₁) (eq₂ : f₂ ≫ i₂ = i₃ ≫ g₂) [is_iso i₁] [is_iso i₂] [is_iso i₃] : is_iso (pushout.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) := begin refine ⟨⟨pushout.map _ _ _ _ (inv i₁) (inv i₂) (inv i₃) _ _, _, _⟩⟩, { rw [is_iso.comp_inv_eq, category.assoc, eq₁, is_iso.inv_hom_id_assoc] }, { rw [is_iso.comp_inv_eq, category.assoc, eq₂, is_iso.inv_hom_id_assoc] }, tidy end /-- If `f₁ = f₂` and `g₁ = g₂`, we may construct a canonical isomorphism `pushout f₁ g₁ ≅ pullback f₂ g₂` -/ @[simps hom] def pushout.congr_hom {X Y Z : C} {f₁ f₂ : X ⟶ Y} {g₁ g₂ : X ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pushout f₁ g₁] [has_pushout f₂ g₂] : pushout f₁ g₁ ≅ pushout f₂ g₂ := as_iso $ pushout.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) @[simp] lemma pushout.congr_hom_inv {X Y Z : C} {f₁ f₂ : X ⟶ Y} {g₁ g₂ : X ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pushout f₁ g₁] [has_pushout f₂ g₂] : (pushout.congr_hom h₁ h₂).inv = pushout.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) := begin apply pushout.hom_ext, { erw pushout.inl_desc, rw [iso.comp_inv_eq, category.id_comp], erw pushout.inl_desc, rw category.id_comp }, { erw pushout.inr_desc, rw [iso.comp_inv_eq, category.id_comp], erw pushout.inr_desc, rw category.id_comp } end section variables {D : Type u₂} [category.{v} D] (G : C ⥤ D) /-- The comparison morphism for the pullback of `f,g`. This is an isomorphism iff `G` preserves the pullback of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : G.obj (pullback f g) ⟶ pullback (G.map f) (G.map g) := pullback.lift (G.map pullback.fst) (G.map pullback.snd) (by simp only [←G.map_comp, pullback.condition]) @[simp, reassoc] lemma pullback_comparison_comp_fst (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.fst = G.map pullback.fst := pullback.lift_fst _ _ _ @[simp, reassoc] lemma pullback_comparison_comp_snd (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.snd = G.map pullback.snd := pullback.lift_snd _ _ _ @[simp, reassoc] lemma map_lift_pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] {W : C} {h : W ⟶ X} {k : W ⟶ Y} (w : h ≫ f = k ≫ g) : G.map (pullback.lift _ _ w) ≫ pullback_comparison G f g = pullback.lift (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } /-- The comparison morphism for the pushout of `f,g`. This is an isomorphism iff `G` preserves the pushout of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout (G.map f) (G.map g) ⟶ G.obj (pushout f g) := pushout.desc (G.map pushout.inl) (G.map pushout.inr) (by simp only [←G.map_comp, pushout.condition]) @[simp, reassoc] lemma inl_comp_pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout.inl ≫ pushout_comparison G f g = G.map pushout.inl := pushout.inl_desc _ _ _ @[simp, reassoc] lemma inr_comp_pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout.inr ≫ pushout_comparison G f g = G.map pushout.inr := pushout.inr_desc _ _ _ @[simp, reassoc] lemma pushout_comparison_map_desc (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] {W : C} {h : Y ⟶ W} {k : Z ⟶ W} (w : f ≫ h = g ≫ k) : pushout_comparison G f g ≫ G.map (pushout.desc _ _ w) = pushout.desc (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } end section pullback_symmetry open walking_cospan variables (f : X ⟶ Z) (g : Y ⟶ Z) /-- Making this a global instance would make the typeclass seach go in an infinite loop. -/ lemma has_pullback_symmetry [has_pullback f g] : has_pullback g f := ⟨⟨⟨pullback_cone.mk _ _ pullback.condition.symm, pullback_cone.flip_is_limit (pullback_is_pullback _ _)⟩⟩⟩ local attribute [instance] has_pullback_symmetry /-- The isomorphism `X ×[Z] Y ≅ Y ×[Z] X`. -/ def pullback_symmetry [has_pullback f g] : pullback f g ≅ pullback g f := is_limit.cone_point_unique_up_to_iso (pullback_cone.flip_is_limit (pullback_is_pullback f g) : is_limit (pullback_cone.mk _ _ pullback.condition.symm)) (limit.is_limit _) @[simp, reassoc] lemma pullback_symmetry_hom_comp_fst [has_pullback f g] : (pullback_symmetry f g).hom ≫ pullback.fst = pullback.snd := by simp [pullback_symmetry] @[simp, reassoc] lemma pullback_symmetry_hom_comp_snd [has_pullback f g] : (pullback_symmetry f g).hom ≫ pullback.snd = pullback.fst := by simp [pullback_symmetry] @[simp, reassoc] lemma pullback_symmetry_inv_comp_fst [has_pullback f g] : (pullback_symmetry f g).inv ≫ pullback.fst = pullback.snd := by simp [iso.inv_comp_eq] @[simp, reassoc] lemma pullback_symmetry_inv_comp_snd [has_pullback f g] : (pullback_symmetry f g).inv ≫ pullback.snd = pullback.fst := by simp [iso.inv_comp_eq] end pullback_symmetry section pushout_symmetry open walking_cospan variables (f : X ⟶ Y) (g : X ⟶ Z) /-- Making this a global instance would make the typeclass seach go in an infinite loop. -/ lemma has_pushout_symmetry [has_pushout f g] : has_pushout g f := ⟨⟨⟨pushout_cocone.mk _ _ pushout.condition.symm, pushout_cocone.flip_is_colimit (pushout_is_pushout _ _)⟩⟩⟩ local attribute [instance] has_pushout_symmetry /-- The isomorphism `Y ⨿[X] Z ≅ Z ⨿[X] Y`. -/ def pushout_symmetry [has_pushout f g] : pushout f g ≅ pushout g f := is_colimit.cocone_point_unique_up_to_iso (pushout_cocone.flip_is_colimit (pushout_is_pushout f g) : is_colimit (pushout_cocone.mk _ _ pushout.condition.symm)) (colimit.is_colimit _) @[simp, reassoc] lemma inl_comp_pushout_symmetry_hom [has_pushout f g] : pushout.inl ≫ (pushout_symmetry f g).hom = pushout.inr := (colimit.is_colimit (span f g)).comp_cocone_point_unique_up_to_iso_hom (pushout_cocone.flip_is_colimit (pushout_is_pushout g f)) _ @[simp, reassoc] lemma inr_comp_pushout_symmetry_hom [has_pushout f g] : pushout.inr ≫ (pushout_symmetry f g).hom = pushout.inl := (colimit.is_colimit (span f g)).comp_cocone_point_unique_up_to_iso_hom (pushout_cocone.flip_is_colimit (pushout_is_pushout g f)) _ @[simp, reassoc] lemma inl_comp_pushout_symmetry_inv [has_pushout f g] : pushout.inl ≫ (pushout_symmetry f g).inv = pushout.inr := by simp [iso.comp_inv_eq] @[simp, reassoc] lemma inr_comp_pushout_symmetry_inv [has_pushout f g] : pushout.inr ≫ (pushout_symmetry f g).inv = pushout.inl := by simp [iso.comp_inv_eq] end pushout_symmetry section pullback_left_iso open walking_cospan /-- The pullback of `f, g` is also the pullback of `f ≫ i, g ≫ i` for any mono `i`. -/ noncomputable def pullback_is_pullback_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] [has_pullback f g] : is_limit (pullback_cone.mk pullback.fst pullback.snd _) := pullback_cone.is_limit_of_comp_mono f g i _ (limit.is_limit (cospan f g)) instance has_pullback_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] [has_pullback f g] : has_pullback (f ≫ i) (g ≫ i) := ⟨⟨⟨_,pullback_is_pullback_of_comp_mono f g i⟩⟩⟩ variables (f : X ⟶ Z) (g : Y ⟶ Z) [is_iso f] /-- If `f : X ⟶ Z` is iso, then `X ×[Z] Y ≅ Y`. This is the explicit limit cone. -/ def pullback_cone_of_left_iso : pullback_cone f g := pullback_cone.mk (g ≫ inv f) (𝟙 _) $ by simp @[simp] lemma pullback_cone_of_left_iso_X : (pullback_cone_of_left_iso f g).X = Y := rfl @[simp] lemma pullback_cone_of_left_iso_fst : (pullback_cone_of_left_iso f g).fst = g ≫ inv f := rfl @[simp] lemma pullback_cone_of_left_iso_snd : (pullback_cone_of_left_iso f g).snd = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_left_iso_π_app_none : (pullback_cone_of_left_iso f g).π.app none = g := by { delta pullback_cone_of_left_iso, simp } @[simp] lemma pullback_cone_of_left_iso_π_app_left : (pullback_cone_of_left_iso f g).π.app left = g ≫ inv f := rfl @[simp] lemma pullback_cone_of_left_iso_π_app_right : (pullback_cone_of_left_iso f g).π.app right = 𝟙 _ := rfl /-- Verify that the constructed limit cone is indeed a limit. -/ def pullback_cone_of_left_iso_is_limit : is_limit (pullback_cone_of_left_iso f g) := pullback_cone.is_limit_aux' _ (λ s, ⟨s.snd, by simp [← s.condition_assoc]⟩) lemma has_pullback_of_left_iso : has_pullback f g := ⟨⟨⟨_, pullback_cone_of_left_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pullback_of_left_iso instance pullback_snd_iso_of_left_iso : is_iso (pullback.snd : pullback f g ⟶ _) := begin refine ⟨⟨pullback.lift (g ≫ inv f) (𝟙 _) (by simp), _, by simp⟩⟩, ext, { simp [← pullback.condition_assoc] }, { simp [pullback.condition_assoc] }, end variables (i : Z ⟶ W) [mono i] instance has_pullback_of_right_factors_mono (f : X ⟶ Z) : has_pullback i (f ≫ i) := by { nth_rewrite 0 ← category.id_comp i, apply_instance } instance pullback_snd_iso_of_right_factors_mono (f : X ⟶ Z) : is_iso (pullback.snd : pullback i (f ≫ i) ⟶ _) := begin convert (congr_arg is_iso (show _ ≫ pullback.snd = _, from limit.iso_limit_cone_hom_π ⟨_,pullback_is_pullback_of_comp_mono (𝟙 _) f i⟩ walking_cospan.right)).mp infer_instance; exact (category.id_comp _).symm end end pullback_left_iso section pullback_right_iso open walking_cospan variables (f : X ⟶ Z) (g : Y ⟶ Z) [is_iso g] /-- If `g : Y ⟶ Z` is iso, then `X ×[Z] Y ≅ X`. This is the explicit limit cone. -/ def pullback_cone_of_right_iso : pullback_cone f g := pullback_cone.mk (𝟙 _) (f ≫ inv g) $ by simp @[simp] lemma pullback_cone_of_right_iso_X : (pullback_cone_of_right_iso f g).X = X := rfl @[simp] lemma pullback_cone_of_right_iso_fst : (pullback_cone_of_right_iso f g).fst = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_right_iso_snd : (pullback_cone_of_right_iso f g).snd = f ≫ inv g := rfl @[simp] lemma pullback_cone_of_right_iso_π_app_none : (pullback_cone_of_right_iso f g).π.app none = f := category.id_comp _ @[simp] lemma pullback_cone_of_right_iso_π_app_left : (pullback_cone_of_right_iso f g).π.app left = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_right_iso_π_app_right : (pullback_cone_of_right_iso f g).π.app right = f ≫ inv g := rfl /-- Verify that the constructed limit cone is indeed a limit. -/ def pullback_cone_of_right_iso_is_limit : is_limit (pullback_cone_of_right_iso f g) := pullback_cone.is_limit_aux' _ (λ s, ⟨s.fst, by simp [s.condition_assoc]⟩) lemma has_pullback_of_right_iso : has_pullback f g := ⟨⟨⟨_, pullback_cone_of_right_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pullback_of_right_iso instance pullback_snd_iso_of_right_iso : is_iso (pullback.fst : pullback f g ⟶ _) := begin refine ⟨⟨pullback.lift (𝟙 _) (f ≫ inv g) (by simp), _, by simp⟩⟩, ext, { simp }, { simp [pullback.condition_assoc] }, end variables (i : Z ⟶ W) [mono i] instance has_pullback_of_left_factors_mono (f : X ⟶ Z) : has_pullback (f ≫ i) i := by { nth_rewrite 1 ← category.id_comp i, apply_instance } instance pullback_snd_iso_of_left_factors_mono (f : X ⟶ Z) : is_iso (pullback.fst : pullback (f ≫ i) i ⟶ _) := begin convert (congr_arg is_iso (show _ ≫ pullback.fst = _, from limit.iso_limit_cone_hom_π ⟨_,pullback_is_pullback_of_comp_mono f (𝟙 _) i⟩ walking_cospan.left)).mp infer_instance; exact (category.id_comp _).symm end end pullback_right_iso section pushout_left_iso open walking_span /-- The pushout of `f, g` is also the pullback of `h ≫ f, h ≫ g` for any epi `h`. -/ noncomputable def pushout_is_pushout_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] [has_pushout f g] : is_colimit (pushout_cocone.mk pushout.inl pushout.inr _) := pushout_cocone.is_colimit_of_epi_comp f g h _ (colimit.is_colimit (span f g)) instance has_pushout_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] [has_pushout f g] : has_pushout (h ≫ f) (h ≫ g) := ⟨⟨⟨_,pushout_is_pushout_of_epi_comp f g h⟩⟩⟩ variables (f : X ⟶ Y) (g : X ⟶ Z) [is_iso f] /-- If `f : X ⟶ Y` is iso, then `Y ⨿[X] Z ≅ Z`. This is the explicit colimit cocone. -/ def pushout_cocone_of_left_iso : pushout_cocone f g := pushout_cocone.mk (inv f ≫ g) (𝟙 _) $ by simp @[simp] lemma pushout_cocone_of_left_iso_X : (pushout_cocone_of_left_iso f g).X = Z := rfl @[simp] lemma pushout_cocone_of_left_iso_inl : (pushout_cocone_of_left_iso f g).inl = inv f ≫ g := rfl @[simp] lemma pushout_cocone_of_left_iso_inr : (pushout_cocone_of_left_iso f g).inr = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_left_iso_ι_app_none : (pushout_cocone_of_left_iso f g).ι.app none = g := by { delta pushout_cocone_of_left_iso, simp } @[simp] lemma pushout_cocone_of_left_iso_ι_app_left : (pushout_cocone_of_left_iso f g).ι.app left = inv f ≫ g := rfl @[simp] lemma pushout_cocone_of_left_iso_ι_app_right : (pushout_cocone_of_left_iso f g).ι.app right = 𝟙 _ := rfl /-- Verify that the constructed cocone is indeed a colimit. -/ def pushout_cocone_of_left_iso_is_limit : is_colimit (pushout_cocone_of_left_iso f g) := pushout_cocone.is_colimit_aux' _ (λ s, ⟨s.inr, by simp [← s.condition]⟩) lemma has_pushout_of_left_iso : has_pushout f g := ⟨⟨⟨_, pushout_cocone_of_left_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pushout_of_left_iso instance pushout_inr_iso_of_left_iso : is_iso (pushout.inr : _ ⟶ pushout f g) := begin refine ⟨⟨pushout.desc (inv f ≫ g) (𝟙 _) (by simp), (by simp), _⟩⟩, ext, { simp [← pushout.condition] }, { simp [pushout.condition_assoc] }, end variables (h : W ⟶ X) [epi h] instance has_pushout_of_right_factors_epi (f : X ⟶ Y) : has_pushout h (h ≫ f) := by { nth_rewrite 0 ← category.comp_id h, apply_instance } instance pushout_inr_iso_of_right_factors_epi (f : X ⟶ Y) : is_iso (pushout.inr : _ ⟶ pushout h (h ≫ f)) := begin convert (congr_arg is_iso (show pushout.inr ≫ _ = _, from colimit.iso_colimit_cocone_ι_inv ⟨_, pushout_is_pushout_of_epi_comp (𝟙 _) f h⟩ walking_span.right)).mp infer_instance; exact (category.comp_id _).symm end end pushout_left_iso section pushout_right_iso open walking_span variables (f : X ⟶ Y) (g : X ⟶ Z) [is_iso g] /-- If `f : X ⟶ Z` is iso, then `Y ⨿[X] Z ≅ Y`. This is the explicit colimit cocone. -/ def pushout_cocone_of_right_iso : pushout_cocone f g := pushout_cocone.mk (𝟙 _) (inv g ≫ f) $ by simp @[simp] lemma pushout_cocone_of_right_iso_X : (pushout_cocone_of_right_iso f g).X = Y := rfl @[simp] lemma pushout_cocone_of_right_iso_inl : (pushout_cocone_of_right_iso f g).inl = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_right_iso_inr : (pushout_cocone_of_right_iso f g).inr = inv g ≫ f := rfl @[simp] lemma pushout_cocone_of_right_iso_ι_app_none : (pushout_cocone_of_right_iso f g).ι.app none = f := by { delta pushout_cocone_of_right_iso, simp } @[simp] lemma pushout_cocone_of_right_iso_ι_app_left : (pushout_cocone_of_right_iso f g).ι.app left = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_right_iso_ι_app_right : (pushout_cocone_of_right_iso f g).ι.app right = inv g ≫ f := rfl /-- Verify that the constructed cocone is indeed a colimit. -/ def pushout_cocone_of_right_iso_is_limit : is_colimit (pushout_cocone_of_right_iso f g) := pushout_cocone.is_colimit_aux' _ (λ s, ⟨s.inl, by simp [←s.condition]⟩) lemma has_pushout_of_right_iso : has_pushout f g := ⟨⟨⟨_, pushout_cocone_of_right_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pushout_of_right_iso instance pushout_inl_iso_of_right_iso : is_iso (pushout.inl : _ ⟶ pushout f g) := begin refine ⟨⟨pushout.desc (𝟙 _) (inv g ≫ f) (by simp), (by simp), _⟩⟩, ext, { simp [←pushout.condition] }, { simp [pushout.condition] }, end variables (h : W ⟶ X) [epi h] instance has_pushout_of_left_factors_epi (f : X ⟶ Y) : has_pushout (h ≫ f) h := by { nth_rewrite 1 ← category.comp_id h, apply_instance } instance pushout_inl_iso_of_left_factors_epi (f : X ⟶ Y) : is_iso (pushout.inl : _ ⟶ pushout (h ≫ f) h) := begin convert (congr_arg is_iso (show pushout.inl ≫ _ = _, from colimit.iso_colimit_cocone_ι_inv ⟨_, pushout_is_pushout_of_epi_comp f (𝟙 _) h⟩ walking_span.left)).mp infer_instance; exact (category.comp_id _).symm end end pushout_right_iso section open walking_cospan variable (f : X ⟶ Y) instance has_kernel_pair_of_mono [mono f] : has_pullback f f := ⟨⟨⟨_, pullback_cone.is_limit_mk_id_id f⟩⟩⟩ lemma fst_eq_snd_of_mono_eq [mono f] : (pullback.fst : pullback f f ⟶ _) = pullback.snd := ((pullback_cone.is_limit_mk_id_id f).fac (get_limit_cone (cospan f f)).cone left).symm.trans ((pullback_cone.is_limit_mk_id_id f).fac (get_limit_cone (cospan f f)).cone right : _) @[simp] lemma pullback_symmetry_hom_of_mono_eq [mono f] : (pullback_symmetry f f).hom = 𝟙 _ := by ext; simp [fst_eq_snd_of_mono_eq] instance fst_iso_of_mono_eq [mono f] : is_iso (pullback.fst : pullback f f ⟶ _) := begin refine ⟨⟨pullback.lift (𝟙 _) (𝟙 _) (by simp), _, by simp⟩⟩, ext, { simp }, { simp [fst_eq_snd_of_mono_eq] } end instance snd_iso_of_mono_eq [mono f] : is_iso (pullback.snd : pullback f f ⟶ _) := by { rw ← fst_eq_snd_of_mono_eq, apply_instance } end section open walking_span variable (f : X ⟶ Y) instance has_cokernel_pair_of_epi [epi f] : has_pushout f f := ⟨⟨⟨_, pushout_cocone.is_colimit_mk_id_id f⟩⟩⟩ lemma inl_eq_inr_of_epi_eq [epi f] : (pushout.inl : _ ⟶ pushout f f) = pushout.inr := ((pushout_cocone.is_colimit_mk_id_id f).fac (get_colimit_cocone (span f f)).cocone left).symm.trans ((pushout_cocone.is_colimit_mk_id_id f).fac (get_colimit_cocone (span f f)).cocone right : _) @[simp] lemma pullback_symmetry_hom_of_epi_eq [epi f] : (pushout_symmetry f f).hom = 𝟙 _ := by ext; simp [inl_eq_inr_of_epi_eq] instance inl_iso_of_epi_eq [epi f] : is_iso (pushout.inl : _ ⟶ pushout f f) := begin refine ⟨⟨pushout.desc (𝟙 _) (𝟙 _) (by simp), by simp, _⟩⟩, ext, { simp }, { simp [inl_eq_inr_of_epi_eq] } end instance inr_iso_of_epi_eq [epi f] : is_iso (pushout.inr : _ ⟶ pushout f f) := by { rw ← inl_eq_inr_of_epi_eq, apply_instance } end section paste_lemma variables {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ X₂) (f₂ : X₂ ⟶ X₃) (g₁ : Y₁ ⟶ Y₂) (g₂ : Y₂ ⟶ Y₃) variables (i₁ : X₁ ⟶ Y₁) (i₂ : X₂ ⟶ Y₂) (i₃ : X₃ ⟶ Y₃) variables (h₁ : i₁ ≫ g₁ = f₁ ≫ i₂) (h₂ : i₂ ≫ g₂ = f₂ ≫ i₃) /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the big square is a pullback if both the small squares are. -/ def big_square_is_pullback (H : is_limit (pullback_cone.mk _ _ h₂)) (H' : is_limit (pullback_cone.mk _ _ h₁)) : is_limit (pullback_cone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc])) := begin fapply pullback_cone.is_limit_aux', intro s, have : (s.fst ≫ g₁) ≫ g₂ = s.snd ≫ i₃ := by rw [← s.condition, category.assoc], rcases pullback_cone.is_limit.lift' H (s.fst ≫ g₁) s.snd this with ⟨l₁, hl₁, hl₁'⟩, rcases pullback_cone.is_limit.lift' H' s.fst l₁ hl₁.symm with ⟨l₂, hl₂, hl₂'⟩, use l₂, use hl₂, use show l₂ ≫ f₁ ≫ f₂ = s.snd, by { rw [← hl₁', ← hl₂', category.assoc], refl }, intros m hm₁ hm₂, apply pullback_cone.is_limit.hom_ext H', { erw [hm₁, hl₂] }, { apply pullback_cone.is_limit.hom_ext H, { erw [category.assoc, ← h₁, ← category.assoc, hm₁, ← hl₂, category.assoc, category.assoc, h₁], refl }, { erw [category.assoc, hm₂, ← hl₁', ← hl₂'] } } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the big square is a pushout if both the small squares are. -/ def big_square_is_pushout (H : is_colimit (pushout_cocone.mk _ _ h₂)) (H' : is_colimit (pushout_cocone.mk _ _ h₁)) : is_colimit (pushout_cocone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc])) := begin fapply pushout_cocone.is_colimit_aux', intro s, have : i₁ ≫ s.inl = f₁ ≫ (f₂ ≫ s.inr) := by rw [s.condition, category.assoc], rcases pushout_cocone.is_colimit.desc' H' s.inl (f₂ ≫ s.inr) this with ⟨l₁, hl₁, hl₁'⟩, rcases pushout_cocone.is_colimit.desc' H l₁ s.inr hl₁' with ⟨l₂, hl₂, hl₂'⟩, use l₂, use show (g₁ ≫ g₂) ≫ l₂ = s.inl, by { rw [← hl₁, ← hl₂, category.assoc], refl }, use hl₂', intros m hm₁ hm₂, apply pushout_cocone.is_colimit.hom_ext H, { apply pushout_cocone.is_colimit.hom_ext H', { erw [← category.assoc, hm₁, hl₂, hl₁] }, { erw [← category.assoc, h₂, category.assoc, hm₂, ← hl₂', ← category.assoc, ← category.assoc, ← h₂], refl } }, { erw [hm₂, hl₂'] } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the left square is a pullback if the right square and the big square are. -/ def left_square_is_pullback (H : is_limit (pullback_cone.mk _ _ h₂)) (H' : is_limit (pullback_cone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc]))) : is_limit (pullback_cone.mk _ _ h₁) := begin fapply pullback_cone.is_limit_aux', intro s, have : s.fst ≫ g₁ ≫ g₂ = (s.snd ≫ f₂) ≫ i₃ := by { rw [← category.assoc, s.condition, category.assoc, category.assoc, h₂] }, rcases pullback_cone.is_limit.lift' H' s.fst (s.snd ≫ f₂) this with ⟨l₁, hl₁, hl₁'⟩, use l₁, use hl₁, split, { apply pullback_cone.is_limit.hom_ext H, { erw [category.assoc, ← h₁, ← category.assoc, hl₁, s.condition], refl }, { erw [category.assoc, hl₁'], refl } }, { intros m hm₁ hm₂, apply pullback_cone.is_limit.hom_ext H', { erw [hm₁, hl₁] }, { erw [hl₁', ← hm₂], exact (category.assoc _ _ _).symm } } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the right square is a pushout if the left square and the big square are. -/ def right_square_is_pushout (H : is_colimit (pushout_cocone.mk _ _ h₁)) (H' : is_colimit (pushout_cocone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc]))) : is_colimit (pushout_cocone.mk _ _ h₂) := begin fapply pushout_cocone.is_colimit_aux', intro s, have : i₁ ≫ g₁ ≫ s.inl = (f₁ ≫ f₂) ≫ s.inr := by { rw [category.assoc, ← s.condition, ← category.assoc, ← category.assoc, h₁] }, rcases pushout_cocone.is_colimit.desc' H' (g₁ ≫ s.inl) s.inr this with ⟨l₁, hl₁, hl₁'⟩, dsimp at *, use l₁, refine ⟨_,_,_⟩, { apply pushout_cocone.is_colimit.hom_ext H, { erw [← category.assoc, hl₁], refl }, { erw [← category.assoc, h₂, category.assoc, hl₁', s.condition] } }, { exact hl₁' }, { intros m hm₁ hm₂, apply pushout_cocone.is_colimit.hom_ext H', { erw [hl₁, category.assoc, hm₁] }, { erw [hm₂, hl₁'] } } end end paste_lemma section variables (f : X ⟶ Z) (g : Y ⟶ Z) (f' : W ⟶ X) variables [has_pullback f g] [has_pullback f' (pullback.fst : pullback f g ⟶ _)] variables [has_pullback (f' ≫ f) g] /-- The canonical isomorphism `W ×[X] (X ×[Z] Y) ≅ W ×[Z] Y` -/ noncomputable def pullback_right_pullback_fst_iso : pullback f' (pullback.fst : pullback f g ⟶ _) ≅ pullback (f' ≫ f) g := begin let := big_square_is_pullback (pullback.snd : pullback f' (pullback.fst : pullback f g ⟶ _) ⟶ _) pullback.snd f' f pullback.fst pullback.fst g pullback.condition pullback.condition (pullback_is_pullback _ _) (pullback_is_pullback _ _), exact (this.cone_point_unique_up_to_iso (pullback_is_pullback _ _) : _) end @[simp, reassoc] lemma pullback_right_pullback_fst_iso_hom_fst : (pullback_right_pullback_fst_iso f g f').hom ≫ pullback.fst = pullback.fst := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.left @[simp, reassoc] lemma pullback_right_pullback_fst_iso_hom_snd : (pullback_right_pullback_fst_iso f g f').hom ≫ pullback.snd = pullback.snd ≫ pullback.snd := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_fst : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.fst = pullback.fst := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.left @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_snd_snd : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.snd ≫ pullback.snd = pullback.snd := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.right @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_snd_fst : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ f' := begin rw ← pullback.condition, exact pullback_right_pullback_fst_iso_inv_fst_assoc _ _ _ _ end end section variables (f : X ⟶ Y) (g : X ⟶ Z) (g' : Z ⟶ W) variables [has_pushout f g] [has_pushout (pushout.inr : _ ⟶ pushout f g) g'] variables [has_pushout f (g ≫ g')] /-- The canonical isomorphism `(Y ⨿[X] Z) ⨿[Z] W ≅ Y ×[X] W` -/ noncomputable def pushout_left_pushout_inr_iso : pushout (pushout.inr : _ ⟶ pushout f g) g' ≅ pushout f (g ≫ g') := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .cocone_point_unique_up_to_iso (pushout_is_pushout _ _) : _) @[simp, reassoc] lemma inl_pushout_left_pushout_inr_iso_inv : pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').inv = pushout.inl ≫ pushout.inl := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .comp_cocone_point_unique_up_to_iso_inv (pushout_is_pushout _ _) walking_span.left : _) @[simp, reassoc] lemma inr_pushout_left_pushout_inr_iso_hom : pushout.inr ≫ (pushout_left_pushout_inr_iso f g g').hom = pushout.inr := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .comp_cocone_point_unique_up_to_iso_hom (pushout_is_pushout _ _) walking_span.right : _) @[simp, reassoc] lemma inr_pushout_left_pushout_inr_iso_inv : pushout.inr ≫ (pushout_left_pushout_inr_iso f g g').inv = pushout.inr := by rw [iso.comp_inv_eq, inr_pushout_left_pushout_inr_iso_hom] @[simp, reassoc] lemma inl_inl_pushout_left_pushout_inr_iso_hom : pushout.inl ≫ pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').hom = pushout.inl := by rw [← category.assoc, ← iso.eq_comp_inv, inl_pushout_left_pushout_inr_iso_inv] @[simp, reassoc] lemma inr_inl_pushout_left_pushout_inr_iso_hom : pushout.inr ≫ pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').hom = g' ≫ pushout.inr := by rw [← category.assoc, ← iso.eq_comp_inv, category.assoc, inr_pushout_left_pushout_inr_iso_inv, pushout.condition] end section pullback_assoc /- The objects and morphisms are as follows: Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ where the two squares are pullbacks. We can then construct the pullback squares W - l₂ -> Z₂ - g₄ -> X₃ | | l₁ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ and W' - l₂' -> Z₂ | | l₁' g₃ ∨ ∨ Z₁ X₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ We will show that both `W` and `W'` are pullbacks over `g₁, g₂`, and thus we may construct a canonical isomorphism between them. -/ variables {X₁ X₂ X₃ Y₁ Y₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₁) (f₃ : X₂ ⟶ Y₂) variables (f₄ : X₃ ⟶ Y₂) [has_pullback f₁ f₂] [has_pullback f₃ f₄] include f₁ f₂ f₃ f₄ local notation `Z₁` := pullback f₁ f₂ local notation `Z₂` := pullback f₃ f₄ local notation `g₁` := (pullback.fst : Z₁ ⟶ X₁) local notation `g₂` := (pullback.snd : Z₁ ⟶ X₂) local notation `g₃` := (pullback.fst : Z₂ ⟶ X₂) local notation `g₄` := (pullback.snd : Z₂ ⟶ X₃) local notation `W` := pullback (g₂ ≫ f₃) f₄ local notation `W'` := pullback f₁ (g₃ ≫ f₂) local notation `l₁` := (pullback.fst : W ⟶ Z₁) local notation `l₂` := (pullback.lift (pullback.fst ≫ g₂) pullback.snd ((category.assoc _ _ _).trans pullback.condition) : W ⟶ Z₂) local notation `l₁'`:= (pullback.lift pullback.fst (pullback.snd ≫ g₃) (pullback.condition.trans (category.assoc _ _ _).symm) : W' ⟶ Z₁) local notation `l₂'`:= (pullback.snd : W' ⟶ Z₂) /-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/ def pullback_pullback_left_is_pullback [has_pullback (g₂ ≫ f₃) f₄] : is_limit (pullback_cone.mk l₁ l₂ (show l₁ ≫ g₂ = l₂ ≫ g₃, from (pullback.lift_fst _ _ _).symm)) := begin apply left_square_is_pullback, exact pullback_is_pullback f₃ f₄, convert pullback_is_pullback (g₂ ≫ f₃) f₄, rw pullback.lift_snd end /-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/ def pullback_assoc_is_pullback [has_pullback (g₂ ≫ f₃) f₄] : is_limit (pullback_cone.mk (l₁ ≫ g₁) l₂ (show (l₁ ≫ g₁) ≫ f₁ = l₂ ≫ (g₃ ≫ f₂), by rw [pullback.lift_fst_assoc, category.assoc, category.assoc, pullback.condition])) := begin apply pullback_cone.flip_is_limit, apply big_square_is_pullback, { apply pullback_cone.flip_is_limit, exact pullback_is_pullback f₁ f₂ }, { apply pullback_cone.flip_is_limit, apply pullback_pullback_left_is_pullback }, { exact pullback.lift_fst _ _ _ }, { exact pullback.condition.symm } end lemma has_pullback_assoc [has_pullback (g₂ ≫ f₃) f₄] : has_pullback f₁ (g₃ ≫ f₂) := ⟨⟨⟨_, pullback_assoc_is_pullback f₁ f₂ f₃ f₄⟩⟩⟩ /-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/ def pullback_pullback_right_is_pullback [has_pullback f₁ (g₃ ≫ f₂)] : is_limit (pullback_cone.mk l₁' l₂' (show l₁' ≫ g₂ = l₂' ≫ g₃, from pullback.lift_snd _ _ _)) := begin apply pullback_cone.flip_is_limit, apply left_square_is_pullback, { apply pullback_cone.flip_is_limit, exact pullback_is_pullback f₁ f₂ }, { apply pullback_cone.flip_is_limit, convert pullback_is_pullback f₁ (g₃ ≫ f₂), rw pullback.lift_fst }, { exact pullback.condition.symm } end /-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[Y₂] X₃`. -/ def pullback_assoc_symm_is_pullback [has_pullback f₁ (g₃ ≫ f₂)] : is_limit (pullback_cone.mk l₁' (l₂' ≫ g₄) (show l₁' ≫ (g₂ ≫ f₃) = (l₂' ≫ g₄) ≫ f₄, by rw [pullback.lift_snd_assoc, category.assoc, category.assoc, pullback.condition])) := begin apply big_square_is_pullback, exact pullback_is_pullback f₃ f₄, apply pullback_pullback_right_is_pullback end lemma has_pullback_assoc_symm [has_pullback f₁ (g₃ ≫ f₂)] : has_pullback (g₂ ≫ f₃) f₄ := ⟨⟨⟨_, pullback_assoc_symm_is_pullback f₁ f₂ f₃ f₄⟩⟩⟩ variables [has_pullback (g₂ ≫ f₃) f₄] [has_pullback f₁ (g₃ ≫ f₂)] /-- The canonical isomorphism `(X₁ ×[Y₁] X₂) ×[Y₂] X₃ ≅ X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/ noncomputable def pullback_assoc : pullback (pullback.snd ≫ f₃ : pullback f₁ f₂ ⟶ _) f₄ ≅ pullback f₁ (pullback.fst ≫ f₂ : pullback f₃ f₄ ⟶ _) := (pullback_pullback_left_is_pullback f₁ f₂ f₃ f₄).cone_point_unique_up_to_iso (pullback_pullback_right_is_pullback f₁ f₂ f₃ f₄) @[simp, reassoc] lemma pullback_assoc_inv_fst_fst : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst ≫ pullback.fst = pullback.fst := begin transitivity l₁' ≫ pullback.fst, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.left, exact pullback.lift_fst _ _ _, end @[simp, reassoc] lemma pullback_assoc_hom_fst : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.fst = pullback.fst ≫ pullback.fst := by rw [← iso.eq_inv_comp, pullback_assoc_inv_fst_fst] @[simp, reassoc] lemma pullback_assoc_hom_snd_fst : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin transitivity l₂ ≫ pullback.fst, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right, exact pullback.lift_fst _ _ _, end @[simp, reassoc] lemma pullback_assoc_hom_snd_snd : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.snd ≫ pullback.snd = pullback.snd := begin transitivity l₂ ≫ pullback.snd, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right, exact pullback.lift_snd _ _ _, end @[simp, reassoc] lemma pullback_assoc_inv_fst_snd : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.fst := by rw [iso.inv_comp_eq, pullback_assoc_hom_snd_fst] @[simp, reassoc] lemma pullback_assoc_inv_snd : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.snd = pullback.snd ≫ pullback.snd := by rw [iso.inv_comp_eq, pullback_assoc_hom_snd_snd] end pullback_assoc section pushout_assoc /- The objects and morphisms are as follows: Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ where the two squares are pushouts. We can then construct the pushout squares Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ l₂ ∨ ∨ X₁ - f₁ -> Y₁ - l₁ -> W and Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ X₂ Y₂ | | f₂ l₂' ∨ ∨ Y₁ - l₁' -> W' We will show that both `W` and `W'` are pushouts over `f₂, f₃`, and thus we may construct a canonical isomorphism between them. -/ variables {X₁ X₂ X₃ Z₁ Z₂ : C} (g₁ : Z₁ ⟶ X₁) (g₂ : Z₁ ⟶ X₂) (g₃ : Z₂ ⟶ X₂) variables (g₄ : Z₂ ⟶ X₃) [has_pushout g₁ g₂] [has_pushout g₃ g₄] include g₁ g₂ g₃ g₄ local notation `Y₁` := pushout g₁ g₂ local notation `Y₂` := pushout g₃ g₄ local notation `f₁` := (pushout.inl : X₁ ⟶ Y₁) local notation `f₂` := (pushout.inr : X₂ ⟶ Y₁) local notation `f₃` := (pushout.inl : X₂ ⟶ Y₂) local notation `f₄` := (pushout.inr : X₃ ⟶ Y₂) local notation `W` := pushout g₁ (g₂ ≫ f₃) local notation `W'` := pushout (g₃ ≫ f₂) g₄ local notation `l₁` := (pushout.desc pushout.inl (f₃ ≫ pushout.inr) (pushout.condition.trans (category.assoc _ _ _)) : Y₁ ⟶ W) local notation `l₂` := (pushout.inr : Y₂ ⟶ W) local notation `l₁'`:= (pushout.inl : Y₁ ⟶ W') local notation `l₂'`:= (pushout.desc (f₂ ≫ pushout.inl) pushout.inr ((category.assoc _ _ _).symm.trans pushout.condition) : Y₂ ⟶ W') /-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_pushout_left_is_pushout [has_pushout (g₃ ≫ f₂) g₄] : is_colimit (pushout_cocone.mk l₁' l₂' (show f₂ ≫ l₁' = f₃ ≫ l₂', from (pushout.inl_desc _ _ _).symm)) := begin apply pushout_cocone.flip_is_colimit, apply right_square_is_pushout, { apply pushout_cocone.flip_is_colimit, exact pushout_is_pushout _ _ }, { apply pushout_cocone.flip_is_colimit, convert pushout_is_pushout (g₃ ≫ f₂) g₄, exact pushout.inr_desc _ _ _ }, { exact pushout.condition.symm } end /-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_assoc_is_pushout [has_pushout (g₃ ≫ f₂) g₄] : is_colimit (pushout_cocone.mk (f₁ ≫ l₁') l₂' (show g₁ ≫ (f₁ ≫ l₁') = (g₂ ≫ f₃) ≫ l₂', by rw [category.assoc, pushout.inl_desc, pushout.condition_assoc])) := begin apply big_square_is_pushout, { apply pushout_pushout_left_is_pushout }, { exact pushout_is_pushout _ _ } end lemma has_pushout_assoc [has_pushout (g₃ ≫ f₂) g₄] : has_pushout g₁ (g₂ ≫ f₃) := ⟨⟨⟨_, pushout_assoc_is_pushout g₁ g₂ g₃ g₄⟩⟩⟩ /-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_pushout_right_is_pushout [has_pushout g₁ (g₂ ≫ f₃)] : is_colimit (pushout_cocone.mk l₁ l₂ (show f₂ ≫ l₁ = f₃ ≫ l₂, from pushout.inr_desc _ _ _)) := begin apply right_square_is_pushout, { exact pushout_is_pushout _ _ }, { convert pushout_is_pushout g₁ (g₂ ≫ f₃), rw pushout.inl_desc } end /-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃`. -/ def pushout_assoc_symm_is_pushout [has_pushout g₁ (g₂ ≫ f₃)] : is_colimit (pushout_cocone.mk l₁ (f₄ ≫ l₂) ((show (g₃ ≫ f₂) ≫ l₁ = g₄ ≫ (f₄ ≫ l₂), by rw [category.assoc, pushout.inr_desc, pushout.condition_assoc]))) := begin apply pushout_cocone.flip_is_colimit, apply big_square_is_pushout, { apply pushout_cocone.flip_is_colimit, apply pushout_pushout_right_is_pushout }, { apply pushout_cocone.flip_is_colimit, exact pushout_is_pushout _ _ }, { exact pushout.condition.symm }, { exact (pushout.inr_desc _ _ _).symm } end lemma has_pushout_assoc_symm [has_pushout g₁ (g₂ ≫ f₃)] : has_pushout (g₃ ≫ f₂) g₄ := ⟨⟨⟨_, pushout_assoc_symm_is_pushout g₁ g₂ g₃ g₄⟩⟩⟩ variables [has_pushout (g₃ ≫ f₂) g₄] [has_pushout g₁ (g₂ ≫ f₃)] /-- The canonical isomorphism `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃ ≅ X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/ noncomputable def pushout_assoc : pushout (g₃ ≫ pushout.inr : _ ⟶ pushout g₁ g₂) g₄ ≅ pushout g₁ (g₂ ≫ pushout.inl : _ ⟶ pushout g₃ g₄) := (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄).cocone_point_unique_up_to_iso (pushout_pushout_right_is_pushout g₁ g₂ g₃ g₄) @[simp, reassoc] lemma inl_inl_pushout_assoc_hom : pushout.inl ≫ pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inl := begin transitivity f₁ ≫ l₁, { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄) .comp_cocone_point_unique_up_to_iso_hom _ walking_cospan.left }, { exact pushout.inl_desc _ _ _ } end @[simp, reassoc] lemma inr_inl_pushout_assoc_hom : pushout.inr ≫ pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inl ≫ pushout.inr := begin transitivity f₂ ≫ l₁, { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄) .comp_cocone_point_unique_up_to_iso_hom _ walking_cospan.left }, { exact pushout.inr_desc _ _ _ } end @[simp, reassoc] lemma inr_inr_pushout_assoc_inv : pushout.inr ≫ pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inr := begin transitivity f₄ ≫ l₂', { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄).comp_cocone_point_unique_up_to_iso_inv (pushout_pushout_right_is_pushout g₁ g₂ g₃ g₄) walking_cospan.right }, { exact pushout.inr_desc _ _ _ } end @[simp, reassoc] lemma inl_pushout_assoc_inv : pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inl ≫ pushout.inl := by rw [iso.comp_inv_eq, category.assoc, inl_inl_pushout_assoc_hom] @[simp, reassoc] lemma inl_inr_pushout_assoc_inv : pushout.inl ≫ pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inr ≫ pushout.inl := by rw [← category.assoc, iso.comp_inv_eq, category.assoc, inr_inl_pushout_assoc_hom] @[simp, reassoc] lemma inr_pushout_assoc_hom : pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inr ≫ pushout.inr := by rw [← iso.eq_comp_inv, category.assoc, inr_inr_pushout_assoc_inv] end pushout_assoc variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms See https://stacks.math.columbia.edu/tag/001W -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan.{v} C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span.{v} C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ lemma has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ lemma has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } end category_theory.limits
33b1abed8d72945d541a4f70111a6e75045ae8f9
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/tactic/ring2.lean
a108fed55b1b62a7b1657f6d9ee33901d31d46c9
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
18,177
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro An experimental variant on the `ring` tactic that uses computational reflection instead of proof generation. Useful for kernel benchmarking. -/ import tactic.ring data.num.lemmas namespace tactic.ring2 @[derive has_reflect] inductive {u} tree (α : Type u) : Type u | nil {} : tree | node : α → tree → tree → tree def tree.get {α} [has_zero α] : pos_num → tree α → α | _ tree.nil := 0 | pos_num.one (tree.node a t₁ t₂) := a | (pos_num.bit0 n) (tree.node a t₁ t₂) := t₁.get n | (pos_num.bit1 n) (tree.node a t₁ t₂) := t₂.get n def tree.of_rbnode {α} : rbnode α → tree α | rbnode.leaf := tree.nil | (rbnode.red_node l a r) := tree.node a (tree.of_rbnode l) (tree.of_rbnode r) | (rbnode.black_node l a r) := tree.node a (tree.of_rbnode l) (tree.of_rbnode r) def tree.index_of {α} (lt : α → α → Prop) [decidable_rel lt] (x : α) : tree α → option pos_num | tree.nil := none | (tree.node a t₁ t₂) := match cmp_using lt x a with | ordering.lt := pos_num.bit0 <$> tree.index_of t₁ | ordering.eq := some pos_num.one | ordering.gt := pos_num.bit1 <$> tree.index_of t₂ end meta def tree.reflect' (u : level) (α : expr) : tree expr → expr | tree.nil := (expr.const ``tree.nil [u] : expr) α | (tree.node a t₁ t₂) := (expr.const ``tree.node [u] : expr) α a t₁.reflect' t₂.reflect' @[derive has_reflect] inductive csring_expr | atom : pos_num → csring_expr | const : num → csring_expr | add : csring_expr → csring_expr → csring_expr | mul : csring_expr → csring_expr → csring_expr | pow : csring_expr → num → csring_expr namespace csring_expr def eval {α} [comm_semiring α] (t : tree α) : csring_expr → α | (atom n) := @tree.get _ ⟨0⟩ n t | (const n) := n | (add x y) := eval x + eval y | (mul x y) := eval x * eval y | (pow x n) := eval x ^ (n : ℕ) end csring_expr @[derive decidable_eq] inductive horner_expr | const : znum → horner_expr | horner : horner_expr → pos_num → num → horner_expr → horner_expr namespace horner_expr def is_cs : horner_expr → Prop | (const n) := ∃ m:num, n = m.to_znum | (horner a x n b) := is_cs a ∧ is_cs b instance : has_zero horner_expr := ⟨const 0⟩ instance : has_one horner_expr := ⟨const 1⟩ def atom (n : pos_num) : horner_expr := horner 1 n 1 0 def repr : horner_expr → string | (const n) := _root_.repr n | (horner a x n b) := "(" ++ repr a ++ ") * x" ++ _root_.repr x ++ "^" ++ _root_.repr n ++ " + " ++ repr b instance : has_repr horner_expr := ⟨repr⟩ def horner' (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) : horner_expr := match a with | const q := if q = 0 then b else horner a x n b | horner a₁ x₁ n₁ b₁ := if x₁ = x ∧ b₁ = 0 then horner a₁ x (n₁ + n) b else horner a x n b end def add_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then e else begin induction e with n a x n b A B, { exact const (k + n) }, { exact horner a x n B } end def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) : horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr | (const n₂) n₁ b₁ B₁ := add_const n₂ (horner a₁ x₁ n₁ b₁) | (horner a₂ x₂ n₂ b₂) n₁ b₁ B₁ := let e₂ := horner a₂ x₂ n₂ b₂ in match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (add_aux b₂ n₁ b₁ B₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (add_aux a₂ k 0 id) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end def add : horner_expr → horner_expr → horner_expr | (const n₁) e₂ := add_const n₁ e₂ | (horner a₁ x₁ n₁ b₁) e₂ := add_aux a₁ (add a₁) x₁ e₂ n₁ b₁ (add b₁) /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact add_const n₁ e₂ }, exact match e₂ with e₂ := begin induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁; let e₁ := horner a₁ x₁ n₁ b₁, { exact add_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, exact match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end end end end-/ def neg (e : horner_expr) : horner_expr := begin induction e with n a x n b A B, { exact const (-n) }, { exact horner A x n B } end def mul_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then 0 else if k = 1 then e else begin induction e with n a x n b A B, { exact const (n * k) }, { exact horner A x n B } end def mul_aux (a₁ x₁ n₁ b₁) (A₁ B₁ : horner_expr → horner_expr) : horner_expr → horner_expr | (const n₂) := mul_const n₂ (horner a₁ x₁ n₁ b₁) | e₂@(horner a₂ x₂ n₂ b₂) := match pos_num.cmp x₁ x₂ with | ordering.lt := horner (A₁ e₂) x₁ n₁ (B₁ e₂) | ordering.gt := horner (mul_aux a₂) x₂ n₂ (mul_aux b₂) | ordering.eq := let haa := horner' (mul_aux a₂) x₁ n₂ 0 in if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) end def mul : horner_expr → horner_expr → horner_expr | (const n₁) := mul_const n₁ | e₁@(horner a₁ x₁ n₁ b₁) := mul_aux a₁ x₁ n₁ b₁ (mul a₁) (mul b₁). /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact mul_const n₁ e₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂; let e₁ := horner a₁ x₁ n₁ b₁, { exact mul_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, cases pos_num.cmp x₁ x₂, { exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) }, { let haa := horner' A₂ x₁ n₂ 0, exact if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) }, { exact horner A₂ x₂ n₂ B₂ } end-/ instance : has_add horner_expr := ⟨add⟩ instance : has_neg horner_expr := ⟨neg⟩ instance : has_mul horner_expr := ⟨mul⟩ def pow (e : horner_expr) : num → horner_expr | 0 := 1 | (num.pos p) := begin induction p with p ep p ep, { exact e }, { exact (ep.mul ep).mul e }, { exact ep.mul ep } end def inv (e : horner_expr) : horner_expr := 0 def of_csexpr : csring_expr → horner_expr | (csring_expr.atom n) := atom n | (csring_expr.const n) := const n.to_znum | (csring_expr.add x y) := (of_csexpr x).add (of_csexpr y) | (csring_expr.mul x y) := (of_csexpr x).mul (of_csexpr y) | (csring_expr.pow x n) := (of_csexpr x).pow n def cseval {α} [comm_semiring α] (t : tree α) : horner_expr → α | (const n) := n.abs | (horner a x n b) := _root_.horner (cseval a) (t.get x) n (cseval b) theorem cseval_atom {α} [comm_semiring α] (t : tree α) (n : pos_num) : (atom n).is_cs ∧ cseval t (atom n) = t.get n := ⟨⟨⟨1, rfl⟩, ⟨0, rfl⟩⟩, (tactic.ring.horner_atom _).symm⟩ theorem cseval_add_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (add_const k.to_znum e).is_cs ∧ cseval t (add_const k.to_znum e) = k + cseval t e := begin simp [add_const], cases k; simp! *, simp [show znum.pos k ≠ 0, from dec_trivial], induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, refine ⟨⟨n + num.pos k, by simp; refl⟩, _⟩, cases n; simp! }, { rcases B cs.2 with ⟨csb, h⟩, simp! [*, cs.1], rw [← tactic.ring.horner_add_const, add_comm], refl } end theorem cseval_horner' {α} [comm_semiring α] (t : tree α) (a x n b) (h₁ : is_cs a) (h₂ : is_cs b) : (horner' a x n b).is_cs ∧ cseval t (horner' a x n b) = _root_.horner (cseval t a) (t.get x) n (cseval t b) := begin cases a with n₁ a₁ x₁ n₁ b₁; simp [horner']; split_ifs, { simp! [*, _root_.horner] }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ }, { refine ⟨⟨h₁.1, h₂⟩, eq.symm _⟩, simp! *, apply tactic.ring.horner_horner, simp }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ } end theorem cseval_add {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (add e₁ e₂).is_cs ∧ cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa using cseval_add_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁, { rcases cs₂ with ⟨n₂, rfl⟩, simp! [cseval_add_const t n₂ cs₁] }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases pos_num.cmp x₁ x₂; simp!, { rcases B₁ csb₁ cs₂ with ⟨csh, h⟩, refine ⟨⟨csa₁, csh⟩, eq.symm _⟩, apply tactic.ring.horner_add_const, exact h.symm }, { cases C, have B0 : is_cs 0 → ∀ {e₂ : horner_expr}, is_cs e₂ → is_cs (add 0 e₂) ∧ cseval t (add 0 e₂) = cseval t 0 + cseval t e₂ := λ _ e₂ c, ⟨c, (zero_add _).symm⟩, cases e : num.sub' n₁ n₂ with k k; simp!, { have : n₁ = n₂, { have := congr_arg (coe : znum → ℤ) e, simp at this, have := sub_eq_zero.1 this, rw [← num.to_nat_to_int, ← num.to_nat_to_int] at this, exact num.to_nat_inj.1 (int.coe_nat_inj this) }, subst n₂, rcases cseval_horner' _ _ _ _ _ _ _ with ⟨csh, h⟩, { refine ⟨csh, h.trans (eq.symm _)⟩, simp *, apply tactic.ring.horner_add_horner_eq; try {refl}, simp }, all_goals {simp! *} }, { simp [B₁ csb₁ csb₂], rcases A₂ csa₂ _ _ B0 ⟨csa₁, 0, rfl⟩ with ⟨csh, h⟩, refine ⟨csh, eq.symm _⟩, rw [show id = add 0, from rfl, h], apply tactic.ring.horner_add_horner_gt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add'], simpa using congr_arg (coe : znum → ℤ) e }, all_goals { apply add_comm } }, { have : (horner a₂ x₁ (num.pos k) 0).is_cs := ⟨csa₂, 0, rfl⟩, simp [B₁ csb₁ csb₂, A₁ csa₁ this], symmetry, apply tactic.ring.horner_add_horner_lt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add', ← neg_inj', neg_sub], simpa using congr_arg (coe : znum → ℤ) e }, { refl }, { apply add_comm } } }, { rcases B₂ csb₂ _ _ B₁ ⟨csa₁, csb₁⟩ with ⟨csh, h⟩, refine ⟨⟨csa₂, csh⟩, eq.symm _⟩, apply tactic.ring.const_add_horner, simp [h] } end theorem cseval_mul_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (mul_const k.to_znum e).is_cs ∧ cseval t (mul_const k.to_znum e) = cseval t e * k := begin simp [mul_const], split_ifs with h h, { cases (num.to_znum_inj.1 h : k = 0), exact ⟨⟨0, rfl⟩, (mul_zero _).symm⟩ }, { cases (num.to_znum_inj.1 h : k = 1), exact ⟨cs, (mul_one _).symm⟩ }, induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, suffices, refine ⟨⟨n * k, this⟩, _⟩, swap, {cases n; cases k; refl}, rw [show _, from this], simp! }, { cases cs, simp! *, symmetry, apply tactic.ring.horner_mul_const; refl } end theorem cseval_mul {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (mul e₁ e₂).is_cs ∧ cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa [mul_comm] using cseval_mul_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂, { rcases cs₂ with ⟨n₂, rfl⟩, simpa! using cseval_mul_const t n₂ cs₁ }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases A₂ csa₂ with csA₂ hA₂, cases pos_num.cmp x₁ x₂; simp!, { simp [A₁ csa₁ cs₂, B₁ csb₁ cs₂], symmetry, apply tactic.ring.horner_mul_const; refl }, { cases cseval_horner' t _ x₁ n₂ 0 csA₂ ⟨0, rfl⟩ with csh₁ h₁, cases C, split_ifs, { subst b₂, refine ⟨csh₁, h₁.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner_zero; try {refl}, simp! [hA₂] }, { cases A₁ csa₁ csb₂ with csA₁ hA₁, cases cseval_add t csh₁ _ with csh₂ h₂, { refine ⟨csh₂, h₂.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner; try {refl}, simp! * }, exact ⟨csA₁, (B₁ csb₁ csb₂).1⟩ } }, { simp [A₂ csa₂, B₂ csb₂], rw [mul_comm, eq_comm], apply tactic.ring.horner_const_mul, {apply mul_comm}, {refl} }, end theorem cseval_pow {α} [comm_semiring α] (t : tree α) {x : horner_expr} (cs : x.is_cs) : ∀ (n : num), (pow x n).is_cs ∧ cseval t (pow x n) = cseval t x ^ (n : ℕ) | 0 := ⟨⟨1, rfl⟩, (pow_zero _).symm⟩ | (num.pos p) := begin simp [pow], induction p with p ep p ep, { simp * }, { simp [pow_bit1], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, cases cseval_mul t cs₀ cs with cs₁ h₁, simp * }, { simp [pow_bit0], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, simp * } end theorem cseval_of_csexpr {α} [comm_semiring α] (t : tree α) : ∀ (r : csring_expr), (of_csexpr r).is_cs ∧ cseval t (of_csexpr r) = r.eval t | (csring_expr.atom n) := cseval_atom _ _ | (csring_expr.const n) := ⟨⟨n, rfl⟩, by cases n; refl⟩ | (csring_expr.add x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_add t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.mul x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_mul t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.pow x n) := let ⟨cs, h⟩ := cseval_of_csexpr x, ⟨cs, h⟩ := cseval_pow t cs n in ⟨cs, by simp! [h, *]⟩ end horner_expr theorem correctness {α} [comm_semiring α] (t : tree α) (r₁ r₂ : csring_expr) (H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) : r₁.eval t = r₂.eval t := by repeat {rw ← (horner_expr.cseval_of_csexpr t _).2}; rw H meta def reflect_expr : expr → csring_expr × dlist expr | `(%%e₁ + %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂, l₁ ++ l₂) /-| `(%%e₁ - %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂.neg, l₁ ++ l₂) | `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/ | `(%%e₁ * %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂, l₁ ++ l₂) /-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l) | `(%%e₁ / %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂.inv, l₁ ++ l₂)-/ | e@`(%%e₁ ^ %%e₂) := match reflect_expr e₁, expr.to_nat e₂ with | (r₁, l₁), some n₂ := (r₁.pow (num.of_nat' n₂), l₁) | (r₁, l₁), none := (csring_expr.atom 1, dlist.singleton e) end | e := match expr.to_nat e with | some n := (csring_expr.const (num.of_nat' n), dlist.empty) | none := (csring_expr.atom 1, dlist.singleton e) end meta def csring_expr.replace (t : tree expr) : csring_expr → state_t (list expr) option csring_expr | (csring_expr.atom _) := do e ← get, p ← monad_lift (t.index_of (<) e.head), put e.tail, pure (csring_expr.atom p) | (csring_expr.const n) := pure (csring_expr.const n) | (csring_expr.add x y) := csring_expr.add <$> x.replace <*> y.replace | (csring_expr.mul x y) := csring_expr.mul <$> x.replace <*> y.replace | (csring_expr.pow x n) := (λ x, csring_expr.pow x n) <$> x.replace --| (csring_expr.neg x) := csring_expr.neg <$> x.replace --| (csring_expr.inv x) := csring_expr.inv <$> x.replace end tactic.ring2 namespace tactic namespace interactive open interactive interactive.types lean.parser open tactic.ring2 local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of rings. This variant on the `ring` tactic uses kernel computation instead of proof generation. -/ meta def ring2 : tactic unit := do `[repeat {rw ← nat.pow_eq_pow}], `(%%e₁ = %%e₂) ← target, α ← infer_type e₁, expr.sort (level.succ u) ← infer_type α, let (r₁, l₁) := reflect_expr e₁, let (r₂, l₂) := reflect_expr e₂, let L := (l₁ ++ l₂).to_list, let s := tree.of_rbnode (rbtree_of L).1, (r₁, L) ← (state_t.run (r₁.replace s) L : option _), (r₂, _) ← (state_t.run (r₂.replace s) L : option _), let se : expr := s.reflect' u α, let er₁ : expr := reflect r₁, let er₂ : expr := reflect r₂, cs ← mk_app ``comm_semiring [α] >>= mk_instance, e ← to_expr ```(correctness %%se %%er₁ %%er₂ rfl) <|> fail ("ring2 tactic failed, using abstract equality:\n" ++ repr (horner_expr.of_csexpr r₁) ++ "\n =?=\n" ++ repr (horner_expr.of_csexpr r₂)), tactic.exact e end interactive end tactic
0ab734012ab64d1f710b8c6b257972e074642ca7
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_15_16.lean
562057b8bfe624c70d62f632910eeb20a5d3084b
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
764
lean
namespace fol_15_16 -- Show that reflexivity is sufficient to derive the rules for symmetry and transitivity. theorem foo {A : Type} {a b c : A} : a = b → c = b → a = c := assume h1: a = b, assume h2: c = b, show a = c, from calc a = b : by rw h1 ... = c : by rw ← h2 section variable A : Type variables a b c : A example (h1 : a = b) (h2 : c = b) : a = c := foo h1 h2 end section variable {A : Type} variables {a b c : A} -- Proof using foo and rfl, without using eq.symm. theorem fol_15 (h : b = a) : a = b := show a = b, by rw h -- Using foo and fol_15 to prove transitivity. theorem fol_16 (h1 : a = b) (h2 : b = c) : a = c := show a = c, from calc a = b : by rw h1 ... = c : by rw h2 end end fol_15_16
2a279554dd1eff689fb604d17a434c6e44211331
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/char_zero.lean
86887715e33d78e44b92d1b1a4afeb20bec3ddcb
[ "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
7,267
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.cast import data.fintype.basic import tactic.wlog /-! # Characteristic zero A ring `R` is called of characteristic zero if every natural number `n` is non-zero when considered as an element of `R`. Since this definition doesn't mention the multiplicative structure of `R` except for the existence of `1` in this file characteristic zero is defined for additive monoids with `1`. ## Main definition `char_zero` is the typeclass of an additive monoid with one such that the natural homomorphism from the natural numbers into it is injective. ## Main statements * A linearly ordered semiring has characteristic zero. * Characteristic zero implies that the additive monoid is infinite. ## TODO * Once order of a group is defined for infinite additive monoids redefine or at least connect to order of `1` in the additive monoid with one. * Unify with `char_p` (possibly using an out-parameter) -/ /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) *Warning*: for a semiring `R`, `char_zero R` and `char_p R 0` need not coincide. * `char_zero R` requires an injection `ℕ ↪ R`; * `char_p R 0` asks that only `0 : ℕ` maps to `0 : R` under the map `ℕ → R`. For instance, endowing `{0, 1}` with addition given by `max` (i.e. `1` is absorbing), shows that `char_zero {0, 1}` does not hold and yet `char_p {0, 1} 0` does. This example is formalized in `counterexamples/char_p_zero_ne_char_zero`. -/ class char_zero (R : Type*) [add_monoid R] [has_one R] : Prop := (cast_injective : function.injective (coe : ℕ → R)) theorem char_zero_of_inj_zero {R : Type*} [add_left_cancel_monoid R] [has_one R] (H : ∀ n:ℕ, (n:R) = 0 → n = 0) : char_zero R := ⟨λ m n, begin assume h, wlog hle : m ≤ n, rcases nat.le.dest hle with ⟨k, rfl⟩, rw [nat.cast_add, eq_comm, add_right_eq_self] at h, rw [H k h, add_zero] end⟩ /-- Note this is not an instance as `char_zero` implies `nontrivial`, and this would risk forming a loop. -/ lemma ordered_semiring.to_char_zero {R : Type*} [ordered_semiring R] [nontrivial R] : char_zero R := ⟨nat.strict_mono_cast.injective⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {R : Type*} [linear_ordered_semiring R] : char_zero R := ordered_semiring.to_char_zero namespace nat variables {R : Type*} [add_monoid R] [has_one R] [char_zero R] theorem cast_injective : function.injective (coe : ℕ → R) := char_zero.cast_injective /-- `nat.cast` as an embedding into monoids of characteristic `0`. -/ @[simps] def cast_embedding : ℕ ↪ R := ⟨coe, cast_injective⟩ @[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : R) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : R) = 0 ↔ n = 0 := by rw [←cast_zero, cast_inj] @[simp, norm_cast] theorem cast_eq_one {n : ℕ} : (n : R) = 1 ↔ n = 1 := by rw [←cast_one, cast_inj] @[simp] lemma cast_pow_eq_one {R : Type*} [semiring R] [char_zero R] (q : ℕ) (n : ℕ) (hn : n ≠ 0) : (q : R) ^ n = 1 ↔ q = 1 := by { rw [←cast_pow, cast_eq_one], exact pow_eq_one_iff hn } @[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : R) ≠ 0 ↔ n ≠ 0 := cast_eq_zero.not @[norm_cast] theorem cast_ne_one {n : ℕ} : (n : R) ≠ 1 ↔ n ≠ 1 := cast_eq_one.not lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : R) ≠ 0 := by exact_mod_cast n.succ_ne_zero @[simp, norm_cast] theorem cast_div_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ} (n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, { exact cast_div n_dvd (cast_ne_zero.2 hn), }, end end nat section variables (M : Type*) [add_monoid M] [has_one M] [char_zero M] @[priority 100] -- see Note [lower instance priority] instance char_zero.infinite : infinite M := infinite.of_injective coe nat.cast_injective variable {M} @[field_simps] lemma two_ne_zero' : (2:M) ≠ 0 := have ((2:ℕ):M) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_two] at this end section variables {R : Type*} [non_assoc_semiring R] [no_zero_divisors R] [char_zero R] @[simp] lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] @[simp] lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero @[simp] lemma zero_eq_bit0 {a : R} : 0 = bit0 a ↔ a = 0 := by { rw [eq_comm], exact bit0_eq_zero } end section variables {R : Type*} [non_assoc_ring R] [no_zero_divisors R] [char_zero R] lemma neg_eq_self_iff {a : R} : -a = a ↔ a = 0 := neg_eq_iff_add_eq_zero.trans add_self_eq_zero lemma eq_neg_self_iff {a : R} : a = -a ↔ a = 0 := eq_neg_iff_add_eq_zero.trans add_self_eq_zero lemma nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b := begin rw [←sub_eq_zero, ←mul_sub, mul_eq_zero, sub_eq_zero] at h, exact_mod_cast h, end lemma nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b := by simpa [w] using nat_mul_inj h lemma bit0_injective : function.injective (bit0 : R → R) := λ a b h, begin dsimp [bit0] at h, simp only [(two_mul a).symm, (two_mul b).symm] at h, refine nat_mul_inj' _ two_ne_zero, exact_mod_cast h, end lemma bit1_injective : function.injective (bit1 : R → R) := λ a b h, begin simp only [bit1, add_left_inj] at h, exact bit0_injective h, end @[simp] lemma bit0_eq_bit0 {a b : R} : bit0 a = bit0 b ↔ a = b := bit0_injective.eq_iff @[simp] lemma bit1_eq_bit1 {a b : R} : bit1 a = bit1 b ↔ a = b := bit1_injective.eq_iff @[simp] lemma bit1_eq_one {a : R} : bit1 a = 1 ↔ a = 0 := by rw [show (1 : R) = bit1 0, by simp, bit1_eq_bit1] @[simp] lemma one_eq_bit1 {a : R} : 1 = bit1 a ↔ a = 0 := by { rw [eq_comm], exact bit1_eq_one } end section variables {R : Type*} [division_ring R] [char_zero R] @[simp] lemma half_add_self (a : R) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : R) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : R) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end namespace with_top instance {R : Type*} [add_monoid R] [has_one R] [char_zero R] : char_zero (with_top R) := { cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h } end with_top section ring_hom variables {R S : Type*} [non_assoc_semiring R] [non_assoc_semiring S] lemma ring_hom.char_zero (ϕ : R →+* S) [hS : char_zero S] : char_zero R := ⟨λ a b h, char_zero.cast_injective (by rw [←map_nat_cast ϕ, ←map_nat_cast ϕ, h])⟩ lemma ring_hom.char_zero_iff {ϕ : R →+* S} (hϕ : function.injective ϕ) : char_zero R ↔ char_zero S := ⟨λ hR, ⟨λ a b h, by rwa [←@nat.cast_inj R _ _ hR, ←hϕ.eq_iff, map_nat_cast ϕ, map_nat_cast ϕ]⟩, λ hS, by exactI ϕ.char_zero⟩ end ring_hom
9ddcd418fa1f42f0797b5ef666eadb85f8ad47dc
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/graphs/category.lean
7e27f7106ca578b53b2f99e5dd930c99c4a927c3
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,237
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan and Scott Morrison import category_theory.category import category_theory.graphs namespace category_theory open category_theory.graphs universes u v variable {C : Type u} instance category.graph [𝒞 : category.{v} C] : graph C := { edges := 𝒞.hom } variable [small_category C] inductive morphism_path : C → C → Type (u+1) | nil : Π (h : C), morphism_path h h | cons : Π {h s t : C} (e : h ⟶ s) (l : morphism_path s t), morphism_path h t notation a :: b := morphism_path.cons a b notation `c[` l:(foldr `, ` (h t, morphism_path.cons h t) morphism_path.nil _ `]`) := l def concatenate_paths : Π {x y z : C}, morphism_path x y → morphism_path y z → morphism_path x z | ._ ._ _ (morphism_path.nil _) q := q | ._ ._ _ (@morphism_path.cons ._ _ _ _ _ e p') q := morphism_path.cons e (concatenate_paths p' q) def category.compose_path : Π {X Y : C}, morphism_path X Y → (X ⟶ Y) | X ._ (morphism_path.nil ._) := 𝟙 X | _ _ (@morphism_path.cons ._ ._ _ _ ._ e p) := e ≫ (category.compose_path p) end category_theory
8b10b9ffc2b85eb4ed8d1fb9f807e147339ef75c
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Binders.lean
1c6494f68badd79ba26ca458f531af58dc1f90c4
[ "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
27,751
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.Elab.Quotation.Precheck import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole ref else stx[1] /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match stx with | `(_) => mkFreshIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do if stx.isNone then let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst return mkIdentFrom stx id else return stx[0] structure BinderView where id : Syntax type : Syntax bi : BinderInfo partial def quoteAutoTactic : Syntax → TermElabM Syntax | stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalid auto tactic, identifier is not allowed" | stx@(Syntax.node _ k args) => do if stx.isAntiquot then throwErrorAt stx "invalid auto tactic, antiquotation is not allowed" else let mut quotedArgs ← `(Array.empty) for arg in args do if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then throwErrorAt arg "invalid auto tactic, antiquotation is not allowed" else let quotedArg ← quoteAutoTactic arg quotedArgs ← `(Array.push $quotedArgs $quotedArg) `(Syntax.node SourceInfo.none $(quote k) $quotedArgs) | Syntax.atom info val => `(mkAtom $(quote val)) | Syntax.missing => throwError "invalid auto tactic, tactic is missing" def declareTacticSyntax (tactic : Syntax) : TermElabM Name := withFreshMacroScope do let name ← MonadQuotation.addMacroScope `_auto let type := Lean.mkConst `Lean.Syntax let tactic ← quoteAutoTactic tactic let val ← elabTerm tactic type let val ← instantiateMVars val trace[Elab.autoParam] val let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } addDecl decl compileDecl decl return name /- Expand `optional (binderTactic <|> binderDefault)` def binderTactic := leading_parser " := " >> " by " >> tacticParser def binderDefault := leading_parser " := " >> termParser -/ private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do if optBinderModifier.isNone then return type else let modifier := optBinderModifier[0] let kind := modifier.getKind if kind == `Lean.Parser.Term.binderDefault then let defaultVal := modifier[1] `(optParam $type $defaultVal) else if kind == `Lean.Parser.Term.binderTactic then let tac := modifier[2] let name ← declareTacticSyntax tac `(autoParam $type $(mkIdentFrom tac name)) else throwUnsupportedSyntax private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) := ids.getArgs.mapM fun id => let k := id.getKind if k == identKind || k == `Lean.Parser.Term.hole then return id else throwErrorAt id "identifier or `_` expected" private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := do let k := stx.getKind if k == ``Lean.Parser.Term.simpleBinder then -- binderIdent+ >> optType let ids ← getBinderIds stx[0] let optType := stx[1] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := expandOptType id optType, bi := BinderInfo.default } else if k == ``Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids ← getBinderIds stx[1] let type := stx[2] let optModifier := stx[3] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := (← expandBinderModifier (expandBinderType id type) optModifier), bi := BinderInfo.default } else if k == ``Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids ← getBinderIds stx[1] let type := stx[2] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := expandBinderType id type, bi := BinderInfo.implicit } else if k == ``Lean.Parser.Term.strictImplicitBinder then -- `⦃` binderIdent+ binderType `⦄` let ids ← getBinderIds stx[1] let type := stx[2] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := expandBinderType id type, bi := BinderInfo.strictImplicit } else if k == ``Lean.Parser.Term.instBinder then -- `[` optIdent type `]` let id ← expandOptIdent stx[1] let type := stx[2] pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ] else throwUnsupportedSyntax private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer binder type" private def addLocalVarInfo (stx : Syntax) (fvar : Expr) : TermElabM Unit := do addTermInfo (isBinder := true) stx fvar private def ensureAtomicBinderName (binderView : BinderView) : TermElabM Unit := let n := binderView.id.getId.eraseMacroScopes unless n.isAtomic do throwErrorAt binderView.id "invalid binder name '{n}', it must be atomic" register_builtin_option checkBinderAnnotations : Bool := { defValue := true descr := "check whether type is a class instance whenever the binder annotation `[...]` is used" } private partial def elabBinderViews {α} (binderViews : Array BinderView) (fvars : Array (Syntax × Expr)) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array (Syntax × Expr)) : TermElabM α := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type if binderView.bi.isInstImplicit && checkBinderAnnotations.get (← getOptions) then unless (← isClass? type).isSome do throwErrorAt binderView.type "invalid binder annotation, type is not a class instance{indentExpr type}\nuse the command `set_option checkBinderAnnotations false` to disable the check" withLocalDecl binderView.id.getId binderView.bi type fun fvar => do addLocalVarInfo binderView.id fvar loop (i+1) (fvars.push (binderView.id, fvar)) else k fvars loop 0 fvars private partial def elabBindersAux {α} (binders : Array Syntax) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array (Syntax × Expr)) : TermElabM α := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) elabBinderViews binderViews fvars <| loop (i+1) else k fvars loop 0 #[] /-- Like `elabBinders`, but also pass syntax node per binder. `elabBinders(Ex)` automatically adds binder info nodes for the produced fvars, but storing the syntax nodes might be necessary when later adding the same binders back to the local context so that info nodes can manually be added for the new fvars; see `MutualDef` for an example. -/ def elabBindersEx {α} (binders : Array Syntax) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := withoutPostponingUniverseConstraints do if binders.isEmpty then k #[] else elabBindersAux binders k /-- Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `x` with the updated context. -/ def elabBinders (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := elabBindersEx binders (fun fvars => k (fvars.map (·.2))) def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α := elabBinders #[binder] fun fvars => x fvars[0] @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match stx with | `(forall $binders*, $term) => elabBinders binders fun xs => do let e ← elabType term mkForallFVars xs e | _ => throwUnsupportedSyntax @[builtinTermElab arrow] def elabArrow : TermElab := fun stx _ => match stx with | `($dom:term -> $rng) => do -- elaborate independently from each other let dom ← elabType dom let rng ← elabType rng mkForall (← MonadQuotation.addMacroScope `a) BinderInfo.default dom rng | _ => throwUnsupportedSyntax /-- The dependent arrow. `(x : α) → β` is equivalent to `∀ x : α, β`, but we usually reserve the latter for propositions. Also written as `Π x : α, β` (the "Pi-type") in the literature. -/ @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracketedBinder `->` term let binder := stx[0] let term := stx[2] elabBinders #[binder] fun xs => do mkForallFVars xs (← elabType term) /-- Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private partial def getFunBinderIds? (stx : Syntax) : OptionT MacroM (Array Syntax) := let convertElem (stx : Syntax) : OptionT MacroM Syntax := match stx with | `(_) => do let ident ← mkFreshIdent stx; pure ident | `($id:ident) => return id | _ => failure match stx with | `($f $args*) => do let mut acc := #[].push (← convertElem f) for arg in args do acc := acc.push (← convertElem arg) return acc | _ => return #[].push (← convertElem stx) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec leading_parser unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/ partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : MacroM (Array Syntax × Syntax × Bool) := let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do if h : i < binders.size then let binder := binders.get ⟨i, h⟩ let processAsPattern : Unit → MacroM (Array Syntax × Syntax × Bool) := fun _ => do let pattern := binder let major ← mkFreshIdent binder let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder)) let newBody ← `(match $major:ident with | $pattern => $newBody) pure (binders, newBody, true) match binder with | Syntax.node _ ``Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node _ ``Lean.Parser.Term.strictImplicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node _ ``Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node _ ``Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node _ ``Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node _ ``Lean.Parser.Term.hole _ => let ident ← mkFreshIdent binder let type := binder loop body (i+1) (newBinders.push <| mkExplicitBinder ident type) | Syntax.node _ ``Lean.Parser.Term.paren args => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder[1] if binderBody.isNone then processAsPattern () else let idents := binderBody[0] let special := binderBody[1] if special.isNone then processAsPattern () else if special[0].getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else -- typeAscription := `:` term let type := special[0][1] match (← getFunBinderIds? idents) with | some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | Syntax.ident .. => let type := mkHole binder loop body (i+1) (newBinders.push <| mkExplicitBinder binder type) | _ => processAsPattern () else pure (newBinders, body, false) loop body 0 #[] namespace FunBinders structure State where fvars : Array Expr := #[] lctx : LocalContext localInsts : LocalInstances expectedType? : Option Expr := none private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do match s.expectedType? with | none => pure s | some expectedType => let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ d b _ => discard <| isDefEq fvarType d let b := b.instantiate1 fvar pure { s with expectedType? := some b } | _ => pure { s with expectedType? := none } private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView withRef binderView.type <| withLCtx s.lctx s.localInsts do let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId let s := { s with fvars := s.fvars.push fvar } -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type) /- We do **not** want to support default and auto arguments in lambda abstractions. Example: `fun (x : Nat := 10) => x+1`. We do not believe this is an useful feature, and it would complicate the logic here. -/ let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi addTermInfo (lctx? := some lctx) (isBinder := true) binderView.id fvar let s ← withRef binderView.id <| propagateExpectedType fvar type s let s := { s with lctx := lctx } match (← isClass? type) with | none => elabFunBinderViews binderViews (i+1) s | some className => resettingSynthInstanceCache do let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId } elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts } else pure s partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) let s ← elabFunBinderViews binderViews 0 s elabFunBindersAux binders (i+1) s else pure s end FunBinders def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] expectedType? else do let lctx ← getLCtx let localInsts ← getLocalInstances let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? } resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) <| withLCtx s.lctx s.localInsts <| x s.fvars s.expectedType? /- Helper function for `expandEqnsIntoMatch` -/ private def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat := let alt0 := matchAlts[0][0] let pats := alt0[1].getSepArgs pats.size def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax := match whereDecls with | `(whereDecls|where $[$decls:letRecDecl $[;]?]*) => `(let rec $decls:letRecDecl,*; $body) | _ => Macro.throwUnsupported def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax := if whereDeclsOpt.isNone then body else expandWhereDecls whereDeclsOpt[0] body /- Helper function for `expandMatchAltsIntoMatch` -/ private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax | 0, discrs => do if matchTactic then `(tactic|match $[$discrs:term],* with $matchAlts:matchAlts) else `(match $[$discrs:term],* with $matchAlts:matchAlts) | n+1, discrs => withFreshMacroScope do let x ← `(x) let d ← `(@$x:ident) -- See comment below let body ← expandMatchAltsIntoMatchAux matchAlts matchTactic n (discrs.push d) if matchTactic then `(tactic| intro $x:term; $body:tactic) else `(@fun $x => $body) /-- Expand `matchAlts` syntax into a full `match`-expression. Example ``` | 0, true => alt_1 | i, _ => alt_2 ``` expands into (for tactic == false) ``` fun x_1 x_2 => match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` and (for tactic == true) ``` intro x_1; intro x_2; match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` Remark: we add `@` to make sure we don't consume implicit arguments, and to make the behavior consistent with `fun`. Example: ``` inductive T : Type 1 := | mkT : (forall {a : Type}, a -> a) -> T def makeT (f : forall {a : Type}, a -> a) : T := mkT f def makeT' : (forall {a : Type}, a -> a) -> T | f => mkT f ``` The two definitions should be elaborated without errors and be equivalent. -/ def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts tactic (getMatchAltsNumPatterns matchAlts) #[] def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts true (getMatchAltsNumPatterns matchAlts) #[] /-- Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause. Expand `matchAltsWhereDecls` into `let rec` + `match`-expression. Example ``` | 0, true => ... f 0 ... | i, _ => ... f i + g i ... where f x := g x + 1 g : Nat → Nat | 0 => 1 | x+1 => f x ``` expands into ``` fux x_1 x_2 => let rec f x := g x + 1, g : Nat → Nat | 0 => 1 | x+1 => f x match x_1, x_2 with | 0, true => ... f 0 ... | i, _ => ... f i + g i ... ``` -/ def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax := let matchAlts := matchAltsWhereDecls[0] let whereDeclsOpt := matchAltsWhereDecls[1] let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax := match i with | 0 => do let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts) if whereDeclsOpt.isNone then return matchStx else expandWhereDeclsOpt whereDeclsOpt matchStx | n+1 => withFreshMacroScope do let d ← `(@x) -- See comment at `expandMatchAltsIntoMatch` let body ← loop n (discrs.push d) `(@fun x => $body) loop (getMatchAltsNumPatterns matchAlts) #[] @[builtinMacro Lean.Parser.Term.fun] partial def expandFun : Macro | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← expandFunBinders binders body if expandedPattern then `(fun $binders* => $body) else Macro.throwUnsupported | stx@`(fun $m:matchAlts) => expandMatchAltsIntoMatch stx m | _ => Macro.throwUnsupported open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.fun] def precheckFun : Precheck | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body let mut ids := #[] for b in binders do for v in ← matchBinder b do Quotation.withNewLocals ids <| precheck v.type ids := ids.push v.id.getId Quotation.withNewLocals ids <| precheck body | _ => throwUnsupportedSyntax @[builtinTermElab «fun»] partial def elabFun : TermElab := fun stx expectedType? => match stx with | `(fun $binders* => $body) => do -- We can assume all `match` binders have been iteratively expanded by the above macro here, though -- we still need to call `expandFunBinders` once to obtain `binders` in a normal form -- expected by `elabFunBinder`. let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body elabFunBinders binders expectedType? fun xs expectedType? => do /- We ensure the expectedType here since it will force coercions to be applied if needed. If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`, and another instance for the dependent version. -/ let e ← elabTermEnsuringType body expectedType? mkLambdaFVars xs e | _ => throwUnsupportedSyntax /- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created. Otherwise, we create a term of the form `(fun (x : type) => body) val` The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`. If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/ def elabLetDeclAux (id : Syntax) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) (usedLetOnly : Bool) : TermElabM Expr := do let (type, val, arity) ← elabBinders binders fun xs => do let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type" if elabBodyFirst then let type ← mkForallFVars xs type let val ← mkFreshExprMVar type pure (type, val, xs.size) else let val ← elabTermEnsuringType valStx type let type ← mkForallFVars xs type /- By default `mkLambdaFVars` and `mkLetFVars` create binders only for let-declarations that are actually used in the body. This generates counterintuitive behavior in the elaborator since users will not be notified about holes such as ``` def ex : Nat := let x := _ 42 ``` -/ let val ← mkLambdaFVars xs val (usedLetOnly := false) pure (type, val, xs.size) trace[Elab.let.decl] "{id.getId} : {type} := {val}" let result ← if useLetExpr then withLetDecl id.getId type val fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLetFVars #[x] body (usedLetOnly := usedLetOnly) else let f ← withLocalDecl id.getId BinderInfo.default type fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLambdaFVars #[x] body (usedLetOnly := false) pure <| mkLetFunAnnotation (mkApp f val) if elabBodyFirst then forallBoundedTelescope type arity fun xs type => do let valResult ← elabTermEnsuringType valStx type let valResult ← mkLambdaFVars xs valResult (usedLetOnly := false) unless (← isDefEq val valResult) do throwError "unexpected error when elaborating 'let'" pure result structure LetIdDeclView where id : Syntax binders : Array Syntax type : Syntax value : Syntax def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView := -- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser let id := letIdDecl[0] let binders := letIdDecl[1].getArgs let optType := letIdDecl[2] let type := expandOptType id optType let value := letIdDecl[4] { id := id, binders := binders, type := type, value := value } def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do let ref := letDecl let matchAlts := letDecl[3] let val ← expandMatchAltsIntoMatch ref matchAlts return mkNode `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val] def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) (usedLetOnly : Bool) : TermElabM Expr := do let ref := stx let letDecl := stx[1][0] let body := stx[3] if letDecl.getKind == `Lean.Parser.Term.letIdDecl then let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst usedLetOnly else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then -- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser let pat := letDecl[0] let optType := letDecl[2] let type := expandOptType pat optType let val := letDecl[4] let stxNew ← `(let x : $type := $val; match x with | $pat => $body) let stxNew := match useLetExpr, elabBodyFirst with | true, false => stxNew | true, true => stxNew.setKind `Lean.Parser.Term.«let_delayed» | false, false => stxNew.setKind `Lean.Parser.Term.«let_fun» | false, true => unreachable! withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then let letDeclIdNew ← liftMacroM <| expandLetEqnsDecl letDecl let declNew := stx[1].setArg 0 letDeclIdNew let stxNew := stx.setArg 1 declNew withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else throwUnsupportedSyntax @[builtinTermElab «let»] def elabLetDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := false) (usedLetOnly := false) @[builtinTermElab «let_fun»] def elabLetFunDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := false) (elabBodyFirst := false) (usedLetOnly := false) @[builtinTermElab «let_delayed»] def elabLetDelayedDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := true) (usedLetOnly := false) @[builtinTermElab «let_tmp»] def elabLetTmpDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := false) (usedLetOnly := true) builtin_initialize registerTraceClass `Elab.let end Lean.Elab.Term
23c98e0667679e7a25dafeedc0aa6dd48c64f614
5584bde9c451ee99730cbf3a8b06e49672e133fe
/src/whatIsALanguage.lean
7604b9c5ff761bd2250eff8012ce508069408ed5
[]
no_license
Victor-Pham/complogic-s21
400ed583a3644945761bfc16b8cdcbb9bc81c624
2de995c20209ad36f25a69b78f1b20394a5473d4
refs/heads/master
1,677,319,385,825
1,612,464,253,000
1,612,464,253,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,418
lean
inductive Syntax : Type | I | II | III | IV | V inductive Semantics : Type | one | two | three | four | five #reduce one -- Defined in Semantics namespace #reduce Semantics.one -- Access definition in namespace open Semantics -- Open namespaces open Syntax #reduce one -- Now defined in current namespace /- Here's an informal definition of our desired semantics. I --> one II --> two III --> three IV --> four V --> five -/ -- We can formalize semantics as a function /- A little bit of Lean -/ -- Literal expressions -- Variable expressions -- Application expressions #reduce 1 -- literal def x := 1 -- variable #reduce x def my_id : nat → nat := (λ n, n) -- lambda expression, literal -- Ident Type Value -- type inference in use #reduce (my_id 1) #reduce (my_id 4) -- #reduce (my_id "Hello, Lean!") def my_id' : ℕ → ℕ -- by cases | n := n def my_id'' (n : nat) : nat := -- C style syntax n #reduce my_id #reduce my_id'' -- End of "A little bit of Lean" -- Another aside def my_add (n m : ℕ) := nat.add n m -- n + m #reduce my_add 2 3 def my_add' : ℕ → (ℕ → ℕ) := λ n, λ m, n + m def k := my_add' 5 #reduce k 6 /- Our semantics! -/ def my_eval : Syntax → Semantics | I := one | II := two | III := three | IV := four | V := five #reduce my_eval II
bcaf040541c64294494aa8bf6f6ff38e18c152da
df561f413cfe0a88b1056655515399c546ff32a5
/3-function-world/l9.lean
4ae4402e9eb67a0ae66924b8af6d583d222a2d46
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
350
lean
example (A B C D E F G H I J K L : Type) (f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F) (f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J) (f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L) : A → L := begin intro a, exact f15 (f11 (f9 (f8 (f5 (f2 (f1 a)))))), end
6808bb9f44af8cb12ad2673d5fdf750ea523320d
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/destruct.lean
7360c9cadf76db99b924431dde7485fb27cea743
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
946
lean
universe variables u inductive Vec (α : Type u) : nat → Type (max 1 u) | nil : Vec 0 | cons : ∀ {n}, α → Vec n → Vec (nat.succ n) lemma split {α : Type u} {n : nat} (v : Vec α n) : (v == (Vec.nil α) ∧ n = 0) ∨ ∃ m h (t : Vec α m), v == Vec.cons h t ∧ n = nat.succ m := Vec.cases_on v (or.inl ⟨heq.refl _, rfl⟩) (λ n h t, or.inr ⟨n, h, t, heq.refl _, rfl⟩) constant f {α : Type u} {n : nat} : Vec α n → nat axiom fax1 (α : Type u) : f (Vec.nil α) = 0 axiom fax2 {α : Type u} {n : nat} (v : Vec α (nat.succ n)) : f v = 1 example {α : Type u} {n : nat} (v : Vec α n) : f v ≠ 2 := begin destruct v, {intros, intro, have h := fax1 α, cc}, intros n1 h t, intros, intro, have h := fax2 (Vec.cons h t), cc end open nat example : ∀ n, 0 < n → succ (pred n) = n := begin intro n, destruct n, {dsimp, intros, have h := lt_irrefl 0, cc}, {intros, subst n, dsimp, reflexivity} end
2b732ca10281581e0a38bb3144d2a6daac66daa4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/number_theory/quadratic_reciprocity.lean
840064de3ad8db77d99c438c9b96b94231796436
[ "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
25,770
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 := (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 only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {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) := begin 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 only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {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)), { apply 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 only [*, lt_succ_iff, Ico.mem, mem_product] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), 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, simpa only [this, le_zero_iff_eq, Ico.mem, one_ne_zero, false_and, mem_product] using hx }, 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 only [mem_union, mem_filter, Ico.mem, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [Ico.card, nat.sub_zero, succ_sub_succ_eq_sub] end 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
7deb3e6db12a84885be39b10b4b79f7b14c1f31c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/functorial.lean
8d1c1b625c0573daad8b0085022cb4a4eb6fa220
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,544
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.functor /-! # Unbundled functors, as a typeclass decorating the object-level function. -/ namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A unbundled functor. -/ -- Perhaps in the future we could redefine `functor` in terms of this, but that isn't the -- immediate plan. class functorial (F : C → D) : Type (max v₁ v₂ u₁ u₂) := (map : Π {X Y : C}, (X ⟶ Y) → ((F X) ⟶ (F Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (F X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) /-- If `F : C → D` (just a function) has `[functorial F]`, we can write `map F f : F X ⟶ F Y` for the action of `F` on a morphism `f : X ⟶ Y`. -/ def map (F : C → D) [functorial.{v₁ v₂} F] {X Y : C} (f : X ⟶ Y) : F X ⟶ F Y := functorial.map.{v₁ v₂} f @[simp] lemma map_as_map {F : C → D} [functorial.{v₁ v₂} F] {X Y : C} {f : X ⟶ Y} : functorial.map.{v₁ v₂} f = map F f := rfl @[simp] lemma functorial.map_id {F : C → D} [functorial.{v₁ v₂} F] {X : C} : map F (𝟙 X) = 𝟙 (F X) := functorial.map_id' X @[simp] lemma functorial.map_comp {F : C → D} [functorial.{v₁ v₂} F] {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : map F (f ≫ g) = map F f ≫ map F g := functorial.map_comp' f g namespace functor /-- Bundle a functorial function as a functor. -/ def of (F : C → D) [I : functorial.{v₁ v₂} F] : C ⥤ D := { obj := F, ..I } end functor instance (F : C ⥤ D) : functorial.{v₁ v₂} (F.obj) := { .. F } @[simp] lemma map_functorial_obj (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : map F.obj f = F.map f := rfl instance functorial_id : functorial.{v₁ v₁} (id : C → C) := { map := λ X Y f, f } section variables {E : Type u₃} [category.{v₃} E] /-- `G ∘ F` is a functorial if both `F` and `G` are. -/ -- This is no longer viable as an instance in Lean 3.7, -- #lint reports an instance loop -- Will this be a problem? def functorial_comp (F : C → D) [functorial.{v₁ v₂} F] (G : D → E) [functorial.{v₂ v₃} G] : functorial.{v₁ v₃} (G ∘ F) := { ..(functor.of F ⋙ functor.of G) } end end category_theory
52196610b62a785a7024e3c05bcb260fa06ba490
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/strLitProj.lean
5c9bcf0125a64723cf1fc397fb631d253c5cc4a1
[ "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
81
lean
#reduce "".data example : "".data = [] := rfl theorem ex : "".data = [] := rfl
07e66872c3f6cf0dc4cd6e5db2cc7b3fe34a98b9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/archive/imo/imo1972_b2.lean
81d6444723f3f3d9f7095da2e6ae2a78f3e05f73
[ "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
4,335
lean
/- Copyright (c) 2020 Ruben Van de Velde, Stanislas Polu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ruben Van de Velde, Stanislas Polu -/ import data.real.basic import data.set.basic import analysis.normed_space.basic /-! # IMO 1972 B2 Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`, `f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`. Prove that `|g(x)| ≤ 1` for all `x`. -/ /-- This proof begins by introducing the supremum of `f`, `k ≤ 1` as well as `k' = k / ∥g y∥`. We then suppose that the conclusion does not hold (`hneg`) and show that `k ≤ k'` (by `2 * (∥f x∥ * ∥g y∥) ≤ 2 * k` obtained from the main hypothesis `hf1`) and that `k' < k` (obtained from `hneg` directly), finally raising a contradiction with `k' < k'`. (Authored by Stanislas Polu inspired by Ruben Van de Velde). -/ example (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, (f(x+y) + f(x-y)) = 2 * f(x) * g(y)) (hf2 : ∀ y, ∥f(y)∥ ≤ 1) (hf3 : ∃ x, f(x) ≠ 0) (y : ℝ) : ∥g(y)∥ ≤ 1 := begin classical, set S := set.range (λ x, ∥f x∥), -- Introduce `k`, the supremum of `f`. let k : ℝ := Sup (S), -- Show that `∥f x∥ ≤ k`. have hk₁ : ∀ x, ∥f x∥ ≤ k, { have h : bdd_above S, from ⟨1, set.forall_range_iff.mpr hf2⟩, intro x, exact le_cSup h (set.mem_range_self x), }, -- Show that `2 * (∥f x∥ * ∥g y∥) ≤ 2 * k`. have hk₂ : ∀ x, 2 * (∥f x∥ * ∥g y∥) ≤ 2 * k, { intro x, calc 2 * (∥f x∥ * ∥g y∥) = ∥2 * f x * g y∥ : by simp [real.norm_eq_abs, abs_mul, mul_assoc] ... = ∥f (x + y) + f (x - y)∥ : by rw hf1 ... ≤ ∥f (x + y)∥ + ∥f (x - y)∥ : norm_add_le _ _ ... ≤ k + k : add_le_add (hk₁ _) (hk₁ _) ... = 2 * k : (two_mul _).symm, }, -- Suppose the conclusion does not hold. by_contra hneg, push_neg at hneg, set k' := k / ∥g y∥, -- Demonstrate that `k' < k` using `hneg`. have H₁ : k' < k, { have h₁ : 0 < k, { obtain ⟨x, hx⟩ := hf3, calc 0 < ∥f x∥ : norm_pos_iff.mpr hx ... ≤ k : hk₁ x }, rw div_lt_iff, apply lt_mul_of_one_lt_right h₁ hneg, exact trans zero_lt_one hneg }, -- Demonstrate that `k ≤ k'` using `hk₂`. have H₂ : k ≤ k', { have h₁ : ∃ x : ℝ, x ∈ S, { use ∥f 0∥, exact set.mem_range_self 0, }, have h₂ : ∀ x, ∥f x∥ ≤ k', { intros x, rw le_div_iff, { apply (mul_le_mul_left zero_lt_two).mp (hk₂ x) }, { exact trans zero_lt_one hneg } }, apply cSup_le h₁, rintros y' ⟨yy, rfl⟩, exact h₂ yy }, -- Conclude by obtaining a contradiction, `k' < k'`. apply lt_irrefl k', calc k' < k : H₁ ... ≤ k' : H₂, end /-- IMO 1972 B2 Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`, `f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`. Prove that `|g(x)| ≤ 1` for all `x`. This is a more concise version of the proof proposed by Ruben Van de Velde. -/ example (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, (f (x+y) + f(x-y)) = 2 * f(x) * g(y)) (hf2 : bdd_above (set.range (λ x, ∥f x∥))) (hf3 : ∃ x, f(x) ≠ 0) (y : ℝ) : ∥g(y)∥ ≤ 1 := begin obtain ⟨x, hx⟩ := hf3, set k := ⨆ x, ∥f x∥, have h : ∀ x, ∥f x∥ ≤ k := le_csupr hf2, by_contradiction H, push_neg at H, have hgy : 0 < ∥g y∥, by linarith, have k_pos : 0 < k := lt_of_lt_of_le (norm_pos_iff.mpr hx) (h x), have : k / ∥g y∥ < k := (div_lt_iff hgy).mpr (lt_mul_of_one_lt_right k_pos H), have : k ≤ k / ∥g y∥, { suffices : ∀ x, ∥f x∥ ≤ k / ∥g y∥, from csupr_le this, intro x, suffices : 2 * (∥f x∥ * ∥g y∥) ≤ 2 * k, by { rwa [le_div_iff hgy, ←mul_le_mul_left zero_lt_two], apply_instance }, calc 2 * (∥f x∥ * ∥g y∥) = ∥2 * f x * g y∥ : by simp [abs_mul, mul_assoc] ... = ∥f (x + y) + f (x - y)∥ : by rw hf1 ... ≤ ∥f (x + y)∥ + ∥f (x - y)∥ : abs_add _ _ ... ≤ 2 * k : by linarith [h (x+y), h (x -y)] }, linarith, end
b4a6649fc3259adf53ed499a6b5769e967d5ad11
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/uniform_space/complete_separated.lean
13a3844519483403036658937250d46ec093c60c
[ "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
1,353
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.cauchy import topology.uniform_space.separation import topology.dense_embedding /-! # Theory of complete separated uniform spaces. This file is for elementary lemmas that depend on both Cauchy filters and separation. -/ open filter open_locale topological_space filter variables {α : Type*} /-In a separated space, a complete set is closed -/ lemma is_complete.is_closed [uniform_space α] [separated_space α] {s : set α} (h : is_complete s) : is_closed s := is_closed_iff_cluster_pt.2 $ λ a ha, begin let f := 𝓝 a ⊓ 𝓟 s, have : cauchy f := cauchy_nhds.mono' ha inf_le_left, rcases h f this (inf_le_right) with ⟨y, ys, fy⟩, rwa (tendsto_nhds_unique' ha inf_le_left fy : a = y) end namespace dense_inducing open filter variables [topological_space α] {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated_space γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_inducing e) (h : ∀ b : β, cauchy (map f (comap e $ 𝓝 b))) : continuous (de.extend f) := de.continuous_extend $ λ b, complete_space.complete (h b) end dense_inducing
aa561bfc70721f10c8681fd0056a93c857ae746a
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/bounded_continuous_function.lean
a7ff4db404afd01e61704687cb88eb148c175069
[ "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
28,972
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.basic /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ noncomputable theory open_locale topological_space classical open set filter metric universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) := {f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C} local infixr ` →ᵇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space α] [metric_space β] [metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β := ⟨f, hf, bounded_range_iff.1 $ bounded_of_compact $ compact_range hf⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, λ y, calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≤ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf dist_set_exists $ λb hb, hb.2 x @[ext] lemma ext (H : ∀x, f x = g x) : f = g := subtype.eq $ funext H lemma ext_iff : f = g ↔ ∀ x, f x = g x := ⟨λ h, λ x, h ▸ rfl, ext⟩ /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf dist_set_exists (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg', eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg), dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } variable (α) /-- Constant as a continuous bounded function. -/ def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ variable {α} @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl lemma const_apply (a : α) (b : β) : (const α b : α → β) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α (default β)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ have Hs : _ := continuous_iff'.1 f.2.1 x (ε/2) (half_pos ε0), mem_sets_of_superset (prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) Hs) $ λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy ... = ε : add_halves _ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (tendsto_const_nhds.dist (hF x)) (filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous, as a uniform limit of continuous functions -/ have : tendsto_uniformly (λn x, f n x) F at_top, { refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _), refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _), rw dist_comm, exact lt_of_le_of_lt (fF_bdd x n) hn }, exact this.continuous (λN, (f N).2.1) }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), λ x y, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) {C : nnreal} (H : lipschitz_with C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨λx, G (f x), H.continuous.comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) := lipschitz_with.of_dist_le_mul $ λ f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _ ... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨s.cod_restrict f H, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space α] [compact_space α] [metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)), refine calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : is_compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset ((_ : is_compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set β) (hs : is_compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' hs.is_closed).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ 𝓝 x, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : 0 < ε) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [normed_group β] variables (f g : α →ᵇ β) {x : α} {C : ℝ} instance : has_zero (α →ᵇ β) := ⟨const α 0⟩ @[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl /-- The norm of a bounded continuous function is the supremum of `∥f x∥`. We use `Inf` to ensure that the definition works if `α` has no elements. -/ lemma norm_eq (f : α →ᵇ β) : ∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} := by simp [norm_def, bounded_continuous_function.dist_eq] lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) : dist (f x) (f y) ≤ 2 * C := calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _ ... ≤ C + C : add_le_add (hC x) (hC y) ... = 2 * C : (two_mul _).symm /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ := dist_le_two_norm' f.norm_coe_le_norm x y variable {f} /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 variable (f) /-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty, then it is equal to `∥b∥`. -/ lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ := (norm_le (norm_nonneg b)).2 $ λ x, le_refl _ @[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ := le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β := ⟨λn, f n, ⟨Hf, ⟨_, dist_le_two_norm' H⟩⟩⟩ lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C := (norm_le hC).2 hfC /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β := of_normed_group f continuous_of_discrete_topology C H /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := ⟨λf g, of_normed_group (f + g) (f.2.1.add g.2.1) (∥f∥ + ∥g∥) $ λ x, le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) (g.norm_coe_le_norm x))⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, of_normed_group (-f) f.2.1.neg ∥f∥ $ λ x, trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩ @[simp] lemma coe_add : ⇑(f + g) = λ x, f x + g x := rfl lemma add_apply : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : ⇑(-f) = λ x, - f x := rfl lemma neg_apply : (-f) x = -f x := rfl lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 := (@ext_iff _ _ _ _ f 0).symm instance : add_comm_group (α →ᵇ β) := { add_assoc := assume f g h, by ext; simp [add_assoc], zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp [add_comm], ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_sub : ⇑(f - g) = λ x, f x - g x := rfl lemma sub_apply : (f - g) x = f x - g x := rfl instance : normed_group (α →ᵇ β) := { dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] } lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g := by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x } lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 end normed_group section normed_space /-! ### Normed space structure In this section, if `β` is a normed space, then we show that the space of bounded continuous functions from `α` to `β` inherits a normed space structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_scalar 𝕜 (α →ᵇ β) := ⟨λ c f, of_normed_group (c • f) (continuous_const.smul f.2.1) (∥c∥ * ∥f∥) $ λ x, trans_rel_right _ (norm_smul _ _) (mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))⟩ @[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl instance : semimodule 𝕜 (α →ᵇ β) := semimodule.of_core $ { smul := (•), smul_add := λ c f g, ext $ λ x, smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, ext $ λ x, add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul c₁ c₂ (f x), one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } instance : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _⟩ end normed_space section normed_ring /-! ### Normed ring structure In this section, if `R` is a normed ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] {R : Type*} [normed_ring R] instance : ring (α →ᵇ R) := { one := const α 1, mul := λ f g, of_normed_group (f * g) (f.2.1.mul g.2.1) (∥f∥ * ∥g∥) $ λ x, le_trans (normed_ring.norm_mul (f x) (g x)) $ mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _), one_mul := λ f, ext $ λ x, one_mul (f x), mul_one := λ f, ext $ λ x, mul_one (f x), mul_assoc := λ f₁ f₂ f₃, ext $ λ x, mul_assoc _ _ _, left_distrib := λ f₁ f₂ f₃, ext $ λ x, left_distrib _ _ _, right_distrib := λ f₁ f₂ f₃, ext $ λ x, right_distrib _ _ _, .. bounded_continuous_function.add_comm_group } instance : normed_ring (α →ᵇ R) := { norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, .. bounded_continuous_function.normed_group } end normed_ring section normed_algebra /-! ### Normed algebra structure In this section, if `γ` is a normed algebra, then we show that the space of bounded continuous functions from `α` to `γ` inherits a normed algebra structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables [normed_ring γ] [normed_algebra 𝕜 γ] variables {f g : α →ᵇ γ} {x : α} {c : 𝕜} /-- `bounded_continuous_function.const` as a `ring_hom`. -/ def C : 𝕜 →+* (α →ᵇ γ) := { to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c), map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one, map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _, map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero, map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ } instance : algebra 𝕜 (α →ᵇ γ) := { to_ring_hom := C, commutes' := λ c f, ext $ λ x, algebra.commutes' _ _, smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _, ..bounded_continuous_function.semimodule, ..bounded_continuous_function.ring } instance [nonempty α] : normed_algebra 𝕜 (α →ᵇ γ) := { norm_algebra_map_eq := λ c, begin calc ∥ (algebra_map 𝕜 (α →ᵇ γ)).to_fun c∥ = ∥(algebra_map 𝕜 γ) c∥ : _ ... = ∥c∥ : norm_algebra_map_eq _ _, apply norm_const_eq ((algebra_map 𝕜 γ) c), assumption, end, ..bounded_continuous_function.algebra } /-! ### Structure as normed module over scalar functions If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous functions from `α` to `β` is naturally a module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) := ⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x)) (continuous.smul f.2.1 g.2.1) (∥f∥ * ∥g∥) (λ x, calc ∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _ ... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _) (norm_nonneg _)) ⟩ instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) := semimodule.of_core $ { smul := (•), smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ := norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ /- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts show that the space of bounded continuous functions from `α` to `β` is naturally a normed module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ end normed_algebra end bounded_continuous_function
f6765e068fc25eef1065b7dde91564a87fb87a67
37683ecbb27d7c2037bfd9ad7e06d662f460a005
/homotopy/pushout.hlean
844b4e93bdd54cc9389339ce68ed69cf702bc71a
[ "Apache-2.0" ]
permissive
GRSEB9S/Spectral-1
b2443b09cae7aac1247b1f88c846c532ac802b8e
dd14277e0bfc6270a488eb3b9ec231484065b9d8
refs/heads/master
1,631,315,269,407
1,522,048,315,000
1,522,799,803,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,873
hlean
import ..algebra.exactness homotopy.cofiber homotopy.wedge homotopy.smash open eq function is_trunc sigma prod lift is_equiv equiv pointed sum unit bool cofiber namespace pushout section variables {TL BL TR : Type*} {f : TL →* BL} {g : TL →* TR} {TL' BL' TR' : Type*} {f' : TL' →* BL'} {g' : TL' →* TR'} (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) definition ppushout_functor [constructor] (tl : TL → TL') (bl : BL →* BL') (tr : TR → TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g →* ppushout f' g' := begin fconstructor, { exact pushout.functor tl bl tr fh gh }, { exact ap inl (respect_pt bl) }, end definition ppushout_pequiv (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g ≃* ppushout f' g' := pequiv_of_equiv (pushout.equiv _ _ _ _ tl bl tr fh gh) (ap inl (respect_pt bl)) end /- WIP: proving that satisfying the universal property of the pushout is equivalent to being equivalent to the pushout -/ universe variables u₁ u₂ u₃ u₄ variables {A : Type.{u₁}} {B : Type.{u₂}} {C : Type.{u₃}} {D D' : Type.{u₄}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) -- (f : A → B) (g : A → C) (h : B → D) (k : C → D) include p definition is_pushout : Type := Π⦃X : Type.{max u₁ u₂ u₃ u₄}⦄ (h' : B → X) (k' : C → X) (p' : h' ∘ f ~ k' ∘ g), is_contr (Σ(l : D → X) (v : l ∘ h ~ h' × l ∘ k ~ k'), Πa, square (prod.pr1 v (f a)) (prod.pr2 v (g a)) (ap l (p a)) (p' a)) definition cocone [reducible] (X : Type) : Type := Σ(v : (B → X) × (C → X)), prod.pr1 v ∘ f ~ prod.pr2 v ∘ g definition cocone_of_map [constructor] (X : Type) (l : D → X) : cocone p X := ⟨(l ∘ h, l ∘ k), λa, ap l (p a)⟩ -- definition cocone_of_map (X : Type) (l : D → X) : Σ(h' : B → X) (k' : C → X), -- h' ∘ f ~ k' ∘ g := -- ⟨l ∘ h, l ∘ k, λa, ap l (p a)⟩ omit p definition is_pushout2 [reducible] : Type := Π(X : Type.{max u₁ u₂ u₃ u₄}), is_equiv (cocone_of_map p X) section open sigma.ops protected definition inv_left (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ h ~ prod.pr1 v.1 := ap10 (ap prod.pr1 (right_inv (cocone_of_map p X) v)..1) protected definition inv_right (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ k ~ prod.pr2 v.1 := ap10 (ap prod.pr2 (right_inv (cocone_of_map p X) v)..1) end section local attribute is_pushout [reducible] definition is_prop_is_pushout : is_prop (is_pushout p) := _ local attribute is_pushout2 [reducible] definition is_prop_is_pushout2 : is_prop (is_pushout2 p) := _ end definition ap_eq_apd10_ap {A B : Type} {C : B → Type} (f : A → Πb, C b) {a a' : A} (p : a = a') (b : B) : ap (λa, f a b) p = apd10 (ap f p) b := by induction p; reflexivity variables (f g) definition is_pushout2_pushout : @is_pushout2 _ _ _ _ f g inl inr glue := λX, to_is_equiv (pushout_arrow_equiv f g X ⬝e assoc_equiv_prod _) definition is_equiv_of_is_pushout2_simple [constructor] {A B C D : Type.{u₁}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) (H : is_pushout2 p) : D ≃ pushout f g := begin fapply equiv.MK, { exact (cocone_of_map p _)⁻¹ᶠ ⟨(inl, inr), glue⟩ }, { exact pushout.elim h k p }, { intro x, exact sorry }, { apply ap10, apply eq_of_fn_eq_fn (equiv.mk _ (H D)), fapply sigma_eq, { esimp, fapply prod_eq, apply eq_of_homotopy, intro b, exact ap (pushout.elim h k p) (pushout.inv_left p H ⟨(inl, inr), glue⟩ b), apply eq_of_homotopy, intro c, exact ap (pushout.elim h k p) (pushout.inv_right p H ⟨(inl, inr), glue⟩ c) }, { apply pi.pi_pathover_constant, intro a, apply eq_pathover, refine !ap_eq_apd10_ap ⬝ph _ ⬝hp !ap_eq_apd10_ap⁻¹, refine ap (λx, apd10 x _) (ap_compose (λx, x ∘ f) pr1 _ ⬝ ap02 _ !prod_eq_pr1) ⬝ph _ ⬝hp ap (λx, apd10 x _) (ap_compose (λx, x ∘ g) pr2 _ ⬝ ap02 _ !prod_eq_pr2)⁻¹, refine apd10 !apd10_ap_precompose_dependent a ⬝ph _ ⬝hp apd10 !apd10_ap_precompose_dependent⁻¹ a, refine apd10 !apd10_eq_of_homotopy (f a) ⬝ph _ ⬝hp apd10 !apd10_eq_of_homotopy⁻¹ (g a), refine ap_compose (pushout.elim h k p) _ _ ⬝pv _, refine aps (pushout.elim h k p) _ ⬝vp (!elim_glue ⬝ !ap_id⁻¹), esimp, exact sorry }, } end -- definition is_equiv_of_is_pushout2 [constructor] (H : is_pushout2 p) : D ≃ pushout f g := -- begin -- fapply equiv.MK, -- { exact down.{_ u₄} ∘ (cocone_of_map p _)⁻¹ᶠ ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ }, -- { exact pushout.elim h k p }, -- { intro x, exact sorry -- }, -- { intro d, apply eq_of_fn_eq_fn (equiv_lift D), esimp, revert d, -- apply ap10, -- apply eq_of_fn_eq_fn (equiv.mk _ (H (lift.{_ (max u₁ u₂ u₃)} D))), -- fapply sigma_eq, -- { esimp, fapply prod_eq, -- apply eq_of_homotopy, intro b, apply ap up, esimp, -- exact ap (pushout.elim h k p ∘ down.{_ u₄}) -- (pushout.inv_left p H ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ b), -- exact sorry }, -- { exact sorry }, -- -- note q := @eq_of_is_contr _ H'' -- -- ⟨up ∘ pushout.elim h k p ∘ down ∘ (center' H').1, -- -- (λb, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr1 (center' H').2 b), -- -- λc, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr2 (center' H').2 c))⟩ -- -- ⟨up, (λx, idp, λx, idp)⟩, -- -- exact ap down (ap10 q..1 d) -- } -- end /- composing pushouts -/ definition pushout_vcompose_to [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout h (@inl _ _ _ f g)) : pushout (h ∘ f) g := begin induction x with d y b, { exact inl d }, { induction y with b c a, { exact inl (h b) }, { exact inr c }, { exact glue a }}, { reflexivity } end definition pushout_vcompose_from [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout (h ∘ f) g) : pushout h (@inl _ _ _ f g) := begin induction x with d c a, { exact inl d }, { exact inr (inr c) }, { exact glue (f a) ⬝ ap inr (glue a) } end definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := begin fapply equiv.MK, { exact pushout_vcompose_to }, { exact pushout_vcompose_from }, { intro x, induction x with d c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_vcompose_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ !ap_compose'⁻¹ ⬝ !idp_con ⬝ _, esimp, apply elim_glue }}, { intro x, induction x with d y b, { reflexivity }, { induction y with b c a, { exact glue b }, { reflexivity }, { apply eq_pathover, refine ap_compose pushout_vcompose_from _ _ ⬝ph _, esimp, refine ap02 _ !elim_glue ⬝ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }}, { apply eq_pathover_id_right, esimp, refine ap_compose pushout_vcompose_from _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }} end definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := calc pushout (@inr _ _ _ f g) h ≃ pushout h (@inr _ _ _ f g) : pushout.symm ... ≃ pushout h (@inl _ _ _ g f) : pushout.equiv _ _ _ _ erfl erfl (pushout.symm f g) (λa, idp) (λa, idp) ... ≃ pushout (h ∘ g) f : pushout_vcompose ... ≃ pushout f (h ∘ g) : pushout.symm definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : pushout h k ≃ pushout hf g := begin refine _ ⬝e pushout_vcompose f g h ⬝e _, { fapply pushout.equiv, reflexivity, reflexivity, exact e, reflexivity, exact homotopy_of_homotopy_inv_post e _ _ p }, { fapply pushout.equiv, reflexivity, reflexivity, reflexivity, exact q, reflexivity }, end definition pushout_hcompose_equiv {A B C D E : Type} {f : A → B} (g : A → C) {h : C → E} {hg : A → E} {k : C → D} (e : D ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inr) (q : h ∘ g ~ hg) : pushout k h ≃ pushout f hg := calc pushout k h ≃ pushout h k : pushout.symm ... ≃ pushout hg f : by exact pushout_vcompose_equiv _ (e ⬝e pushout.symm f g) p q ... ≃ pushout f hg : pushout.symm definition pushout_of_equiv_left_to [unfold 6] {A B C : Type} {f : A ≃ B} {g : A → C} (x : pushout f g) : C := begin induction x with b c a, { exact g (f⁻¹ b) }, { exact c }, { exact ap g (left_inv f a) } end definition pushout_of_equiv_left [constructor] {A B C : Type} (f : A ≃ B) (g : A → C) : pushout f g ≃ C := begin fapply equiv.MK, { exact pushout_of_equiv_left_to }, { exact inr }, { intro c, reflexivity }, { intro x, induction x with b c a, { exact (glue (f⁻¹ b))⁻¹ ⬝ ap inl (right_inv f b) }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose inr _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply move_top_of_left, apply move_left_of_bot, refine ap02 _ (adj f _) ⬝ !ap_compose⁻¹ ⬝pv _ ⬝vp !ap_compose, apply natural_square_tr }} end definition pushout_of_equiv_right [constructor] {A B C : Type} (f : A → B) (g : A ≃ C) : pushout f g ≃ B := calc pushout f g ≃ pushout g f : pushout.symm f g ... ≃ B : pushout_of_equiv_left g f -- todo: define pushout.equiv (renamed to pushout_equiv_pushout) using this variables {A₁ B₁ C₁ A₂ B₂ C₂ A₃ B₃ C₃ : Type} {f₁ : A₁ → B₁} {g₁ : A₁ → C₁} {f₂ : A₂ → B₂} {g₂ : A₂ → C₂} {f₃ : A₃ → B₃} {g₃ : A₃ → C₃} {h₂ : A₂ → A₃} {h₁ : A₁ → A₂} {i₂ : B₂ → B₃} {i₁ : B₁ → B₂} {j₂ : C₂ → C₃} {j₁ : C₁ → C₂} (p₂ : i₂ ∘ f₂ ~ f₃ ∘ h₂) (q₂ : j₂ ∘ g₂ ~ g₃ ∘ h₂) (p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁) (q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁) definition pushout_functor_compose : pushout.functor (h₂ ∘ h₁) (i₂ ∘ i₁) (j₂ ∘ j₁) (p₁ ⬝htyv p₂) (q₁ ⬝htyv q₂) ~ pushout.functor h₂ i₂ j₂ p₂ q₂ ∘ pushout.functor h₁ i₁ j₁ p₁ q₁ := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, refine !elim_glue ⬝ whisker_right _ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ (ap02 _ !con_inv ⬝ !ap_con ⬝ whisker_left _ (ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹)) ⬝ _ ⬝ (ap_compose (pushout.functor h₂ i₂ j₂ p₂ q₂) _ _ ⬝ ap02 _ !elim_glue)⁻¹, refine _ ⬝ (!ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ !ap_compose'⁻¹)⁻¹ᵖ, refine !con.assoc⁻¹ ⬝ whisker_right _ _, exact whisker_right _ !con.assoc ⬝ !con.assoc } end variables {p₁ q₁} definition pushout_functor_homotopy_constant {p₁' : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁' : j₁ ∘ g₁ ~ g₂ ∘ h₁} (p : p₁ ~ p₁') (q : q₁ ~ q₁') : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₁ i₁ j₁ p₁' q₁' := begin induction p, induction q, reflexivity end definition pushout_functor_homotopy {h₁ h₂ : A₁ → A₂} {i₁ i₂ : B₁ → B₂} {j₁ j₂ : C₁ → C₂} {p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁} {p₂ : i₂ ∘ f₁ ~ f₂ ∘ h₂} {q₂ : j₂ ∘ g₁ ~ g₂ ∘ h₂} (r : h₁ ~ h₂) (s : i₁ ~ i₂) (t : j₁ ~ j₂) (u : r ⬝htyh p₁ ~ p₂ ⬝htyh s) (v : r ⬝htyh q₁ ~ q₂ ⬝htyh t) : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₂ i₂ j₂ p₂ q₂ := begin induction r, induction s, induction t, apply pushout_functor_homotopy_constant, { exact (rfl_hhconcat p₁)⁻¹ʰᵗʸ ⬝hty u ⬝hty hhconcat_rfl p₂ }, exact (rfl_hhconcat q₁)⁻¹ʰᵗʸ ⬝hty v ⬝hty hhconcat_rfl q₂ end /- pushout where one map is constant is a cofiber -/ definition pushout_const_equiv_to [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : pushout f (const A c₀)) : cofiber (sum_functor f (const unit c₀)) := begin induction x with b c a, { exact !cod (sum.inl b) }, { exact !cod (sum.inr c) }, { exact glue (sum.inl a) ⬝ (glue (sum.inr ⋆))⁻¹ } end definition pushout_const_equiv_from [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : cofiber (sum_functor f (const unit c₀))) : pushout f (const A c₀) := begin induction x with v v, { induction v with b c, exact inl b, exact inr c }, { exact inr c₀ }, { induction v with a u, exact glue a, reflexivity } end definition pushout_const_equiv [constructor] {A B C : Type} (f : A → B) (c₀ : C) : pushout f (const A c₀) ≃ cofiber (sum_functor f (const unit c₀)) := begin fapply equiv.MK, { exact pushout_const_equiv_to }, { exact pushout_const_equiv_from }, { intro x, induction x with v v, { induction v with b c, reflexivity, reflexivity }, { exact glue (sum.inr ⋆) }, { apply eq_pathover_id_right, refine ap_compose pushout_const_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction v with a u, { refine !elim_glue ⬝ph _, apply whisker_bl, exact hrfl }, { induction u, exact square_of_eq idp }}}, { intro x, induction x with c b a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_const_equiv_from _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) }} end /- wedge is the cofiber of the map 2 -> A + B -/ -- move to sum definition sum_of_bool [unfold 3] (A B : Type*) (b : bool) : A + B := by induction b; exact sum.inl pt; exact sum.inr pt definition psum_of_pbool [constructor] (A B : Type*) : pbool →* (A +* B) := pmap.mk (sum_of_bool A B) idp -- move to wedge definition wedge_equiv_pushout_sum [constructor] (A B : Type*) : wedge A B ≃ cofiber (sum_of_bool A B) := begin refine pushout_const_equiv _ _ ⬝e _, fapply pushout.equiv, exact bool_equiv_unit_sum_unit⁻¹ᵉ, reflexivity, reflexivity, intro x, induction x: reflexivity, intro x, induction x with u u: induction u; reflexivity end section open prod.ops /- products preserve pushouts -/ definition pushout_prod_equiv_to [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (xd : pushout f g × D) : pushout (prod_functor f (@id D)) (prod_functor g id) := begin induction xd with x d, induction x with b c a, { exact inl (b, d) }, { exact inr (c, d) }, { exact glue (a, d) } end definition pushout_prod_equiv_from [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (x : pushout (prod_functor f (@id D)) (prod_functor g id)) : pushout f g × D := begin induction x with bd cd ad, { exact (inl bd.1, bd.2) }, { exact (inr cd.1, cd.2) }, { exact prod_eq (glue ad.1) idp } end definition pushout_prod_equiv {A B C D : Type} (f : A → B) (g : A → C) : pushout f g × D ≃ pushout (prod_functor f (@id D)) (prod_functor g id) := begin fapply equiv.MK, { exact pushout_prod_equiv_to }, { exact pushout_prod_equiv_from }, { intro x, induction x with bd cd ad, { induction bd, reflexivity }, { induction cd, reflexivity }, { induction ad with a d, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_prod_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, esimp, exact !ap_prod_elim ⬝ !idp_con ⬝ !elim_glue }}, { intro xd, induction xd with x d, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose (pushout_prod_equiv_from ∘ pushout_prod_equiv_to) _ _ ⬝ _, refine ap02 _ !ap_prod_mk_left ⬝ !ap_compose ⬝ _, refine ap02 _ (!ap_prod_elim ⬝ !idp_con ⬝ !elim_glue) ⬝ _, refine !elim_glue ⬝ !ap_prod_mk_left⁻¹ }} end end /- interaction of pushout and sums -/ definition pushout_to_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout f g) : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin induction x with b c a, { exact inl (sum.inl b) }, { exact inr c }, { exact glue (sum.inl a) } end definition pushout_from_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀))) : pushout f g := begin induction x with x c x, { induction x with b d, exact inl b, exact inr c₀ }, { exact inr c }, { induction x with a d, exact glue a, reflexivity } end /- The pushout of B <-- A --> C is the same as the pushout of B + D <-- A + D --> C -/ definition pushout_sum_cancel_equiv [constructor] {A B C : Type} (f : A → B) (g : A → C) (D : Type) (c₀ : C) : pushout f g ≃ pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin fapply equiv.MK, { exact pushout_to_sum D c₀ }, { exact pushout_from_sum D c₀ }, { intro x, induction x with x c x, { induction x with b d, reflexivity, esimp, exact (glue (sum.inr d))⁻¹ }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose (pushout_to_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with a d: esimp, { exact hdeg_square !elim_glue }, { exact square_of_eq !con.left_inv }}}, { intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (pushout_from_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ !elim_glue }} end end pushout namespace pushout variables {A A' B B' C C' : Type} {f : A → B} {g : A → C} {f' : A' → B'} {g' : A' → C'} definition sum_pushout_of_pushout_sum [unfold 11] (x : pushout (sum_functor f f') (sum_functor g g')) : pushout f g ⊎ pushout f' g' := begin induction x with b c a, { exact sum_functor inl inl b }, { exact sum_functor inr inr c }, { induction a with a a', exact ap sum.inl (glue a), exact ap sum.inr (glue a') } end definition pushout_sum_of_sum_pushout [unfold 11] (x : pushout f g ⊎ pushout f' g') : pushout (sum_functor f f') (sum_functor g g') := begin induction x with x x, { exact pushout.functor sum.inl sum.inl sum.inl homotopy.rfl homotopy.rfl x }, { exact pushout.functor sum.inr sum.inr sum.inr homotopy.rfl homotopy.rfl x } end variables (f g f' g') /- do we want to define this in terms of sigma_pushout? One possible disadvantage is that the computation on glue is less convenient -/ definition pushout_sum_equiv_sum_pushout [constructor] : pushout (sum_functor f f') (sum_functor g g') ≃ pushout f g ⊎ pushout f' g' := equiv.MK sum_pushout_of_pushout_sum pushout_sum_of_sum_pushout abstract begin intro x, induction x with x x, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, end end abstract begin intro x, induction x with b c a, { induction b: reflexivity }, { induction c: reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sum_of_sum_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': (apply hdeg_square; refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con) } end end variables {f g f' g'} variables {D E F D' E' F' : Type} {h : D → E} {i : D → F} {h' : D' → E'} {i' : D' → F'} {j : A → D} {k : B → E} {l : C → F} {j' : A' → D'} {k' : B' → E'} {l' : C' → F'} {j₂ : A' → D} {k₂ : B' → E} {l₂ : C' → F} (s : hsquare f h j k) (t : hsquare g i j l) (s' : hsquare f' h' j' k') (t' : hsquare g' i' j' l') (s₂ : hsquare f' h j₂ k₂) (t₂ : hsquare g' i j₂ l₂) definition sum_rec_pushout_sum_equiv_sum_pushout : sum.rec (pushout.functor j k l s t) (pushout.functor j₂ k₂ l₂ s₂ t₂) ∘ pushout_sum_equiv_sum_pushout f g f' g' ~ pushout.functor (sum.rec j j₂) (sum.rec k k₂) (sum.rec l l₂) (sum_rec_hsquare s s₂) (sum_rec_hsquare t t₂) := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': exact hdeg_square (!ap_compose'⁻¹ ⬝ !elim_glue ⬝ !elim_glue⁻¹) end end } end definition pushout_sum_equiv_sum_pushout_natural : hsquare (pushout.functor (j +→ j') (k +→ k') (l +→ l') (sum_functor_hsquare s s') (sum_functor_hsquare t t')) (pushout.functor j k l s t +→ pushout.functor j' k' l' s' t') (pushout_sum_equiv_sum_pushout f g f' g') (pushout_sum_equiv_sum_pushout h i h' i') := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _ ⬝hp (!ap_compose ⬝ ap02 _ !elim_glue)⁻¹, refine !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ !ap_inv) ⬝ph _, induction a with a a', { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inl _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inl _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inl _ _) ⬝ !ap_con⁻¹ }, { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inr _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inr _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inr _ _) ⬝ !ap_con⁻¹ } end end } end end pushout namespace pushout open sigma sigma.ops variables {X : Type} {A B C : X → Type} {f : Πx, A x → B x} {g : Πx, A x → C x} definition sigma_pushout_of_pushout_sigma [unfold 7] (x : pushout (total f) (total g)) : Σx, pushout (f x) (g x) := begin induction x with b c a, { exact total (λx, inl) b }, { exact total (λx, inr) c }, { exact sigma_eq_right (glue a.2) } end definition pushout_sigma_of_sigma_pushout [unfold 7] (x : Σx, pushout (f x) (g x)) : pushout (total f) (total g) := pushout.functor (dpair x.1) (dpair x.1) (dpair x.1) homotopy.rfl homotopy.rfl x.2 variables (f g) definition pushout_sigma_equiv_sigma_pushout [constructor] : pushout (total f) (total g) ≃ Σx, pushout (f x) (g x) := equiv.MK sigma_pushout_of_pushout_sigma pushout_sigma_of_sigma_pushout abstract begin intro x, induction x with x y, induction y with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sigma_pushout_of_pushout_sigma _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue } end end abstract begin intro x, induction x with b c a, { induction b, reflexivity }, { induction c, reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sigma_of_sigma_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a', apply hdeg_square, refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con } end end variables {f g} variables {X' : Type} {A' B' C' : X' → Type} {f' : Πx, A' x → B' x} {g' : Πx, A' x → C' x} {s : X → X'} {h₁ : Πx, A x → A' (s x)} {h₂ : Πx, B x → B' (s x)} {h₃ : Πx, C x → C' (s x)} (p : Πx, h₂ x ∘ f x ~ f' (s x) ∘ h₁ x) (q : Πx, h₃ x ∘ g x ~ g' (s x) ∘ h₁ x) definition pushout_sigma_equiv_sigma_pushout_natural : hsquare (pushout.functor (sigma_functor s h₁) (sigma_functor s h₂) (sigma_functor s h₃) (λa, sigma_eq_right (p a.1 a.2)) (λa, sigma_eq_right (q a.1 a.2))) (sigma_functor s (λx, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) (pushout_sigma_equiv_sigma_pushout f g) (pushout_sigma_equiv_sigma_pushout f' g') := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { exact abstract begin apply eq_pathover, apply hdeg_square, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_compose'⁻¹) ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹) ⬝ _, exact (ap_compose (sigma_functor s (λ x, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_compose'⁻¹ ⬝ ap_compose (dpair _) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ !ap_compose'⁻¹)⁻¹ end end } end /- an induction principle for the cofiber of f : A → B if A is a pushout where the second map has a section. The Pgluer is modified to get the right coherence See https://github.com/HoTT/HoTT-Agda/blob/master/theorems/homotopy/elims/CofPushoutSection.agda -/ open sigma.ops definition cofiber_pushout_helper' {A : Type} {B : A → Type} {a₀₀ a₀₂ a₂₀ a₂₂ : A} {p₀₁ : a₀₀ = a₀₂} {p₁₀ : a₀₀ = a₂₀} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} {s : square p₀₁ p₂₁ p₁₀ p₁₂} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ b₂₂' : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂'} {q₁₂ : b₀₂ =[p₁₂] b₂₂} : Σ(r : b₂₂' = b₂₂), squareover B s q₀₁ (r ▸ q₂₁) q₁₀ q₁₂ := begin induction s, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₀ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idp, idso⟩ end definition cofiber_pushout_helper {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} {Pcod : Πd, P (cofiber.cod h d)} {Pbase : P (cofiber.base h)} (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (a : A) : Σ(p : Pbase = Pbase), squareover P (natural_square cofiber.glue (glue a)) (Pgluel (f a)) (p ▸ Pgluer (g a)) (pathover_ap P (λa, cofiber.cod h (h a)) (apd (λa, Pcod (h a)) (glue a))) (pathover_ap P (λa, cofiber.base h) (apd (λa, Pbase) (glue a))) := !cofiber_pushout_helper' definition cofiber_pushout_rec {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} (Pcod : Πd, P (cofiber.cod h d)) (Pbase : P (cofiber.base h)) (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (r : C → A) (p : Πa, r (g a) = a) (x : cofiber h) : P x := begin induction x with d x, { exact Pcod d }, { exact Pbase }, { induction x with b c a, { exact Pgluel b }, { exact (cofiber_pushout_helper Pgluel Pgluer (r c)).1 ▸ Pgluer c }, { apply pathover_pathover, rewrite [p a], exact (cofiber_pushout_helper Pgluel Pgluer a).2 }} end /- universal property of cofiber -/ definition cofiber_exact_1 {X Y Z : Type*} (f : X →* Y) (g : pcofiber f →* Z) : (g ∘* pcod f) ∘* f ~* pconst X Z := !passoc ⬝* pwhisker_left _ !pcod_pcompose ⬝* !pcompose_pconst protected definition pcofiber.elim [constructor] {X Y Z : Type*} {f : X →* Y} (g : Y →* Z) (p : g ∘* f ~* pconst X Z) : pcofiber f →* Z := begin fapply pmap.mk, { intro w, induction w with y x, exact g y, exact pt, exact p x }, { reflexivity } end protected definition pcofiber.elim_pcod {X Y Z : Type*} {f : X →* Y} {g : Y →* Z} (p : g ∘* f ~* pconst X Z) : pcofiber.elim g p ∘* pcod f ~* g := begin fapply phomotopy.mk, { intro y, reflexivity }, { esimp, refine !idp_con ⬝ _, refine _ ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_inv) ◾ !elim_glue)⁻¹, apply eq_inv_con_of_con_eq, exact (to_homotopy_pt p)⁻¹ } end /- The maps Z^{C_f} --> Z^Y --> Z^X are exact at Z^Y. Here Y^X means pointed maps from X to Y and C_f is the cofiber of f. The maps are given by precomposing with (pcod f) and f. -/ definition cofiber_exact {X Y Z : Type*} (f : X →* Y) : is_exact_t (@ppcompose_right _ _ Z (pcod f)) (ppcompose_right f) := begin constructor, { intro g, apply eq_of_phomotopy, apply cofiber_exact_1 }, { intro g p, note q := phomotopy_of_eq p, exact fiber.mk (pcofiber.elim g q) (eq_of_phomotopy (pcofiber.elim_pcod q)) } end /- cofiber of pcod is suspension -/ definition pcofiber_pcod {A B : Type*} (f : A →* B) : pcofiber (pcod f) ≃* susp A := begin fapply pequiv_of_equiv, { refine !pushout.symm ⬝e _, exact pushout_vcompose_equiv f equiv.rfl homotopy.rfl homotopy.rfl }, reflexivity end -- definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : -- pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := -- definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : -- pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := -- definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} -- {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : -- pushout h k ≃ pushout hf g := end pushout namespace pushout /- define the quotient using pushout -/ section open quotient sigma.ops variables {A B : Type} (R : A → A → Type) {Q : B → B → Type} (f : A → B) (k : Πa a' : A, R a a' → Q (f a) (f a')) definition pushout_quotient {A : Type} (R : A → A → Type) : Type := @pushout ((Σa a', R a a') ⊎ (Σa a', R a a')) A (Σa a', R a a') (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) variable {R} definition pushout_quotient_of_quotient [unfold 3] (x : quotient R) : pushout_quotient R := begin induction x with a a a' r, { exact inl a }, { exact glue (sum.inl ⟨a, a', r⟩) ⬝ (glue (sum.inr ⟨a, a', r⟩))⁻¹ } end definition quotient_of_pushout_quotient [unfold 3] (x : pushout_quotient R) : quotient R := begin induction x with a x x, { exact class_of R a }, { exact class_of R x.2.1 }, { induction x with x x, exact eq_of_rel R x.2.2, reflexivity } end variable (R) definition quotient_equiv_pushout [constructor] : quotient R ≃ pushout_quotient R := equiv.MK pushout_quotient_of_quotient quotient_of_pushout_quotient abstract begin intro x, induction x with a x x, { reflexivity }, { exact glue (sum.inr x) }, { apply eq_pathover_id_right, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with x x, { refine !elim_eq_of_rel ⬝ph _, induction x with a x, induction x with a' r, exact whisker_bl _ hrfl }, { exact square_of_eq idp }} end end abstract begin intro x, induction x, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose quotient_of_pushout_quotient _ _ ⬝ ap02 _ !elim_eq_of_rel ⬝ _, exact !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) } end end variable {R} definition sigma_functor2 [unfold 7] : (Σ a a', R a a') → (Σ b b', Q b b') := sigma_functor f (λa, sigma_functor f (k a)) definition pushout_quotient_functor [unfold 7] : pushout_quotient R → pushout_quotient Q := let tf := sigma_functor2 f k in pushout.functor (sum_functor tf tf) f tf begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end definition quotient_equiv_pushout_natural : hsquare (quotient.functor _ _ f k) (pushout_quotient_functor f k) (quotient_equiv_pushout R) (quotient_equiv_pushout Q) := begin intro x, induction x with a a a' r, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ _ ⬝ (ap_compose (pushout.functor _ _ _ _ _) _ _)⁻¹, refine ap02 _ !elim_eq_of_rel ⬝ _ ⬝ (ap02 _ !elim_eq_of_rel)⁻¹, refine !elim_eq_of_rel ⬝ _, exact (!ap_con ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con) ◾ (!ap_inv ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con)⁻²))⁻¹ } end end variables {A B : Type*} open smash definition prod_of_wedge [unfold 3] (v : wedge A B) : A × B := begin induction v with a b , { exact (a, pt) }, { exact (pt, b) }, { reflexivity } end definition wedge_of_sum [unfold 3] (v : A + B) : wedge A B := begin induction v with a b, { exact pushout.inl a }, { exact pushout.inr b } end definition prod_of_wedge_of_sum [unfold 3] (v : A + B) : prod_of_wedge (wedge_of_sum v) = prod_of_sum v := begin induction v with a b, { reflexivity }, { reflexivity } end definition eq_inl_pushout_wedge_of_sum [unfold 3] (v : wedge A B) : inl pt = inl v :> pushout wedge_of_sum bool_of_sum := begin induction v with a b, { exact glue (sum.inl pt) ⬝ (glue (sum.inl a))⁻¹, }, { exact ap inl (glue ⋆) ⬝ glue (sum.inr pt) ⬝ (glue (sum.inr b))⁻¹, }, { apply eq_pathover_constant_left, refine !con.right_inv ⬝pv _ ⬝vp !con_inv_cancel_right⁻¹, exact square_of_eq idp } end variables (A B) definition eq_inr_pushout_wedge_of_sum [unfold 3] (b : bool) : inl pt = inr b :> pushout (@wedge_of_sum A B) bool_of_sum := begin induction b, { exact glue (sum.inl pt) }, { exact ap inl (glue ⋆) ⬝ glue (sum.inr pt) } end definition is_contr_pushout_wedge_of_sum : is_contr (pushout (@wedge_of_sum A B) bool_of_sum) := begin apply is_contr.mk (pushout.inl pt), intro x, induction x with v b w, { apply eq_inl_pushout_wedge_of_sum }, { apply eq_inr_pushout_wedge_of_sum }, { apply eq_pathover_constant_left_id_right, induction w with a b, { apply whisker_rt, exact vrfl }, { apply whisker_rt, exact vrfl }} end definition bool_of_sum_of_bool {A B : Type*} (b : bool) : bool_of_sum (sum_of_bool A B b) = b := by induction b: reflexivity /- a different proof, using pushout lemmas, and the fact that the wedge is the pushout of A + B <-- 2 --> 1 -/ definition pushout_wedge_of_sum_equiv_unit : pushout (@wedge_of_sum A B) bool_of_sum ≃ unit := begin refine pushout_hcompose_equiv (sum_of_bool A B) (wedge_equiv_pushout_sum A B ⬝e !pushout.symm) _ _ ⬝e _, exact erfl, intro x, induction x, reflexivity, reflexivity, exact bool_of_sum_of_bool, apply pushout_of_equiv_right end end pushout namespace pushout -- should this be wedge? /- the wedge connectivity lemma actually works as intended -/ section open trunc_index is_conn prod prod.ops -- of course, the tricky part is coming up with the statement; -- the proof is easy! private definition tricky_lemma {A B : Type} (f : A → B) {a a' : A} (p : a = a') (P : B → Type) {r : f a = f a'} (α : ap f p = r) (s : Π x, P (f x)) (e : Π y, P y) (q : e (f a) = s a) (q' : e (f a') = s a') (H : (ap (transport P r) q)⁻¹ ⬝ (apdt e r ⬝ q') = (tr_compose P f p (s a) ⬝ ap (λ u, transport P u (s a)) α)⁻¹ ⬝ apdt s p) : q =[p] q' := begin induction α, induction p, apply pathover_idp_of_eq, esimp, esimp at H, rewrite ap_id at H, rewrite idp_con at H, exact (eq_con_of_inv_con_eq H)⁻¹, end parameters (n m : ℕ) {A B : Type*} private definition section_of_glue (P : A × B → Type) (s : Π w, P (prod_of_wedge w)) : (s (inl pt) = s (inr pt) :> P (pt, pt)) := ((tr_compose P prod_of_wedge (glue star) (s (inl pt))) ⬝ (ap (λ q, transport P q (s (inl pt))) (wedge.elim_glue (λ a, (a, pt)) (λ b, (pt, b)) idp)))⁻¹ ⬝ (apdt s (glue star)) parameters (A B) parameters [cA : is_conn n A] [cB : is_conn m B] include cA cB definition is_conn_fun_prod_of_wedge : is_conn_fun (m + n) (@prod_of_wedge A B) := begin apply is_conn.is_conn_fun.intro, intro P, fapply is_retraction.mk, { intros s z, induction z with a b, exact @wedge_extension.ext A B n m cA cB (λ a b, P (a, b)) (λ a b, transport (λ k, is_trunc k (P (a, b))) (of_nat_add_of_nat m n) (trunctype.struct (P (a, b)))) (λ a, s (inl a)) (λ b, s (inr b)) (section_of_glue P s) a b }, { intro s, apply eq_of_homotopy, intro w, induction w with a b, { esimp, apply wedge_extension.β_left }, { esimp, apply wedge_extension.β_right }, { esimp, apply @tricky_lemma (wedge A B) (A × B) (@prod_of_wedge A B) (inl pt) (inr pt) wedge.glue P idp (wedge.elim_glue (λ a, (a, pt)) (λ b, (pt, b)) idp) s (prod.rec (@wedge_extension.ext A B n m cA cB (λ a b, P (a, b)) (λ a b, transport (λ k, is_trunc k (P (a, b))) (of_nat_add_of_nat m n) (trunctype.struct (P (a, b)))) (λ a, s (inl a)) (λ b, s (inr b)) (section_of_glue P s))), esimp, rewrite [ap_id,idp_con], apply wedge_extension.coh } } end end end pushout namespace pushout /- alternative version of the flattening lemma -/ -- should be moved to main library section open sigma sigma.ops universe variables u₁ u₂ u₃ u₄ parameters {TL : Type.{u₁}} {BL : Type.{u₂}} {TR : Type.{u₃}} (f : TL → BL) (g : TL → TR) (P : pushout f g → Type.{u₄}) local abbreviation F : sigma (λ x, P (inl (f x))) → sigma (P ∘ inl) := λ z, ⟨ f z.1 , z.2 ⟩ local abbreviation G : sigma (λ x, P (inl (f x))) → sigma (P ∘ inr) := λ z, ⟨ g z.1 , transport P (glue z.1) z.2 ⟩ local abbreviation Pglue : Π x, P (inl (f x)) ≃ P (inr (g x)) := λ x, equiv.mk (transport P (glue x)) (is_equiv_tr P (glue x)) protected definition flattening' : sigma P ≃ pushout F G := begin assert H : Π w, P w ≃ pushout.elim_type (P ∘ inl) (P ∘ inr) Pglue w, { intro w, induction w with x x x, { exact erfl }, { exact erfl }, { apply equiv_pathover, intro pfx pgx q, apply pathover_of_tr_eq, apply eq.trans (ap10 (elim_type_glue.{u₁ u₂ u₃ u₄} (P ∘ inl) (P ∘ inr) Pglue x) pfx), -- why do we need explicit universes here? exact tr_eq_of_pathover q } }, apply equiv.trans (sigma_equiv_sigma_right H), exact pushout.flattening f g (P ∘ inl) (P ∘ inr) Pglue end end end pushout
55a586fbfb1ee2f76298012ed50666cc2dfed811
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/theories/analysis/metric_space.lean
e4568b1e916a722337f70fdbd1c46420def9fd28
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,599
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Metric spaces. -/ import data.real.division open real eq.ops classical algebra structure metric_space [class] (M : Type) : Type := (dist : M → M → ℝ) (dist_self : ∀ x : M, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : M}, dist x y = 0 → x = y) (dist_comm : ∀ x y : M, dist x y = dist y x) (dist_triangle : ∀ x y z : M, dist x y + dist y z ≥ dist x z) namespace metric_space section metric_space_M variables {M : Type} [strucM : metric_space M] include strucM proposition dist_eq_zero_iff (x y : M) : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (suppose x = y, this ▸ !dist_self) proposition dist_nonneg (x y : M) : 0 ≤ dist x y := have dist x y + dist y x ≥ 0, by rewrite -(dist_self x); apply dist_triangle, have 2 * dist x y ≥ 0, using this, by krewrite [-real.one_add_one, right_distrib, +one_mul, dist_comm at {2}]; apply this, nonneg_of_mul_nonneg_left this two_pos proposition dist_pos_of_ne {x y : M} (H : x ≠ y) : dist x y > 0 := lt_of_le_of_ne !dist_nonneg (suppose 0 = dist x y, H (iff.mp !dist_eq_zero_iff this⁻¹)) proposition eq_of_forall_dist_le {x y : M} (H : ∀ ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_zero_of_nonneg_of_forall_le !dist_nonneg H) open nat /- convergence of a sequence -/ definition converges_to_seq (X : ℕ → M) (y : M) : Prop := ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ ⦃n⦄, n ≥ N → dist (X n) y < ε -- the same, with ≤ in place of <; easier to prove, harder to use definition converges_to_seq.intro {X : ℕ → M} {y : M} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → dist (X n) y ≤ ε) : converges_to_seq X y := take ε, assume epos : ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N HN, from H e2pos, exists.intro N (take n, suppose n ≥ N, calc dist (X n) y ≤ ε / 2 : HN _ `n ≥ N` ... < ε : div_two_lt_of_pos epos) notation X `⟶` y `in` `ℕ` := converges_to_seq X y definition converges_seq [class] (X : ℕ → M) : Prop := ∃ y, X ⟶ y in ℕ noncomputable definition limit_seq (X : ℕ → M) [H : converges_seq X] : M := some H proposition converges_to_limit_seq (X : ℕ → M) [H : converges_seq X] : (X ⟶ limit_seq X in ℕ) := some_spec H proposition converges_to_seq_unique {X : ℕ → M} {y₁ y₂ : M} (H₁ : X ⟶ y₁ in ℕ) (H₂ : X ⟶ y₂ in ℕ) : y₁ = y₂ := eq_of_forall_dist_le (take ε, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y₁ < ε / 2), from H₁ e2pos, obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y₂ < ε / 2), from H₂ e2pos, let N := max N₁ N₂ in have dN₁ : dist (X N) y₁ < ε / 2, from HN₁ !le_max_left, have dN₂ : dist (X N) y₂ < ε / 2, from HN₂ !le_max_right, have dist y₁ y₂ < ε, from calc dist y₁ y₂ ≤ dist y₁ (X N) + dist (X N) y₂ : dist_triangle ... = dist (X N) y₁ + dist (X N) y₂ : dist_comm ... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂ ... = ε : add_halves, show dist y₁ y₂ ≤ ε, from le_of_lt this) proposition eq_limit_of_converges_to_seq {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) : y = @limit_seq M _ X (exists.intro y H) := converges_to_seq_unique H (@converges_to_limit_seq M _ X (exists.intro y H)) proposition converges_to_seq_constant (y : M) : (λn, y) ⟶ y in ℕ := take ε, assume egt0 : ε > 0, exists.intro 0 (take n, suppose n ≥ 0, calc dist y y = 0 : !dist_self ... < ε : egt0) proposition converges_to_seq_offset {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) : (λ n, X (n + k)) ⟶ y in ℕ := take ε, suppose ε > 0, obtain N HN, from H `ε > 0`, exists.intro N (take n : ℕ, assume ngtN : n ≥ N, show dist (X (n + k)) y < ε, from HN (n + k) (le.trans ngtN !le_add_right)) proposition converges_to_seq_offset_left {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) : (λ n, X (k + n)) ⟶ y in ℕ := have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm), by+ rewrite aux; exact converges_to_seq_offset k H proposition converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) : (λ n, X (succ n)) ⟶ y in ℕ := converges_to_seq_offset 1 H proposition converges_to_seq_of_converges_to_seq_offset {X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (n + k)) ⟶ y in ℕ) : X ⟶ y in ℕ := take ε, suppose ε > 0, obtain N HN, from H `ε > 0`, exists.intro (N + k) (take n : ℕ, assume nge : n ≥ N + k, have n - k ≥ N, from nat.le_sub_of_add_le nge, have dist (X (n - k + k)) y < ε, from HN (n - k) this, show dist (X n) y < ε, using this, by rewrite [(nat.sub_add_cancel (le.trans !le_add_left nge)) at this]; exact this) proposition converges_to_seq_of_converges_to_seq_offset_left {X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (k + n)) ⟶ y in ℕ) : X ⟶ y in ℕ := have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm), by+ rewrite aux at H; exact converges_to_seq_of_converges_to_seq_offset H proposition converges_to_seq_of_converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : (λ n, X (succ n)) ⟶ y in ℕ) : X ⟶ y in ℕ := @converges_to_seq_of_converges_to_seq_offset M strucM X y 1 H proposition converges_to_seq_offset_iff (X : ℕ → M) (y : M) (k : ℕ) : ((λ n, X (n + k)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset !converges_to_seq_offset proposition converges_to_seq_offset_left_iff (X : ℕ → M) (y : M) (k : ℕ) : ((λ n, X (k + n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset_left !converges_to_seq_offset_left proposition converges_to_seq_offset_succ_iff (X : ℕ → M) (y : M) : ((λ n, X (succ n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset_succ !converges_to_seq_offset_succ /- cauchy sequences -/ definition cauchy (X : ℕ → M) : Prop := ∀ ε : ℝ, ε > 0 → ∃ N, ∀ m n, m ≥ N → n ≥ N → dist (X m) (X n) < ε proposition cauchy_of_converges_seq (X : ℕ → M) [H : converges_seq X] : cauchy X := take ε, suppose ε > 0, obtain y (Hy : converges_to_seq X y), from H, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y < ε / 2), from Hy e2pos, obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y < ε / 2), from Hy e2pos, let N := max N₁ N₂ in exists.intro N (take m n, suppose m ≥ N, suppose n ≥ N, have m ≥ N₁, from le.trans !le_max_left `m ≥ N`, have n ≥ N₂, from le.trans !le_max_right `n ≥ N`, have dN₁ : dist (X m) y < ε / 2, from HN₁ `m ≥ N₁`, have dN₂ : dist (X n) y < ε / 2, from HN₂ `n ≥ N₂`, show dist (X m) (X n) < ε, from calc dist (X m) (X n) ≤ dist (X m) y + dist y (X n) : dist_triangle ... = dist (X m) y + dist (X n) y : dist_comm ... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂ ... = ε : add_halves) end metric_space_M /- convergence of a function at a point -/ section metric_space_M_N variables {M N : Type} [strucM : metric_space M] [strucN : metric_space N] include strucM strucN definition converges_to_at (f : M → N) (y : N) (x : M) := ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ x', x ≠ x' ∧ dist x x' < δ → dist (f x') y < ε notation f `⟶` y `at` x := converges_to_at f y x definition converges_at [class] (f : M → N) (x : M) := ∃ y, converges_to_at f y x noncomputable definition limit_at (f : M → N) (x : M) [H : converges_at f x] : N := some H proposition converges_to_limit_at (f : M → N) (x : M) [H : converges_at f x] : (f ⟶ limit_at f x at x) := some_spec H definition continuous_at (f : M → N) (x : M) := converges_to_at f (f x) x definition continuous (f : M → N) := ∀ x, continuous_at f x theorem continuous_at_spec {f : M → N} {x : M} (Hf : continuous_at f x) : ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ x', dist x x' < δ → dist (f x') (f x) < ε := take ε, suppose ε > 0, obtain δ Hδ, from Hf this, exists.intro δ (and.intro (and.left Hδ) (take x', suppose dist x x' < δ, if Heq : x = x' then by rewrite [Heq, dist_self]; assumption else (suffices dist x x' < δ, from and.right Hδ x' (and.intro Heq this), this))) theorem image_seq_converges_of_converges [instance] (X : ℕ → M) [HX : converges_seq X] {f : M → N} (Hf : continuous f) : converges_seq (λ n, f (X n)) := begin cases HX with xlim Hxlim, existsi f xlim, rewrite ↑converges_to_seq at *, intros ε Hε, let Hcont := Hf xlim Hε, cases Hcont with δ Hδ, cases Hxlim (and.left Hδ) with B HB, existsi B, intro n Hn, cases em (xlim = X n), rewrite [a, dist_self], assumption, apply and.right Hδ, split, exact a, rewrite dist_comm, apply HB Hn end end metric_space_M_N end metric_space
87e60865ca5c4c6aa0a63c5bc1fb69fc47c5cf10
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/monad/algebra.lean
96ab248a5f6895d7329aaa4558a127e85a8ea4bf
[ "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
6,371
lean
/- Copyright (c) 2019 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.monad.basic import category_theory.adjunction.basic /-! # Eilenberg-Moore (co)algebras for a (co)monad This file defines Eilenberg-Moore (co)algebras for a (co)monad, and provides the category instance for them. Further it defines the adjoint pair of free and forgetful functors, respectively from and to the original category, as well as the adjoint pair of forgetful and cofree functors, respectively from and to the original category. ## References * [Riehl, *Category theory in context*, Section 5.2.4][riehl2017] -/ namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 namespace monad /-- An Eilenberg-Moore algebra for a monad `T`. cf Definition 5.2.3 in [Riehl][riehl2017]. -/ structure algebra (T : C ⥤ C) [monad.{v₁} T] : Type (max u₁ v₁) := (A : C) (a : T.obj A ⟶ A) (unit' : (η_ T).app A ≫ a = 𝟙 A . obviously) (assoc' : ((μ_ T).app A ≫ a) = (T.map a ≫ a) . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' namespace algebra variables {T : C ⥤ C} [monad.{v₁} T] /-- A morphism of Eilenberg–Moore algebras for the monad `T`. -/ @[ext] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : T.map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore algebra. -/ @[simps] def id (A : algebra T) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore algebra homomorphisms. -/ @[simps] def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, category.assoc, g.h, ←category.assoc, f.h, category.assoc] } end hom /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ @[simps] instance EilenbergMoore : category (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } end algebra variables (T : C ⥤ C) [monad.{v₁} T] /-- The forgetful functor from the Eilenberg-Moore category, forgetting the algebraic structure. -/ @[simps] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The free functor from the Eilenberg-Moore category, constructing an algebra for any object. -/ @[simps] def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := (μ_ T).app X, assoc' := (monad.assoc _).symm }, map := λ X Y f, { f := T.map f, h' := by erw (μ_ T).naturality } } /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ def adj : free T ⊣ forget T := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, (η_ T).app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := begin dsimp, simp, conv { to_rhs, rw [←category.assoc, ←(μ_ T).naturality, category.assoc], erw algebra.assoc }, refl, end }, left_inv := λ f, begin ext1, dsimp, simp only [free_obj_a, functor.map_comp, algebra.hom.h, category.assoc], erw [←category.assoc, monad.right_unit, id_comp], end, right_inv := λ f, begin dsimp, erw [←category.assoc, ←(η_ T).naturality, functor.id_map, category.assoc, Y.unit, comp_id], end }} end monad namespace comonad /-- An Eilenberg-Moore coalgebra for a comonad `T`. -/ @[nolint has_inhabited_instance] structure coalgebra (G : C ⥤ C) [comonad.{v₁} G] : Type (max u₁ v₁) := (A : C) (a : A ⟶ G.obj A) (counit' : a ≫ (ε_ G).app A = 𝟙 A . obviously) (coassoc' : (a ≫ (δ_ G).app A) = (a ≫ G.map a) . obviously) restate_axiom coalgebra.counit' restate_axiom coalgebra.coassoc' namespace coalgebra variables {G : C ⥤ C} [comonad.{v₁} G] /-- A morphism of Eilenberg-Moore coalgebras for the comonad `G`. -/ @[ext, nolint has_inhabited_instance] structure hom (A B : coalgebra G) := (f : A.A ⟶ B.A) (h' : A.a ≫ G.map f = f ≫ B.a . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore coalgebra. -/ @[simps] def id (A : coalgebra G) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore coalgebra homomorphisms. -/ @[simps] def comp {P Q R : coalgebra G} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, ← category.assoc, f.h, category.assoc, g.h, category.assoc] } end hom /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ @[simps] instance EilenbergMoore : category (coalgebra G) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } end coalgebra variables (G : C ⥤ C) [comonad.{v₁} G] /-- The forgetful functor from the Eilenberg-Moore category, forgetting the coalgebraic structure. -/ @[simps] def forget : coalgebra G ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The cofree functor from the Eilenberg-Moore category, constructing a coalgebra for any object. -/ @[simps] def cofree : C ⥤ coalgebra G := { obj := λ X, { A := G.obj X, a := (δ_ G).app X, coassoc' := (comonad.coassoc _).symm }, map := λ X Y f, { f := G.map f, h' := by erw (δ_ G).naturality; refl} } /-- The adjunction between the cofree and forgetful constructions for Eilenberg-Moore coalgebras for a comonad. -/ def adj : forget G ⊣ cofree G := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, { f := X.a ≫ G.map f, h' := by { rw [functor.map_comp, ← category.assoc, ← coalgebra.coassoc], simp } }, inv_fun := λ g, g.f ≫ (ε_ G).app Y, left_inv := λ f, begin dsimp, rw [category.assoc, (ε_ G).naturality, functor.id_map, ← category.assoc, X.counit, id_comp], end, right_inv := λ g, begin ext1, dsimp, rw [functor.map_comp, ← category.assoc, coalgebra.hom.h, assoc, cofree_obj_a, comonad.right_counit], dsimp, simp end }} end comonad end category_theory
c55e5dc37e7233129706742ab781d8895716ab18
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/order.lean
c62bca08d5e811e17528e1f0d15ec61dc234a0e3
[ "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
27,862
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.tactic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot [] : t = ⊥) @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @mem_nhds_sets α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨tᶜ, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, compl_compl]⟩, assume ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma coinduced_le_iff_le_induced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.unique_topological_space [subsingleton α] : unique (topological_space α) := { default := ⊥, uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] : discrete_topology α := ⟨unique.eq_default t⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space unit := ⊥ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i @[continuity] lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le @[continuity] lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have ne_bot (comap f (𝓝 (f a) ⊓ 𝓟 (f '' s))) ↔ ne_bot (𝓝 (f a) ⊓ 𝓟 (f '' s)), from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot, assume h, forall_sets_nonempty_iff_ne_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ 𝓝 (f a) ⊓ 𝓟 (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ 𝓟 (f '' s), from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := h.nonempty_of_mem this in ⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ 𝓟 s ≠ ⊥ : by rw [closure_eq_cluster_pts]; refl ... ↔ comap f (𝓝 (f a)) ⊓ 𝓟 (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) ⊓ 𝓟 (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_cluster_pts] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := is_open_supr_iff end infi
053e8873e01b0e8e578675a9bbaee120580caac3
aa2345b30d710f7e75f13157a35845ee6d48c017
/category_theory/opposites.lean
1d12fe24f895286567c7163048d3d690ea0f6887
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
1,954
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.types namespace category_theory universes u₁ v₁ u₂ v₂ def op (C : Type u₁) : Type u₁ := C notation C `ᵒᵖ` := op C variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 instance opposite : category.{u₁ v₁} (Cᵒᵖ) := { hom := λ X Y : C, Y ⟶ X, comp := λ _ _ _ f g, g ≫ f, id := λ X, 𝟙 X } namespace functor section variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 protected definition op (F : C ⥤ D) : (Cᵒᵖ) ⥤ (Dᵒᵖ) := { obj := λ X, F X, map' := λ X Y f, F.map f, map_id' := begin /- `obviously'` says: -/ intros, erw [map_id], refl, end, map_comp' := begin /- `obviously'` says: -/ intros, erw [map_comp], refl end } @[simp] lemma opposite_obj (F : C ⥤ D) (X : C) : (F.op) X = F X := rfl @[simp] lemma opposite_map (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : (F.op).map f = F.map f := rfl end variable (C) /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : (Cᵒᵖ × C) ⥤ (Type v₁) := { obj := λ p, @category.hom C _ p.1 p.2, map' := λ X Y f, λ h, f.1 ≫ h ≫ f.2, map_id' := begin /- `obviously'` says: -/ intros, ext, intros, cases X, dsimp at *, simp, erw [category.id_comp] end, map_comp' := begin /- `obviously'` says: -/ intros, ext, intros, cases f, cases g, cases X, cases Y, cases Z, dsimp at *, simp, erw [category.assoc] end } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (functor.hom C) X = @category.hom C _ X.1 X.2 := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (functor.hom C).map f = λ h, f.1 ≫ h ≫ f.2 := rfl end functor end category_theory
48188b70f4976b0ec840b20fd81619801c308309
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/set_theory/cardinal.lean
3d0f87550d14eb5672762cef3dd8c689f8eb8780
[ "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
30,801
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, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.function set_theory.schroeder_bernstein open function lattice set local attribute [instance] classical.prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.lattice.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ @[simp] theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α := mk_le_of_injective subtype.val_injective @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_range_le {α β : Type u} {f : α → β} {s : set α} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range theorem mk_eq_of_injective {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨ set.embedding_of_subset h ⟩ end cardinal
0fb3daf1ba1d257c880c806648272d9e8a70035e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/natural_isomorphism.lean
7b44dc68f968b20087dde82eef60ba8f47745d79
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,240
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor.category import category_theory.isomorphism /-! # Natural isomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For the most part, natural isomorphisms are just another sort of isomorphism. We provide some special support for extracting components: * if `α : F ≅ G`, then `a.app X : F.obj X ≅ G.obj X`, and building natural isomorphisms from components: * ``` nat_iso.of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G ``` only needing to check naturality in one direction. ## Implementation Note that `nat_iso` is a namespace without a corresponding definition; we put some declarations that are specifically about natural isomorphisms in the `iso` namespace so that they are available using dot notation. -/ open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simps] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := ⟨⟨α.inv.app X, ⟨by rw [←comp_app, iso.hom_inv_id, ←id_app], by rw [←comp_app, iso.inv_hom_id, ←id_app]⟩⟩⟩ instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := ⟨⟨α.hom.app X, ⟨by rw [←comp_app, iso.inv_hom_id, ←id_app], by rw [←comp_app, iso.hom_inv_id, ←id_app]⟩⟩⟩ section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma inv_inv_app {F G : C ⥤ D} (e : F ≅ G) (X : C) : inv (e.inv.app X) = e.hom.app X := by { ext, simp } end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : α.inv.app X ≫ F.map f ≫ α.hom.app Y = G.map f := by simp lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : α.hom.app X ≫ G.map f ≫ α.inv.app Y = F.map f := by simp lemma naturality_1' (α : F ⟶ G) (f : X ⟶ Y) [is_iso (α.app X)] : inv (α.app X) ≫ F.map f ≫ α.app Y = G.map f := by simp @[simp, reassoc] lemma naturality_2' (α : F ⟶ G) (f : X ⟶ Y) [is_iso (α.app Y)] : α.app X ≫ G.map f ≫ inv (α.app Y) = F.map f := by rw [←category.assoc, ←naturality, category.assoc, is_iso.hom_inv_id, category.comp_id] /-- The components of a natural isomorphism are isomorphisms. -/ instance is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := ⟨⟨(inv α).app X, ⟨congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X⟩⟩⟩ @[simp] lemma is_iso_inv_app (α : F ⟶ G) [is_iso α] (X) : (inv α).app X = inv (α.app X) := by { ext, rw ←nat_trans.comp_app, simp, } @[simp] lemma inv_map_inv_app (F : C ⥤ D ⥤ E) {X Y : C} (e : X ≅ Y) (Z : D) : inv ((F.map e.inv).app Z) = (F.map e.hom).app Z := by { ext, simp, } /-- Construct a natural isomorphism between functors by giving object level isomorphisms, and checking naturality only in the forward direction. -/ @[simps] def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := { hom := { app := λ X, (app X).hom }, inv := { app := λ X, (app X).inv, naturality' := λ X Y f, begin have h := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (naturality f).symm, simp only [iso.inv_hom_id_assoc, iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end }, } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy /-- A natural transformation is an isomorphism if all its components are isomorphisms. -/ -- Making this an instance would cause a typeclass inference loop with `is_iso_app_of_is_iso`. lemma is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := ⟨(is_iso.of_iso (of_components (λ X, as_iso (α.app X)) (by tidy))).1⟩ /-- Horizontal composition of natural isomorphisms. -/ @[simps] def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end lemma is_iso_map_iff {F₁ F₂ : C ⥤ D} (e : F₁ ≅ F₂) {X Y : C} (f : X ⟶ Y) : is_iso (F₁.map f) ↔ is_iso (F₂.map f) := begin revert F₁ F₂, suffices : ∀ {F₁ F₂ : C ⥤ D} (e : F₁ ≅ F₂) (hf : is_iso (F₁.map f)), is_iso (F₂.map f), { exact λ F₁ F₂ e, ⟨this e, this e.symm⟩, }, introsI F₁ F₂ e hf, refine is_iso.mk ⟨e.inv.app Y ≫ inv (F₁.map f) ≫ e.hom.app X, _, _⟩, { simp only [nat_trans.naturality_assoc, is_iso.hom_inv_id_assoc, iso.inv_hom_id_app], }, { simp only [assoc, ← e.hom.naturality, is_iso.inv_hom_id_assoc, iso.inv_hom_id_app], }, end end nat_iso end category_theory
a77af58044a0f3b85a1b021bf44ea5a4ad73e7ef
b392eb79fb36952401156496daa60628ccb07438
/MathPort/Rules.lean
bcb07128b2ac09e193f2d1fbad96698da53bbd7f
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
1,677
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Gabriel Ebner -/ import MathPort.Util import MathPort.Basic import Lean import Std.Data.HashSet import Std.Data.HashMap namespace MathPort open Lean open Std (HashSet mkHashSet HashMap mkHashMap) def parseRules (rulesFilename : String) : PortM Unit := IO.FS.withFile rulesFilename IO.FS.Mode.read fun h => do while (not (← h.isEof)) do match (← h.getLine).trim.splitOn " " with | ("#" :: _) => pure () | ["align", n₁, n₂] => align (parseName n₁) (parseName n₂) | ["unchanged", n] => unchanged (parseName n) | ["rename", n₁, n₂] => rename (parseName n₁) (parseName n₂) | ["sorry", n] => addSorry (parseName n) | ["neversorry", n] => addNeverSorry (parseName n) | ["noinst", n] => addNoInst (parseName n) | [""] => pure () | tokens => throwError s!"[loadRules] unexpected: '{tokens}'" where align (f t : Name) := modify $ λ s => { s with newNames := s.newNames.insert f t, ignored := s.ignored.insert f } rename (f t : Name) := modify $ λ s => { s with newNames := s.newNames.insert f t } unchanged (n : Name) := align n n addSorry (n : Name) := modify $ λ s => { s with sorries := s.sorries.insert n } addNeverSorry (n : Name) := modify $ λ s => { s with sorries := s.neverSorries.insert n } addNoInst (n : Name) := modify $ λ s => { s with noInsts := s.noInsts.insert n }
40a592f331fc1050e9f4115435390238258f7ff3
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/linear_algebra/basis.lean
4cc8786f0e74e364a1a14d330869886d4acc5c7b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
46,744
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, Alexander Bentkamp Linear independence and basis sets in a module or vector space. This file is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define the following concepts: * `linear_independent α v`: states that the elements of the family `v` are linear independent * `linear_independent.repr hv x`: choose the linear combination representing `x` on the linear independent vectors `v`, given `hv : linear_independent α v`. `x` should be in `span α (range v)` (uses classical choice). * `is_basis α v`: if `v` is a basis, i.e. linear independent and spans the entire space * `is_basis.repr hv x`: like `linear_independent.repr` but as a `linear_map` * `is_basis.constr hv g`: constructs a `linear_map` by extending `g` from the basis `v`, given `hv : is_basis α v`. -/ import linear_algebra.basic linear_algebra.finsupp order.zorn noncomputable theory open function lattice set submodule variables {ι : Type*} {ι' : Type*} {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {v : ι → β} variables [decidable_eq ι] [decidable_eq ι'] [decidable_eq α] [decidable_eq β] [decidable_eq γ] [decidable_eq δ] section module variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables {a b : α} {x y : β} include α variables (α) (v) /-- Linearly independent set of vectors -/ def linear_independent : Prop := (finsupp.total ι β α v).ker = ⊥ variables {α} {v} theorem linear_independent_iff : linear_independent α v ↔ ∀l, finsupp.total ι β α v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent α v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:α)) (hv : linear_independent α v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ α) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent α v) (f : ι' → ι) (hf : injective f) : linear_independent α (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : linear_independent α v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent α v) {l₁ l₂ : ι →₀ α} : finsupp.total ι β α v l₁ = finsupp.total ι β α v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : α) ≠ 1) (hv : linear_independent α v) : injective v := begin intros i j hij, let l : ι →₀ α := finsupp.single i (1 : α) - finsupp.single j 1, have h_total : finsupp.total ι β α v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : α) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent α v) : @linear_independent ι α (span α (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span α (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span α (range v))), simp end section subtype /- The following lemmas use the subtype defined by a set in β as the index set ι. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent α (v ∘ subtype.val : s → β) ↔ ∀ l ∈ (finsupp.supported α α s), (finsupp.total ι β α v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ subtype.val_injective }, intros i hi, rw mem_image, use subtype.mk i (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ s) hi), rw mem_preimage, exact ⟨hi, rfl⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], apply subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι β α v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set β} : linear_independent α (λ x, x : s → β) ↔ ∀ l ∈ (finsupp.supported α α s), (finsupp.total β β α id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent α (v ∘ subtype.val : s → β) ↔ disjoint (finsupp.supported α α s) (finsupp.total ι β α v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set β} : linear_independent α (λ x, x : s → β) ↔ disjoint (finsupp.supported α α s) (finsupp.total β β α id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set β} : linear_independent α (λ x, x : s → β) ↔ (finsupp.total_on β β α id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent α v) : linear_independent α (λ x, x : range v → β) := begin by_cases zero_eq_one : (0 : α) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ (linear_independent.injective zero_eq_one hv) }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : β), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent α (λ x, x : range v → β)) : linear_independent α v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent α (v ∘ subtype.val : s → β)) : linear_independent α (function.restrict v s) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain α α (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent α (λ x, x : (∅ : set β) → β) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set β} (h : t ⊆ s) : linear_independent α (λ x, x : s → β) → linear_independent α (λ x, x : t → β) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint_mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set β} (hs : linear_independent α (λ x, x : s → β)) (ht : linear_independent α (λ x, x : t → β)) (hst : disjoint (span α s) (span α t)) : linear_independent α (λ x, x : (s ∪ t) → β) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total β β α id ls ∈ span α t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total β β α id lt ∈ span α s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total β β α id) ls ∈ span α s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total β β α id) lt ∈ span α t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total β β α id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total β β α id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set β) (H : ∀ t ⊆ s, finite t → linear_independent α (λ x, x : t → β)) : linear_independent α (λ x, x : s → β) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set β} (hs : directed (⊆) s) (h : ∀ i, linear_independent α (λ x, x : s i → β)) : linear_independent α (λ x, x : (⋃ i, s i) → β) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set β)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent α (λ x, x : (a : set β) → β)) : linear_independent α (λ x, x : (⋃₀ s) → β) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set β} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent α (λ x, x : t a → β)) : linear_independent α (λ x, x : (⋃a∈s, t a) → β) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set β} (hl : ∀i, linear_independent α (λ x, x : f i → β)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span α (f i)) (⨆i∈t, span α (f i))) : linear_independent α (λ x, x : (⋃i, f i) → β) := begin classical, rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine disjoint_mono (le_refl _) _ (hd i _ _ his), { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set β) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (inj_on_of_injective _ (assume i j, plift.up.inj)) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} [decidable_eq η] [∀ j, decidable_eq (ιs j)] {f : Π j : η, ιs j → β} (hindep : ∀j, linear_independent α (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span α (range (f i))) (⨆i∈t, span α (range (f i)))) : linear_independent α (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : α) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent α v) def linear_independent.total_equiv (hv : linear_independent α v) : (ι →₀ α) ≃ₗ[α] span α (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span α (range v)) (finsupp.total ι β α v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span α (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end def linear_independent.repr (hv : linear_independent α v) : span α (range v) →ₗ[α] ι →₀ α := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι β α v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι β α v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ α} {x} (eq : finsupp.total ι β α v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ α) →ₗ[α] span α (range v)) l) = finsupp.total ι β α v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ α) →ₗ[α] span α (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent_iff_not_smul_mem_span : linear_independent α v ↔ (∀ (i : ι) (a : α), a • (v i) ∈ span α (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp, by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent α v) (f : ι' ↪ ι) (hss : range v ⊆ span α (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : α)): surjective f := begin intros i, let repr : (span α (range (v ∘ f)) : Type*) → ι' →₀ α := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι β α v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι β α v) l = (finsupp.total ι β α v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : α) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set β} (zero_ne_one : (0 : α) ≠ 1) (hs : linear_independent α (λ x, x : s → β)) (h : t ⊆ s) (hst : s ⊆ span α t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent α v) {f : β →ₗ γ} (hf_inj : disjoint (span α (range v)) f.ker) : linear_independent α (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited β := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ α _ _ _ _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set β} {f : β →ₗ γ} (hs : linear_independent α (λ x, x : s → β)) (hf_inj : disjoint (span α s) f.ker) : linear_independent α (λ x, x : f '' s → γ) := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited β := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp, @finsupp.lmap_domain_total _ _ α _ _ _ _ _ _ _ _ _ _ _ _ id id, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set β} {t : set γ} (hs : linear_independent α (λ x, x : s → β)) (ht : linear_independent α (λ x, x : t → γ)) : linear_independent α (λ x, x : inl α β γ '' s ∪ inr α β γ '' t → β × γ) := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → β} {v' : ι' → γ} (hv : linear_independent α v) (hv' : linear_independent α v') : linear_independent α (sum.elim (inl α β γ ∘ v) (inr α β γ ∘ v')) := begin by_cases zero_eq_one : (0 : α) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_mono _ _ disjoint_inl_inr, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end lemma le_of_span_le_span {s t u: set β} (zero_ne_one : (0 : α) ≠ 1) (hl : linear_independent α (subtype.val : u → β )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span α s ≤ span α t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set β} (zero_ne_one : (0 : α) ≠ 1) (hl : linear_independent α (subtype.val : u → β )) (hsu : s ⊆ u) (htu : t ⊆ u) : span α s ≤ span α t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (α) (v) /-- A set of vectors is a basis if it is linearly independent and all vectors are in the span α. -/ def is_basis := linear_independent α v ∧ span α (range v) = ⊤ variables {α} {v} section is_basis variables {s t : set β} (hv : is_basis α v) lemma is_basis.mem_span (hv : is_basis α v) : ∀ x, x ∈ span α (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis α v) (f : ι' → ι) (hf : bijective f) : is_basis α (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis α v) (zero_ne_one : (0 : α) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h def is_basis.repr : β →ₗ (ι →₀ α) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι β α v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι β α v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported α α univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ α) (hx : x ∈ finsupp.supported α α (univ : set ι)) : hv.repr (finsupp.total ι β α v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → γ) : β →ₗ[α] γ := (finsupp.total γ γ α id).comp $ (finsupp.lmap_domain α α f).comp hv.repr theorem is_basis.constr_apply (f : ι → γ) (x : β) : (hv.constr f : β → γ) x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : β →ₗ[α] γ} (hv : is_basis α v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → γ} {i : ι} (hv : is_basis α v) : (hv.constr f : β → γ) (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → γ} {f : β →ₗ[α] γ} (hv : is_basis α v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : β →ₗ[α] γ) : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis α v) : hv.constr (λi, (0 : γ)) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → γ} (hv : is_basis α v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → γ} (hv : is_basis α v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → γ} (hs : is_basis α v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [constr_add, constr_neg] -- this only works on functions if `α` is a commutative ring lemma constr_smul {ι α β γ} [decidable_eq ι] [decidable_eq α] [decidable_eq β] [decidable_eq γ] [comm_ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] {v : ι → α} {f : ι → γ} {a : α} (hv : is_basis α v) {b : β} : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [inhabited ι] (hv : is_basis α v) {f : ι → γ} : (hv.constr f).range = span α (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] def module_equiv_finsupp (hv : is_basis α v) : β ≃ₗ[α] ι →₀ α := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm def equiv_of_is_basis {v : ι → β} {v' : ι' → γ} {f : β → γ} {g : γ → β} (hv : is_basis α v) (hv' : is_basis α v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : β ≃ₗ γ := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:β →ₗ[α] β, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:γ →ₗ[α] γ, h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → β} {v' : ι' → γ} (hv : is_basis α v) (hv' : is_basis α v') : is_basis α (sum.elim (inl α β γ ∘ v) (inr α β γ ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl α β γ), hv.2, map_top, set.range_comp, span_image (inr α β γ), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (α : Type*) [unique ι] [decidable_eq α] [ring α] : is_basis α (λ (_ : ι), (1 : α)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end lemma linear_equiv.is_basis (hs : is_basis α v) (f : β ≃ₗ[α] γ) : is_basis α (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ _ _ _ _ hs.1 (f : β →ₗ[α] γ), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span α ((f : β →ₗ[α] γ) '' range v) = ⊤, { rw [span_image (f : β →ₗ[α] γ), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent α v) : @is_basis ι α (span α (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span α (set.range (λ i, subtype.mk (v i) _))) = span α (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : β) ∈ map (submodule.subtype _) (span α (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:β, x = 0) : is_basis α (λ x : ι, (0 : β)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis α (λ _ : ι, (0 : (⊥ : submodule α β))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot α).1 (subtype.mem x), end end module section vector_space variables [discrete_field α] [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] {s t : set β} {x y z : β} include α open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section set_option class.instance_max_depth 36 lemma mem_span_insert_exchange : x ∈ span α (insert y s) → x ∉ span α s → y ∈ span α (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent α v ↔ (∀i, v i ∉ span α (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent α v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul _ (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : β} (hx : x ≠ 0) : linear_independent α (λ x, x : ({x} : set β) → β) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule α β} {x : β} (x0 : x ≠ 0) : disjoint p (span α {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent α (λ b, b : s → β)) (hx : x ∉ span α s) : linear_independent α (λ b, b : insert x s → β) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0], exact classical.dec_eq α end lemma exists_linear_independent (hs : linear_independent α (λ x, x : s → β)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span α b ∧ linear_independent α (λ x, x : b → β) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent α (λ x, x : b → β)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span α b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent α (λ x, x : s → β)) : ∃b, s ⊆ b ∧ is_basis α (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (α β) lemma exists_is_basis : ∃b : set β, is_basis α (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {α β} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset β} (hs : linear_independent α (λ x, x : s → β)) (hst : s ⊆ (span α ↑t : submodule α β)) : ∃t':finset β, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset β), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span α ↑(s' ∪ t) : submodule α β) → ∃t':finset β, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one α _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span α ↑(s' ∪ t) : submodule α β), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span α ↑(s' ∪ t) : submodule α β), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span α ↑(insert b₂ s' ∪ t) : submodule α β), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set β), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span α (insert b₁ (insert b₂ ↑(s' ∪ t) : set β)), from span_mono this (hss' hb₃), have s ⊆ (span α (insert b₁ ↑(s' ∪ t)) : submodule α β), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span α (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by rw [finset.union_comm] at hb₂t'; simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent α (λ x, x : s → β)) (hst : s ⊆ span α t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span α ↑(ht.to_finset) : submodule α β), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : β →ₗ[α] γ} (hf_inj : f.ker = ⊥) : ∃g:γ →ₗ β, g.comp f = linear_map.id := begin rcases exists_is_basis α β with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent α (λ x, x : f '' B → γ), { have h₁ := hB₀.image_subtype (show disjoint (span α (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited β := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → β), apply @is_basis.ext _ _ _ _ _ _ _ _ (show decidable_eq β, by assumption) _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : β →ₗ[α] γ} (hf_surj : f.range = ⊤) : ∃g:γ →ₗ β, f.comp g = linear_map.id := begin rcases exists_is_basis α γ with ⟨C, hC⟩, haveI : inhabited β := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → β), apply @is_basis.ext _ _ _ _ _ _ _ _ (show decidable_eq γ, by assumption) _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end set_option class.instance_max_depth 49 open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule α β) : nonempty ((p.quotient × p) ≃ₗ[α] β) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.copair p.subtype) (p.mkq.pair (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype variables (h : is_basis α v) local attribute [instance] submodule.module noncomputable def equiv_fun_basis [fintype ι] : β ≃ (ι → α) := calc β ≃ (ι →₀ α) : (module_equiv_finsupp h).to_equiv ... ≃ (ι → α) : finsupp.equiv_fun_on_fintype theorem vector_space.card_fintype [fintype ι] [fintype α] [fintype β] : card β = (card α) ^ (card ι) := calc card β = card (ι → α) : card_congr (equiv_fun_basis h) ... = card α ^ card ι : card_fun theorem vector_space.card_fintype' [fintype α] [fintype β] : ∃ n : ℕ, card β = (card α) ^ n := begin apply exists.elim (exists_is_basis α β), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact vector_space.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {φ : η → Type*} variables [ring α] [∀i, add_comm_group (φ i)] [∀i, module α (φ i)] [fintype η] [decidable_eq η] lemma linear_independent_std_basis [∀ j, decidable_eq (ιs j)] [∀ i, decidable_eq (φ i)] (v : Πj, ιs j → (φ j)) (hs : ∀i, linear_independent α (v i)) : linear_independent α (λ (ji : Σ j, ιs j), std_basis α φ ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent α (λ i : ιs j, std_basis α φ j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span α (range (λ (i : ιs j), std_basis α φ j (v j i))) ≤ range (std_basis α φ j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span α (range (λ (i : ιs j), std_basis α φ j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis α φ i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis α (λ (j : η), φ j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span α (range (λ (i : ιs j), std_basis α φ j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis α (λ (j : η), φ j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, refine disjoint_mono h₁ h₂ (disjoint_std_basis_std_basis _ _ _ _ h₃), } end lemma is_basis_std_basis [∀ j, decidable_eq (ιs j)] [∀ j, decidable_eq (φ j)] (s : Πj, ιs j → (φ j)) (hs : ∀j, is_basis α (s j)) : is_basis α (λ (ji : Σ j, ιs j), std_basis α φ ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis α φ j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis α φ (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis α φ (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span α (range (std_basis α φ i ∘ s i)) = range (std_basis α φ i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (α ι) lemma is_basis_fun₀ : is_basis α (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis α (λ (i : η), α) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis α _ η (λi:η, unit) (λi:η, α) _ _ _ _ _ _ _ (λ _ _, (1 : α)) (assume i, @is_basis_singleton_one _ _ _ _ _ _), end lemma is_basis_fun : is_basis α (λ i, std_basis α (λi:η, α) i 1) := begin apply is_basis.comp (is_basis_fun₀ α) (λ i, ⟨i, punit.star⟩), { apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] }, end end end module end pi
fcdc932f38390ed016b99fe1df4e04765ff40ae7
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/fintype/small.lean
3c08b81c13615e395f54f0ef48e7c2f121c7c583
[ "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
490
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import logic.small /-! # All finite types are small. That is, any `α` with `[fintype α]` is equivalent to a type in any universe. -/ universes w v @[priority 100] instance small_of_fintype (α : Type v) [fintype α] : small.{w} α := begin rw small_congr (fintype.equiv_fin α), apply_instance, end
eba7336f2e99157db2561676f66fb5bd721a67c5
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/expr_quote.lean
0fb1ec9b0c09ebfe1a913deec7bb00d2a7138bbb
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
143
lean
meta def f (α a : expr) := ```(@id %%α %%a) meta def f (α a : expr) := ```(@id (%%α : Type 2) %%a) set_option pp.universes true #print f
e2ee3d0cb4270fe4b1fbc64823906675d6b23b22
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/analysis/calculus/tangent_cone.lean
538f9027d13cf7810781f56525cf0b07ad54cf09
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,606
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.convex.basic import analysis.normed_space.bounded_linear_maps import analysis.specific_limits /-! # Tangent cone In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s` ensuring that, if a function has two derivatives, then they have to coincide. As a direct definition of this fact (quantifying on all target types and all functions) would depend on universes, we use a more intrinsic definition: if all the possible tangent directions to the set `s` at the point `x` span a dense subset of the whole subset, it is easy to check that the derivative has to be unique. Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`, and express `unique_diff_within_at` and `unique_diff_on` in terms of it. One should however think of this definition as an implementation detail: the only reason to introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness of the derivative. This is why their names reflect their uses, and not how they are defined. ## Implementation details Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the properties of the tangent cone we prove here. -/ 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] open filter set open_locale topological_space /-- The set of all tangent directions to the set `s` at the point `x`. -/ def tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} /-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space. The main role of this property is to ensure that the differential within `s` at `x` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`. To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which is automatic when `E` is not `0`-dimensional). -/ def unique_diff_within_at (s : set E) (x : E) : Prop := dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E) ∧ x ∈ closure s /-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of the whole space. The main role of this property is to ensure that the differential along `s` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in `fderiv.lean`. -/ def unique_diff_on (s : set E) : Prop := ∀x ∈ s, unique_diff_within_at 𝕜 s x variables {𝕜} {x y : E} {s t : set E} section tangent_cone /- This section is devoted to the properties of the tangent cone. -/ open normed_field lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ := begin refine univ_subset_iff.1 (λy hy, _), rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩, refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩, { simp only [norm_pow], exact tendsto_pow_at_top_at_top_of_one_lt hw }, { convert tendsto_const_nhds, ext n, have : w ^ n * (w ^ n)⁻¹ = 1, { apply mul_inv_cancel, apply pow_ne_zero, simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm }, rw [smul_smul, this, one_smul] } end lemma tangent_cone_mono (h : s ⊆ t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩ end /-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone, the sequence `d` tends to 0 at infinity. -/ lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} (hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) : tendsto d l (𝓝 0) := begin have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc, have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) := (continuous_norm.tendsto _).comp hd, have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B, rw zero_mul at C, have : ∀ᶠ n in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥, { apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _), rw [norm_smul, ← mul_assoc, inv_mul_cancel, one_mul], rwa [ne.def, norm_eq_zero] }, have D : tendsto (λ n, ∥d n∥) l (𝓝 0) := tendsto.congr' this C, rw tendsto_zero_iff_norm_tendsto_zero, exact D end lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, refine ⟨c, d, _, ctop, clim⟩, suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x), from tendsto_principal.1 (tendsto_inf.1 this).2, refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h, simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim) end /-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/ lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) : tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x := subset.antisymm (tangent_cone_mono_nhds $ le_of_eq h) (tangent_cone_mono_nhds $ le_of_eq h.symm) /-- Intersecting with a neighborhood of the point does not change the tangent cone. -/ lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) : tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x := tangent_cone_congr (nhds_within_restrict' _ ht).symm /-- The tangent cone of a product contains the tangent cone of its left factor. -/ lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) : linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y (pow_pos one_half_pos n)) with ⟨z, hz, hzt⟩, exact ⟨z - y, by simpa using hzt, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d n, d' n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds hy _, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of its right factor. -/ lemma subset_tangent_cone_prod_right {t : set F} {y : F} (hs : x ∈ closure s) : linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x, by simpa using hzs, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d' n, d n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds _ hy, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of each factor. -/ lemma maps_to_tangent_cone_pi {ι : Type*} [fintype ι] [decidable_eq ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} {i : ι} (hi : ∀ j ≠ i, x j ∈ closure (s j)) : maps_to (linear_map.single i : E i →ₗ[𝕜] Π j, E j) (tangent_cone_at 𝕜 (s i) (x i)) (tangent_cone_at 𝕜 (set.pi univ s) x) := begin rintros w ⟨c, d, hd, hc, hy⟩, have : ∀ n (j ≠ i), ∃ d', x j + d' ∈ s j ∧ ∥c n • d'∥ < (1 / 2 : ℝ) ^ n, { assume n j hj, rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j) (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x j, by simpa using hzs, by simpa using hz⟩ }, choose! d' hd's hcd', refine ⟨c, λ n, function.update (d' n) i (d n), hd.mono (λ n hn j hj', _), hc, tendsto_pi.2 $ λ j, _⟩, { rcases em (j = i) with rfl|hj; simp * }, { rcases em (j = i) with rfl|hj, { simp [hy] }, { suffices : tendsto (λ n, c n • d' n j) at_top (𝓝 0), by simpa [hj], refine squeeze_zero_norm (λ n, (hcd' n j hj).le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } } end /-- If a subset of a real vector space contains a segment, then the direction of this segment belongs to the tangent cone at its endpoints. -/ lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image, refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d, sub_smul, smul_sub, one_smul], abel } }, show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top, { have : (λ (n : ℕ), ∥c n∥) = c, by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) }, rw this, exact tendsto_pow_at_top_at_top_of_one_lt (by norm_num) }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end end tangent_cone section unique_diff /-! ### Properties of `unique_diff_within_at` and `unique_diff_on` This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/ lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) : unique_diff_within_at 𝕜 s x := hs x h lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x := by { rw [unique_diff_within_at, tangent_cone_univ], simp } lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) := λx hx, unique_diff_within_at_univ lemma unique_diff_on_empty : unique_diff_on 𝕜 (∅ : set E) := λ x hx, hx.elim lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x) (st : 𝓝[s] x ≤ 𝓝[t] x) : unique_diff_within_at 𝕜 t x := begin unfold unique_diff_within_at at *, rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢, exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st, h.2.mono st⟩ end lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) : unique_diff_within_at 𝕜 t x := h.mono_nhds $ nhds_within_mono _ st lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) : unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x := ⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩ lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter ht).2 hs lemma unique_diff_within_at_inter' (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter' ht).2 hs lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x := by simpa only [univ_inter] using unique_diff_within_at_univ.inter h lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x := unique_diff_within_at_of_mem_nhds (mem_nhds_sets hs xs) lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) := λx hx, (hs x hx.1).inter (mem_nhds_sets ht hx.2) lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s := λx hx, is_open.unique_diff_within_at hs hx /-- The product of two sets of unique differentiability at points `x` and `y` has unique differentiability at `(x, y)`. -/ lemma unique_diff_within_at.prod {t : set F} {y : F} (hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) : unique_diff_within_at 𝕜 (set.prod s t) (x, y) := begin rw [unique_diff_within_at] at ⊢ hs ht, rw [closure_prod_eq], refine ⟨_, hs.2, ht.2⟩, have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s.prod t) (x, y)) := submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2) (subset_tangent_cone_prod_right hs.2)), rw [linear_map.span_inl_union_inr, submodule.le_def, submodule.prod_coe] at this, exact (hs.1.prod ht.1).mono this end lemma unique_diff_within_at.univ_pi {ι : Type*} [fintype ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} (h : ∀ i, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi univ s) x := begin classical, simp only [unique_diff_within_at, closure_pi_set] at h ⊢, refine ⟨(dense_pi univ (λ i _, (h i).1)).mono _, λ i _, (h i).2⟩, norm_cast, simp only [← submodule.supr_map_single, supr_le_iff, submodule.map_span, submodule.span_le, ← maps_to'], exact λ i, (maps_to_tangent_cone_pi $ λ j hj, (h j).2).mono subset.rfl submodule.subset_span end lemma unique_diff_within_at.pi {ι : Type*} [fintype ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} {I : set ι} (h : ∀ i ∈ I, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi I s) x := begin classical, rw [← set.univ_pi_piecewise], refine unique_diff_within_at.univ_pi (λ i, _), by_cases hi : i ∈ I; simp [*, unique_diff_within_at_univ], end /-- The product of two sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) : unique_diff_on 𝕜 (set.prod s t) := λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.pi {ι : Type*} [fintype ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {I : set ι} (h : ∀ i ∈ I, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi I s) := λ x hx, unique_diff_within_at.pi $ λ i hi, h i hi (x i) (hx i hi) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.univ_pi {ι : Type*} [fintype ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} (h : ∀ i, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi univ s) := unique_diff_on.pi $ λ i _, h i /-- In a real vector space, a convex set with nonempty interior is a set of unique differentiability. -/ theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : (interior s).nonempty) : unique_diff_on ℝ s := begin assume x xs, rcases hs with ⟨y, hy⟩, suffices : y - x ∈ interior (tangent_cone_at ℝ s x), { refine ⟨dense.of_closure _, subset_closure xs⟩, simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior' ⟨y - x, interior_mono submodule.subset_span this⟩] }, rw [mem_interior_iff_mem_nhds] at hy ⊢, apply mem_sets_of_superset ((is_open_map_sub_right x).image_mem_nhds hy), rintros _ ⟨z, zs, rfl⟩, exact mem_tangent_cone_of_segment_subset (conv.segment_subset xs zs) end lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) := unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi] lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) := unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio] lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) := is_open_Ioi.unique_diff_on lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) := is_open_Iio.unique_diff_on lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) := unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab] lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) := if hab : a < b then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab] else by simp only [Ico_eq_empty (le_of_not_lt hab), unique_diff_on_empty] lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) := if hab : a < b then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab] else by simp only [Ioc_eq_empty (le_of_not_lt hab), unique_diff_on_empty] lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) := is_open_Ioo.unique_diff_on /-- The real interval `[0, 1]` is a set of unique differentiability. -/ lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) := unique_diff_on_Icc zero_lt_one end unique_diff
ef5f5a3828dfc1b44d0ad5183a56139e032a7a7b
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/fmatrix.lean
0878ae72ac0de0a0bc158cde461b3cb3eec1bcf0
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
7,105
lean
import data.matrix.basic data.array.lemmas data.rat.basic def fmatrix (m : ℕ) (n : ℕ) := array (m * n) ℚ namespace fmatrix variables {l m n : ℕ} instance : has_add (fmatrix m n) := ⟨array.map₂ (+)⟩ instance : has_zero (fmatrix m n) := ⟨mk_array _ 0⟩ instance : has_neg (fmatrix m n) := ⟨array.map has_neg.neg⟩ lemma add_def (a b : fmatrix m n) : a + b = a.map₂ (+) b := rfl def fin.pair (i : fin m) (j : fin n) : fin (m * n) := ⟨j + n * i, calc ((j : ℕ) + n * i) + 1 = i * n + (j + 1) : by simp [mul_comm, add_comm] ... ≤ i * n + n : add_le_add (le_refl _) j.2 ... = (i + 1) * n : by simp [add_mul] ... ≤ m * n : mul_le_mul i.2 (le_refl _) (nat.zero_le _) (nat.zero_le _)⟩ def fin.unpair₁ (x : fin (m * n)) : fin m := ⟨x / n, nat.div_lt_of_lt_mul (mul_comm m n ▸ x.2)⟩ def fin.unpair₂ (x : fin (m * n)) : fin n := ⟨x % n, nat.mod_lt _ (nat.pos_of_ne_zero (λ hn0, by rw [hn0, mul_zero] at x; exact x.elim0))⟩ @[simp] lemma fin.pair_unpair (x : fin (m * n)) : fin.pair (fin.unpair₁ x) (fin.unpair₂ x) = x := fin.eq_of_veq (nat.mod_add_div _ _) @[simp] lemma fin.unpair₁_pair (i : fin m) (j : fin n) : fin.unpair₁ (fin.pair i j) = i := fin.eq_of_veq $ show ((j : ℕ) + n * i) / n = i, by erw [nat.add_mul_div_left _ _ (lt_of_le_of_lt (nat.zero_le _) j.2), nat.div_eq_of_lt j.2, zero_add] @[simp] lemma fin.unpair₂_pair (i : fin m) (j : fin n) : fin.unpair₂ (fin.pair i j) = j := fin.eq_of_veq $ show ((j : ℕ) + n * i) % n = j, by erw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt j.2]; refl lemma fin.pair_eq_pair {i i' : fin m} {j j' : fin n} : fin.pair i j = fin.pair i' j' ↔ i' = i ∧ j' = j := ⟨λ h, ⟨by rw [← fin.unpair₁_pair i j, h, fin.unpair₁_pair], by rw [← fin.unpair₂_pair i j, h, fin.unpair₂_pair]⟩, λ ⟨hi, hj⟩, by rw [hi, hj]⟩ def read (A : fmatrix m n) (i : fin m) (j : fin n) : ℚ := array.read A (fin.pair i j) def write (A : fmatrix m n) (i : fin m) (j : fin n) : ℚ → fmatrix m n := array.write A (fin.pair i j) @[extensionality] lemma ext {A B : fmatrix m n} (h : ∀ i j, A.read i j = B.read i j) : A = B := array.ext $ λ x, by simpa [fmatrix.read] using h (fin.unpair₁ x) (fin.unpair₂ x) @[simp] lemma read_write (A : fmatrix m n) (i : fin m) (j : fin n) (x : ℚ) : (A.write i j x).read i j = x := array.read_write _ _ _ lemma read_write_of_ne (A : fmatrix m n) {i i' : fin m} {j j': fin n} (x : ℚ) (h : i' ≠ i ∨ j' ≠ j) : (A.write i j x).read i' j' = A.read i' j' := array.read_write_of_ne _ _ (by rwa [ne.def, fin.pair_eq_pair, not_and_distrib]) def foreach_aux (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : Π (i : ℕ) (j : ℕ) (hi : i ≤ m) (hj : j ≤ n), fmatrix m n | 0 j := λ hi hj, A | (i+1) 0 := λ hi hj, foreach_aux i n (nat.le_of_succ_le hi) (le_refl _) | (i+1) (j+1) := λ hi hj, (foreach_aux (i+1) j hi (nat.le_of_succ_le hj)).write ⟨i, hi⟩ ⟨j, hj⟩ (f ⟨i, hi⟩ ⟨j, hj⟩ (A.read ⟨i, hi⟩ ⟨j, hj⟩)) def foreach (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : fmatrix m n := foreach_aux A f m n (le_refl _) (le_refl _) lemma read_foreach_aux (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : Π (i : ℕ) (j : ℕ) (hi : i ≤ m) (hj : j ≤ n) (i' : fin m) (j' : fin n) (hij' : i'.1 + 1 < i ∨ (i'.1 + 1 = i ∧ j'.1 < j)), (A.foreach_aux f i j hi hj).read i' j' = f i' j' (A.read i' j') | 0 j := λ hi hj i' j' hij', hij'.elim (λ hi', (nat.not_lt_zero _ hi').elim) (λ hij', (nat.succ_ne_zero _ hij'.1).elim) | (i+1) 0 := λ hi hj i' j' hij', hij'.elim (λ hi', begin rw [foreach_aux, read_foreach_aux], cases lt_or_eq_of_le (nat.le_of_lt_succ hi') with hi' hi', { exact or.inl hi' }, { exact or.inr ⟨hi', j'.2⟩ } end) (λ hij', (nat.not_lt_zero _ hij'.2).elim) | (i+1) (j+1) := λ hi hj i' j' hij', begin rw [foreach_aux], dsimp only, by_cases hij : i' = ⟨i, hi⟩ ∧ j' = ⟨j, hj⟩, { rw [hij.1, hij.2, read_write] }, { rw not_and_distrib at hij, rw [read_write_of_ne _ _ hij, read_foreach_aux], cases hij' with hi' hij', { exact or.inl hi' }, { exact or.inr ⟨hij'.1, lt_of_le_of_ne (nat.le_of_lt_succ hij'.2) (fin.vne_of_ne (hij.resolve_left (not_not_intro (fin.eq_of_veq (nat.succ_inj hij'.1)))))⟩ } } end @[simp] lemma read_foreach (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) (i : fin m) (j : fin n) : (A.foreach f).read i j = f i j (A.read i j) := read_foreach_aux _ _ _ _ _ _ _ _ ((lt_or_eq_of_le (nat.succ_le_of_lt i.2)).elim or.inl (λ hi, or.inr ⟨hi, j.2⟩)) def write_column (A : fmatrix m n) (i : fin m) (f : fin n → ℚ) : fmatrix m n := (list.fin_range n).foldl (λ A j, A.write i j (f j)) A def to_matrix (A : fmatrix m n) : matrix (fin m) (fin n) ℚ | i j := A.read i j def of_matrix (A : matrix (fin m) (fin n) ℚ) : fmatrix m n := (0 : fmatrix m n).foreach (λ i j _, A i j) @[simp] lemma to_matrix_of_matrix (A : matrix (fin m) (fin n) ℚ) : (of_matrix A).to_matrix = A := by ext; simp [to_matrix, of_matrix] @[simp] lemma of_matrix_to_matrix (A : fmatrix m n) : of_matrix A.to_matrix = A := by ext; simp [of_matrix, to_matrix] def mul (B : fmatrix l m) (C : fmatrix m n) : fmatrix l n := let s : finset (fin m) := finset.univ in (0 : fmatrix l n).foreach (λ i j _, s.sum (λ k : fin m, B.read i k * C.read k j)) instance : has_mul (fmatrix n n) := ⟨mul⟩ instance : has_one (fmatrix n n) := ⟨(0 : fmatrix n n).foreach (λ i j _, if i = j then 1 else 0)⟩ instance : has_le (fmatrix m n) := ⟨λ A B, ∀ i, array.read A i ≤ array.read B i⟩ instance : decidable_rel ((≤) : fmatrix m n → fmatrix m n → Prop) := λ A B, show decidable (∀ i, array.read A i ≤ array.read B i), by apply_instance def mul₂ (M : fmatrix l m) (N : fmatrix m n) : fmatrix l n := array.foreach (0 : fmatrix l n) (λ x _, let i := fin.unpair₁ x in let k := fin.unpair₂ x in finset.univ.sum (λ j : fin m, M.read i j * N.read j k)) def equiv_matrix : fmatrix m n ≃ matrix (fin m) (fin n) ℚ := { to_fun := to_matrix, inv_fun := of_matrix, left_inv := of_matrix_to_matrix, right_inv := to_matrix_of_matrix } lemma to_matrix_add (A B : fmatrix m n) : (A + B).to_matrix = A.to_matrix + B.to_matrix := by ext; simp [to_matrix, fmatrix.read, add_def, array.read_map₂] lemma to_matrix_mul (A : fmatrix l m) (B : fmatrix m n) : (A.mul B).to_matrix = A.to_matrix.mul B.to_matrix := by ext; simp [to_matrix, matrix.mul, fmatrix.mul] end fmatrix -- #eval (fmatrix.mul (show fmatrix 50 50 ℚ, from ((list.range 2500).map nat.cast).to_array)) -- (show fmatrix 50 50 ℚ, from ((list.range 2500).map nat.cast).to_array)) -- #eval let m := 213 in let n := 100 in -- let l : array (m * n) ℚ := unchecked_cast (list.to_array (((list.range (m * n)).map -- (rat.of_int ∘ int.of_nat: ℕ → ℚ)))) in -- array.to_list -- (fmatrix.mul(show fmatrix m n, from unchecked_cast l) -- (show fmatrix n m , from unchecked_cast l))
47634fe57b8b2cadbed0b939f352fc3992824128
46125763b4dbf50619e8846a1371029346f4c3db
/src/order/filter/lift.lean
b502ffb4db2584c6473f0540674e7f2fa441ab29
[ "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
16,566
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Lift filters along filter and set functions. -/ import order.filter.basic open lattice set open_locale classical namespace filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*} section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. This is essentially a push-forward along a function mapping each set to a filter. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ f.lift g ↔ ∃t∈f, s ∈ g t := mem_binfi (assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩) ⟨univ, univ_mem_sets⟩ lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f) (hs : s ∈ g t) : s ∈ f.lift g := le_principal_iff.mp $ show f.lift g ≤ principal s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : g s ≤ h) : f.lift g ≤ h := infi_le_of_le s $ infi_le_of_le hs $ hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} (hh : ∀s∈f, h ≤ g s) : h ≤ f.lift g := le_infi $ assume s, le_infi $ assume hs, hh s hs lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from map_mono.comp hg, filter_eq $ set.ext $ by simp only [mem_lift_sets hg, mem_lift_sets this, exists_prop, forall_const, mem_map, iff_self, function.comp_app] lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) := have monotone (comap m ∘ g), from comap_mono.comp hg, filter_eq $ set.ext begin simp only [mem_lift_sets hg, mem_lift_sets this, comap, mem_lift_sets, mem_set_of_eq, exists_prop, function.comp_apply], exact λ s, ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩ end theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (comap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨preimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' preimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (principal s).lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_ne_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f, g s ≠ ⊥) := begin rw [filter.lift, infi_subtype', infi_ne_bot_iff_of_directed', subtype.forall'], { exact ⟨⟨univ, univ_mem_sets⟩⟩ }, { rintros ⟨s, hs⟩ ⟨t, ht⟩, exact ⟨⟨s ∩ t, inter_mem_sets hs ht⟩, hm (inter_subset_left s t), hm (inter_subset_right s t)⟩ } end @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g) @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp only [filter.lift, infi_inf_eq, eq_self_iff_true] @[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff]) lemma lift_infi {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f), (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), begin simp only [mem_lift_sets g_mono, exists_imp_distrib], exact assume t ht hs, this t ht hs end) end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`. This is essentially a push-forward along a function mapping each set to a set. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (principal ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f) : h t ∈ (f.lift' h) := le_principal_iff.mp $ show f.lift' h ≤ principal (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h) ↔ (∃t∈f, h t ⊆ s) := mem_lift_sets $ monotone_principal.comp hh lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : principal (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) : map_lift_eq $ monotone_principal.comp hh ... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_principal.comp hg theorem comap_lift'_eq {m : γ → β} (hh : monotone h) : comap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc comap m (f.lift' h) = f.lift (comap m ∘ principal ∘ h) : comap_lift_eq $ monotone_principal.comp hh ... = f.lift' (preimage m ∘ h) : by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true] theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (comap m f).lift' g = f.lift' (g ∘ preimage m) := comap_lift_eq2 $ monotone_principal.comp hg lemma lift'_principal {s : set α} (hh : monotone h) : (principal s).lift' h = principal (h s) := lift_principal $ monotone_principal.comp hh lemma principal_le_lift' {t : set β} (hh : ∀s∈f, t ⊆ h s) : principal t ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs) theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) : lift_assoc (monotone_principal.comp hg) ... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_principal.comp hh) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_principal.comp (hg₁ s)) (assume t, monotone_principal.comp (hg₂ t)) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) := le_antisymm (le_infi $ assume t, le_infi $ assume ht, calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s : inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _) ... = _ : by simp only [principal_eq_iff_eq, inf_principal, eq_self_iff_true, function.comp_app]) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp only [le_principal_iff, inter_subset_left, mem_principal_sets, function.comp_app]; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp only [le_principal_iff, inter_subset_right, mem_principal_sets, function.comp_app]; exact inter_subset_left _ _)) lemma lift'_ne_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f, (h s).nonempty) := calc (f.lift' h ≠ ⊥) ↔ (∀s∈f, principal (h s) ≠ ⊥) : lift_ne_bot_iff (monotone_principal.comp hh) ... ↔ (∀s∈f, (h s).nonempty) : by simp only [principal_ne_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f, h s ∈ g) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp only [h_le, le_principal_iff, function.comp_app]; exact h_le s hs lemma lift_infi' {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw mem_lift_sets hg, simp only [exists_imp_distrib, mem_infi hf hι], exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} (hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) := lift_infi hι $ by simp only [principal_eq_iff_eq, inf_principal, function.comp_app]; apply assume s t, hg theorem comap_eq_lift' {f : filter β} {m : α → β} : comap m f = f.lift' (preimage m) := filter_eq $ set.ext $ by simp only [mem_lift'_sets, monotone_preimage, comap, exists_prop, forall_const, iff_self, mem_set_of_eq] end lift' section prod variables {f : filter α} lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) := have ∀(s:set α) (t : set β), principal (set.prod s t) = (principal s).comap prod.fst ⊓ (principal t).comap prod.snd, by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl, begin simp only [filter.lift', function.comp, this, -comap_principal, lift_inf, lift_const, lift_inf], rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal], simp only [filter.prod, lift_principal2, eq_self_iff_true] end lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) := by rw [prod_def]; from lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ filter.prod f f ↔ (∃t∈f, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (filter.prod x x) y ↔ ∀ W ∈ y, ∃ U ∈ x, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self] variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} lemma prod_lift_lift {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) := begin simp only [prod_def], rw [lift_assoc], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) := begin rw [prod_def, lift_lift'_assoc], apply congr_arg, funext x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end end prod end filter
68060cd8ad0b11aff5e350ff697d9858c98ba9ef
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Parser/Term.lean
c4c47dfe6ac08c80e2e3a8dd52e869058c6924e8
[ "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
20,528
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Attr import Lean.Parser.Level namespace Lean namespace Parser namespace Command def commentBody : Parser := { fn := rawFn (finishCommentBlock 1) (trailingWs := true) } @[combinatorParenthesizer Lean.Parser.Command.commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken @[combinatorFormatter Lean.Parser.Command.commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous def docComment := leading_parser ppDedent $ "/--" >> ppSpace >> commentBody >> ppLine end Command builtin_initialize registerBuiltinParserAttribute `builtinTacticParser `tactic LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `tacticParser `tactic @[inline] def tacticParser (rbp : Nat := 0) : Parser := categoryParser `tactic rbp @[inline] def convParser (rbp : Nat := 0) : Parser := categoryParser `conv rbp namespace Tactic def tacticSeq1Indented : Parser := leading_parser many1Indent (group (ppLine >> tacticParser >> optional ";")) def tacticSeqBracketed : Parser := leading_parser "{" >> many (group (ppLine >> tacticParser >> optional ";")) >> ppDedent (ppLine >> "}") def tacticSeq := nodeWithAntiquot "tacticSeq" `Lean.Parser.Tactic.tacticSeq (tacticSeqBracketed <|> tacticSeq1Indented) /- Raw sequence for quotation and grouping -/ def seq1 := node `Lean.Parser.Tactic.seq1 $ sepBy1 tacticParser ";\n" (allowTrailingSep := true) end Tactic def darrow : Parser := " => " namespace Term /- Built-in parsers -/ @[builtinTermParser] def byTactic := leading_parser:leadPrec ppAllowUngrouped >> "by " >> Tactic.tacticSeq def optSemicolon (p : Parser) : Parser := ppDedent $ optional ";" >> ppLine >> p -- `checkPrec` necessary for the pretty printer @[builtinTermParser] def ident := checkPrec maxPrec >> Parser.ident @[builtinTermParser] def num : Parser := checkPrec maxPrec >> numLit @[builtinTermParser] def scientific : Parser := checkPrec maxPrec >> scientificLit @[builtinTermParser] def str : Parser := checkPrec maxPrec >> strLit @[builtinTermParser] def char : Parser := checkPrec maxPrec >> charLit @[builtinTermParser] def type := leading_parser "Type" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) @[builtinTermParser] def sort := leading_parser "Sort" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) @[builtinTermParser] def prop := leading_parser "Prop" @[builtinTermParser] def hole := leading_parser "_" @[builtinTermParser] def syntheticHole := leading_parser "?" >> (ident <|> hole) @[builtinTermParser] def «sorry» := leading_parser "sorry" @[builtinTermParser] def cdot := leading_parser symbol "·" <|> "." def typeAscription := leading_parser " : " >> termParser def tupleTail := leading_parser ", " >> sepBy1 termParser ", " def parenSpecial : Parser := optional (tupleTail <|> typeAscription) @[builtinTermParser] def paren := leading_parser "(" >> (withoutPosition (withoutForbidden (optional (ppDedentIfGrouped termParser >> parenSpecial)))) >> ")" @[builtinTermParser] def anonymousCtor := leading_parser "⟨" >> sepBy termParser ", " >> "⟩" def optIdent : Parser := optional (atomic (ident >> " : ")) def fromTerm := leading_parser " from " >> termParser def sufficesDecl := leading_parser optIdent >> termParser >> (fromTerm <|> byTactic) @[builtinTermParser] def «suffices» := leading_parser:leadPrec withPosition ("suffices " >> sufficesDecl) >> optSemicolon termParser @[builtinTermParser] def «show» := leading_parser:leadPrec "show " >> termParser >> (fromTerm <|> byTactic) def structInstArrayRef := leading_parser "[" >> termParser >>"]" def structInstLVal := leading_parser (ident <|> fieldIdx <|> structInstArrayRef) >> many (group ("." >> (ident <|> fieldIdx)) <|> structInstArrayRef) def structInstField := ppGroup $ leading_parser structInstLVal >> " := " >> termParser def structInstFieldAbbrev := leading_parser atomic (ident >> notFollowedBy ("." <|> ":=" <|> symbol "[") "invalid field abbreviation") -- `x` is an abbreviation for `x := x` def optEllipsis := leading_parser optional ".." @[builtinTermParser] def structInst := leading_parser "{" >> ppHardSpace >> optional (atomic (sepBy1 termParser ", " >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optEllipsis >> optional (" : " >> termParser) >> " }" def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec @[builtinTermParser] def explicit := leading_parser "@" >> termParser maxPrec @[builtinTermParser] def inaccessible := leading_parser ".(" >> termParser >> ")" def binderIdent : Parser := ident <|> hole def binderType (requireType := false) : Parser := if requireType then node nullKind (" : " >> termParser) else optional (" : " >> termParser) def binderTactic := leading_parser atomic (symbol " := " >> " by ") >> Tactic.tacticSeq def binderDefault := leading_parser " := " >> termParser def explicitBinder (requireType := false) := ppGroup $ leading_parser "(" >> many1 binderIdent >> binderType requireType >> optional (binderTactic <|> binderDefault) >> ")" def implicitBinder (requireType := false) := ppGroup $ leading_parser "{" >> many1 binderIdent >> binderType requireType >> "}" def strictImplicitLeftBracket := atomic (group (symbol "{" >> "{")) <|> "⦃" def strictImplicitRightBracket := atomic (group (symbol "}" >> "}")) <|> "⦄" def strictImplicitBinder (requireType := false) := ppGroup $ leading_parser strictImplicitLeftBracket >> many1 binderIdent >> binderType requireType >> strictImplicitRightBracket def instBinder := ppGroup $ leading_parser "[" >> optIdent >> termParser >> "]" def bracketedBinder (requireType := false) := withAntiquot (mkAntiquot "bracketedBinder" none (anonymous := false)) <| explicitBinder requireType <|> strictImplicitBinder requireType <|> implicitBinder requireType <|> instBinder /- It is feasible to support dependent arrows such as `{α} → α → α` without sacrificing the quality of the error messages for the longer case. `{α} → α → α` would be short for `{α : Type} → α → α` Here is the encoding: ``` def implicitShortBinder := node `Lean.Parser.Term.implicitBinder $ "{" >> many1 binderIdent >> pushNone >> "}" def depArrowShortPrefix := try (implicitShortBinder >> unicodeSymbol " → " " -> ") def depArrowLongPrefix := bracketedBinder true >> unicodeSymbol " → " " -> " def depArrowPrefix := depArrowShortPrefix <|> depArrowLongPrefix @[builtinTermParser] def depArrow := leading_parser depArrowPrefix >> termParser ``` Note that no changes in the elaborator are needed. We decided to not use it because terms such as `{α} → α → α` may look too cryptic. Note that we did not add a `explicitShortBinder` parser since `(α) → α → α` is really cryptic as a short for `(α : Type) → α → α`. -/ @[builtinTermParser] def depArrow := leading_parser:25 bracketedBinder true >> unicodeSymbol " → " " -> " >> termParser def simpleBinder := leading_parser many1 binderIdent >> optType @[builtinTermParser] def «forall» := leading_parser:leadPrec unicodeSymbol "∀" "forall" >> many1 (ppSpace >> (simpleBinder <|> bracketedBinder)) >> ", " >> termParser def matchAlt (rhsParser : Parser := termParser) : Parser := nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ "| " >> ppIndent (sepBy1 termParser ", " >> darrow >> checkColGe "alternative right-hand-side to start in a column greater than or equal to the corresponding '|'" >> rhsParser) /-- Useful for syntax quotations. Note that generic patterns such as `` `(matchAltExpr| | ... => $rhs) `` should also work with other `rhsParser`s (of arity 1). -/ def matchAltExpr := matchAlt def matchAlts (rhsParser : Parser := termParser) : Parser := leading_parser withPosition $ many1Indent (ppLine >> matchAlt rhsParser) def matchDiscr := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def trueVal := leading_parser nonReservedSymbol "true" def falseVal := leading_parser nonReservedSymbol "false" def generalizingParam := leading_parser atomic ("(" >> nonReservedSymbol "generalizing") >> " := " >> (trueVal <|> falseVal) >> ")" @[builtinTermParser] def «match» := leading_parser:leadPrec "match " >> optional generalizingParam >> sepBy1 matchDiscr ", " >> optType >> " with " >> ppDedent matchAlts @[builtinTermParser] def «nomatch» := leading_parser:leadPrec "nomatch " >> termParser def funImplicitBinder := atomic (lookahead ("{" >> many1 binderIdent >> (symbol " : " <|> "}"))) >> implicitBinder def funStrictImplicitBinder := atomic (lookahead (strictImplicitLeftBracket >> many1 binderIdent >> (symbol " : " <|> strictImplicitRightBracket))) >> strictImplicitBinder def funSimpleBinder := atomic (lookahead (many1 binderIdent >> " : ")) >> simpleBinder def funBinder : Parser := funStrictImplicitBinder <|> funImplicitBinder <|> instBinder <|> funSimpleBinder <|> termParser maxPrec -- NOTE: we use `nodeWithAntiquot` to ensure that `fun $b => ...` remains a `term` antiquotation def basicFun : Parser := nodeWithAntiquot "basicFun" `Lean.Parser.Term.basicFun (ppGroup (many1 (ppSpace >> funBinder) >> " =>") >> ppSpace >> termParser) @[builtinTermParser] def «fun» := leading_parser:maxPrec ppAllowUngrouped >> unicodeSymbol "λ" "fun" >> (basicFun <|> matchAlts) def optExprPrecedence := optional (atomic ":" >> termParser maxPrec) @[builtinTermParser] def «leading_parser» := leading_parser:leadPrec "leading_parser " >> optExprPrecedence >> termParser @[builtinTermParser] def «trailing_parser» := leading_parser:leadPrec "trailing_parser " >> optExprPrecedence >> optExprPrecedence >> termParser @[builtinTermParser] def borrowed := leading_parser "@& " >> termParser leadPrec @[builtinTermParser] def quotedName := leading_parser nameLit -- use `rawCh` because ``"`" >> ident`` overlaps with `nameLit`, with the latter being preferred by the tokenizer -- note that we cannot use ```"``"``` as a new token either because it would break `precheckedQuot` @[builtinTermParser] def doubleQuotedName := leading_parser "`" >> checkNoWsBefore >> rawCh '`' (trailingWs := false) >> ident def simpleBinderWithoutType := nodeWithAntiquot "simpleBinder" `Lean.Parser.Term.simpleBinder (anonymous := true) (many1 binderIdent >> pushNone) /- Remark: we use `checkWsBefore` to ensure `let x[i] := e; b` is not parsed as `let x [i] := e; b` where `[i]` is an `instBinder`. -/ def letIdLhs : Parser := ident >> notFollowedBy (checkNoWsBefore "" >> "[") "space is required before instance '[...]' binders to distinguish them from array updates `let x[i] := e; ...`" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType def letIdDecl := nodeWithAntiquot "letIdDecl" `Lean.Parser.Term.letIdDecl $ atomic (letIdLhs >> " := ") >> termParser def letPatDecl := nodeWithAntiquot "letPatDecl" `Lean.Parser.Term.letPatDecl $ atomic (termParser >> pushNone >> optType >> " := ") >> termParser /- Remark: the following `(" := " <|> matchAlts)` is a hack we use to produce a better error message at `letDecl`. Consider this following example ``` def myFun (n : Nat) : IO Nat := let q ← (10 : Nat) n + q ``` Without the hack, we get the error `expected '|'` at `←`. Reason: at `letDecl`, we use the parser `(letIdDecl <|> letPatDecl <|> letEqnsDecl)`, `letIdDecl` and `letEqnsDecl` have the same prefix `letIdLhs`, but `letIdDecl` uses `atomic`. Note that the hack relies on the fact that the parser `":="` never succeeds at `(" := " <|> matchAlts)`. It is there just to make sure we produce the error `expected ':=' or '|'` -/ def letEqnsDecl := nodeWithAntiquot "letEqnsDecl" `Lean.Parser.Term.letEqnsDecl $ letIdLhs >> (" := " <|> matchAlts) -- Remark: we use `nodeWithAntiquot` here to make sure anonymous antiquotations (e.g., `$x`) are not `letDecl` def letDecl := nodeWithAntiquot "letDecl" `Lean.Parser.Term.letDecl (notFollowedBy (nonReservedSymbol "rec") "rec" >> (letIdDecl <|> letPatDecl <|> letEqnsDecl)) @[builtinTermParser] def «let» := leading_parser:leadPrec withPosition ("let " >> letDecl) >> optSemicolon termParser @[builtinTermParser] def «let_fun» := leading_parser:leadPrec withPosition ((symbol "let_fun " <|> "let_λ") >> letDecl) >> optSemicolon termParser @[builtinTermParser] def «let_delayed» := leading_parser:leadPrec withPosition ("let_delayed " >> letDecl) >> optSemicolon termParser -- `let`-declaration that is only included in the elaborated term if variable is still there @[builtinTermParser] def «let_tmp» := leading_parser:leadPrec withPosition ("let_tmp " >> letDecl) >> optSemicolon termParser -- like `let_fun` but with optional name def haveIdLhs := optional (ident >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder))) >> optType def haveIdDecl := nodeWithAntiquot "haveIdDecl" `Lean.Parser.Term.haveIdDecl $ atomic (haveIdLhs >> " := ") >> termParser def haveEqnsDecl := nodeWithAntiquot "haveEqnsDecl" `Lean.Parser.Term.haveEqnsDecl $ haveIdLhs >> matchAlts def haveDecl := nodeWithAntiquot "haveDecl" `Lean.Parser.Term.haveDecl (haveIdDecl <|> letPatDecl <|> haveEqnsDecl) @[builtinTermParser] def «have» := leading_parser:leadPrec withPosition ("have " >> haveDecl) >> optSemicolon termParser def «scoped» := leading_parser "scoped " def «local» := leading_parser "local " def attrKind := leading_parser optional («scoped» <|> «local») def attrInstance := ppGroup $ leading_parser attrKind >> attrParser def attributes := leading_parser "@[" >> sepBy1 attrInstance ", " >> "]" def letRecDecl := leading_parser optional Command.docComment >> optional «attributes» >> letDecl def letRecDecls := leading_parser sepBy1 letRecDecl ", " @[builtinTermParser] def «letrec» := leading_parser:leadPrec withPosition (group ("let " >> nonReservedSymbol "rec ") >> letRecDecls) >> optSemicolon termParser @[runBuiltinParserAttributeHooks] def whereDecls := leading_parser " where" >> many1Indent (ppLine >> ppGroup (group (letRecDecl >> optional ";"))) @[runBuiltinParserAttributeHooks] def matchAltsWhereDecls := leading_parser matchAlts >> optional whereDecls @[builtinTermParser] def noindex := leading_parser "no_index " >> termParser maxPrec @[builtinTermParser] def binrel := leading_parser "binrel% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec /-- Similar to `binrel`, but coerse `Prop` arguments into `Bool`. -/ @[builtinTermParser] def binrel_no_prop := leading_parser "binrel_no_prop% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def binop := leading_parser "binop% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def binop_lazy := leading_parser "binop_lazy% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def forInMacro := leading_parser "for_in% " >> termParser maxPrec >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def typeOf := leading_parser "type_of% " >> termParser maxPrec @[builtinTermParser] def ensureTypeOf := leading_parser "ensure_type_of% " >> termParser maxPrec >> strLit >> termParser @[builtinTermParser] def ensureExpectedType := leading_parser "ensure_expected_type% " >> strLit >> termParser maxPrec @[builtinTermParser] def noImplicitLambda := leading_parser "no_implicit_lambda% " >> termParser maxPrec @[builtinTermParser] def letMVar := leading_parser "let_mvar% " >> "?" >> ident >> " := " >> termParser >> "; " >> termParser @[builtinTermParser] def waitIfTypeMVar := leading_parser "wait_if_type_mvar% " >> "?" >> ident >> "; " >> termParser @[builtinTermParser] def waitIfTypeContainsMVar := leading_parser "wait_if_type_contains_mvar% " >> "?" >> ident >> "; " >> termParser @[builtinTermParser] def waitIfContainsMVar := leading_parser "wait_if_contains_mvar% " >> "?" >> ident >> "; " >> termParser def namedArgument := leading_parser atomic ("(" >> ident >> " := ") >> termParser >> ")" def ellipsis := leading_parser ".." def argument := checkWsBefore "expected space" >> checkColGt "expected to be indented" >> (namedArgument <|> ellipsis <|> termParser argPrec) -- `app` precedence is `lead` (cannot be used as argument) -- `lhs` precedence is `max` (i.e. does not accept `arg` precedence) -- argument precedence is `arg` (i.e. does not accept `lead` precedence) @[builtinTermParser] def app := trailing_parser:leadPrec:maxPrec many1 argument @[builtinTermParser] def proj := trailing_parser checkNoWsBefore >> "." >> checkNoWsBefore >> (fieldIdx <|> ident) @[builtinTermParser] def completion := trailing_parser checkNoWsBefore >> "." @[builtinTermParser] def arrayRef := trailing_parser checkNoWsBefore >> "[" >> termParser >>"]" @[builtinTermParser] def arrow := trailing_parser checkPrec 25 >> unicodeSymbol " → " " -> " >> termParser 25 def isIdent (stx : Syntax) : Bool := -- antiquotations should also be allowed where an identifier is expected stx.isAntiquot || stx.isIdent @[builtinTermParser] def explicitUniv : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '.{'" >> ".{" >> sepBy1 levelParser ", " >> "}" @[builtinTermParser] def namedPattern : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '@'" >> "@" >> termParser maxPrec @[builtinTermParser] def pipeProj := trailing_parser:minPrec " |>." >> checkNoWsBefore >> (fieldIdx <|> ident) >> many argument @[builtinTermParser] def pipeCompletion := trailing_parser:minPrec " |>." @[builtinTermParser] def subst := trailing_parser:75 " ▸ " >> sepBy1 (termParser 75) " ▸ " -- NOTE: Doesn't call `categoryParser` directly in contrast to most other "static" quotations, so call `evalInsideQuot` explicitly @[builtinTermParser] def funBinder.quot : Parser := leading_parser "`(funBinder|" >> incQuotDepth (evalInsideQuot ``funBinder funBinder) >> ")" def bracketedBinderF := bracketedBinder -- no default arg @[builtinTermParser] def bracketedBinder.quot : Parser := leading_parser "`(bracketedBinder|" >> incQuotDepth (evalInsideQuot ``bracketedBinderF bracketedBinder) >> ")" @[builtinTermParser] def matchDiscr.quot : Parser := leading_parser "`(matchDiscr|" >> incQuotDepth (evalInsideQuot ``matchDiscr matchDiscr) >> ")" @[builtinTermParser] def attr.quot : Parser := leading_parser "`(attr|" >> incQuotDepth attrParser >> ")" @[builtinTermParser] def panic := leading_parser:leadPrec "panic! " >> termParser @[builtinTermParser] def unreachable := leading_parser:leadPrec "unreachable!" @[builtinTermParser] def dbgTrace := leading_parser:leadPrec withPosition ("dbg_trace" >> ((interpolatedStr termParser) <|> termParser)) >> optSemicolon termParser @[builtinTermParser] def assert := leading_parser:leadPrec withPosition ("assert! " >> termParser) >> optSemicolon termParser def macroArg := termParser maxPrec def macroDollarArg := leading_parser "$" >> termParser 10 def macroLastArg := macroDollarArg <|> macroArg -- Macro for avoiding exponentially big terms when using `STWorld` @[builtinTermParser] def stateRefT := leading_parser "StateRefT" >> macroArg >> macroLastArg @[builtinTermParser] def dynamicQuot := leading_parser "`(" >> ident >> "|" >> incQuotDepth (parserOfStack 1) >> ")" end Term @[builtinTermParser default+1] def Tactic.quot : Parser := leading_parser "`(tactic|" >> incQuotDepth tacticParser >> ")" @[builtinTermParser] def Tactic.quotSeq : Parser := leading_parser "`(tactic|" >> incQuotDepth Tactic.seq1 >> ")" @[builtinTermParser] def Level.quot : Parser := leading_parser "`(level|" >> incQuotDepth levelParser >> ")" open Term in builtin_initialize register_parser_alias letDecl register_parser_alias haveDecl register_parser_alias sufficesDecl register_parser_alias letRecDecls register_parser_alias hole register_parser_alias syntheticHole register_parser_alias matchDiscr register_parser_alias bracketedBinder register_parser_alias attrKind end Parser end Lean
dc4d2e6b67588c8f24c098cfc77e794e04f3c71a
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/algebra/lie/classical.lean
44d52e5bc4a2111caf462deebb37e4fe66f08f50
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,506
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.invertible import algebra.lie.skew_adjoint import linear_algebra.matrix /-! # Classical Lie algebras This file is the place to find definitions and basic properties of the classical Lie algebras: * Aₗ = sl(l+1) * Bₗ ≃ so(l+1, l) ≃ so(2l+1) * Cₗ = sp(l) * Dₗ ≃ so(l, l) ≃ so(2l) ## Main definitions * `lie_algebra.special_linear.sl` * `lie_algebra.symplectic.sp` * `lie_algebra.orthogonal.so` * `lie_algebra.orthogonal.so'` * `lie_algebra.orthogonal.so_indefinite_equiv` * `lie_algebra.orthogonal.type_D` * `lie_algebra.orthogonal.type_B` * `lie_algebra.orthogonal.type_D_equiv_so'` * `lie_algebra.orthogonal.type_B_equiv_so'` ## Implementation notes ### Matrices or endomorphisms Given a finite type and a commutative ring, the corresponding square matrices are equivalent to the endomorphisms of the corresponding finite-rank free module as Lie algebras, see `lie_equiv_matrix'`. We can thus define the classical Lie algebras as Lie subalgebras either of matrices or of endomorphisms. We have opted for the former. At the time of writing (August 2020) it is unclear which approach should be preferred so the choice should be assumed to be somewhat arbitrary. ### Diagonal quadratic form or diagonal Cartan subalgebra For the algebras of type `B` and `D`, there are two natural definitions. For example since the the `2l × 2l` matrix: $$ J = \left[\begin{array}{cc} 0_l & 1_l\\\\ 1_l & 0_l \end{array}\right] $$ defines a symmetric bilinear form equivalent to that defined by the identity matrix `I`, we can define the algebras of type `D` to be the Lie subalgebra of skew-adjoint matrices either for `J` or for `I`. Both definitions have their advantages (in particular the `J`-skew-adjoint matrices define a Lie algebra for which the diagonal matrices form a Cartan subalgebra) and so we provide both. We thus also provide equivalences `type_D_equiv_so'`, `so_indefinite_equiv` which show the two definitions are equivalent. Similarly for the algebras of type `B`. ## Tags classical lie algebra, special linear, symplectic, orthogonal -/ universes u₁ u₂ namespace lie_algebra open_locale matrix variables (n p q l : Type*) (R : Type u₂) variables [fintype n] [fintype l] [fintype p] [fintype q] variables [decidable_eq n] [decidable_eq p] [decidable_eq q] [decidable_eq l] variables [comm_ring R] @[simp] lemma matrix_trace_commutator_zero (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 := begin -- TODO: if we use matrix.mul here, we get a timeout change matrix.trace n R R (X * Y - Y * X) = 0, erw [linear_map.map_sub, matrix.trace_mul_comm, sub_self] end namespace special_linear /-- The special linear Lie algebra: square matrices of trace zero. -/ def sl : lie_subalgebra R (matrix n n R) := { lie_mem := λ X Y _ _, linear_map.mem_ker.2 $ matrix_trace_commutator_zero _ _ _ _, ..linear_map.ker (matrix.trace n R R) } lemma sl_bracket (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl section elementary_basis variables {n} (i j : n) /-- It is useful to define these matrices for explicit calculations in sl n R. -/ abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0 @[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl) @[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h @[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 := begin ext k, rw matrix.diag_apply, suffices : ¬(i = k ∧ j = k), by exact if_neg this, rintros ⟨e₁, e₂⟩, apply h, subst e₁, exact e₂, end lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h] /-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural basis of sl n R. -/ def Eb (h : j ≠ i) : sl n R := ⟨E R i j, by { change E R i j ∈ linear_map.ker (matrix.trace n R R), simp [E_trace_zero R i j h], }⟩ @[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl end elementary_basis lemma sl_non_abelian [nontrivial R] (h : 1 < fintype.card n) : ¬is_lie_abelian ↥(sl n R) := begin rcases fintype.exists_pair_of_one_lt_card h with ⟨j, i, hij⟩, let A := Eb R i j hij, let B := Eb R j i hij.symm, intros c, have c' : A.val ⬝ B.val = B.val ⬝ A.val := by { rw [←sub_eq_zero, ←sl_bracket, c.abelian], refl, }, have : (1 : R) = 0 := by simpa [matrix.mul_apply, hij] using (congr_fun (congr_fun c' i) i), exact one_ne_zero this, end end special_linear namespace symplectic /-- The matrix defining the canonical skew-symmetric bilinear form. -/ def J : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 (-1) 1 0 /-- The symplectic Lie algebra: skew-adjoint matrices with respect to the canonical skew-symmetric bilinear form. -/ def sp : lie_subalgebra R (matrix (l ⊕ l) (l ⊕ l) R) := skew_adjoint_matrices_lie_subalgebra (J l R) end symplectic namespace orthogonal /-- The definite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the identity matrix. -/ def so : lie_subalgebra R (matrix n n R) := skew_adjoint_matrices_lie_subalgebra (1 : matrix n n R) @[simp] lemma mem_so (A : matrix n n R) : A ∈ so n R ↔ Aᵀ = -A := begin erw mem_skew_adjoint_matrices_submodule, simp only [matrix.is_skew_adjoint, matrix.is_adjoint_pair, matrix.mul_one, matrix.one_mul], end /-- The indefinite diagonal matrix with `p` 1s and `q` -1s. -/ def indefinite_diagonal : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, -1) /-- The indefinite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the indefinite diagonal matrix. -/ def so' : lie_subalgebra R (matrix (p ⊕ q) (p ⊕ q) R) := skew_adjoint_matrices_lie_subalgebra $ indefinite_diagonal p q R /-- A matrix for transforming the indefinite diagonal bilinear form into the definite one, provided the parameter `i` is a square root of -1. -/ def Pso (i : R) : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, i) lemma Pso_inv {i : R} (hi : i*i = -1) : (Pso p q R i) * (Pso p q R (-i)) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end lemma is_unit_Pso {i : R} (hi : i*i = -1) : is_unit (Pso p q R i) := ⟨{ val := Pso p q R i, inv := Pso p q R (-i), val_inv := Pso_inv p q R hi, inv_val := by { apply matrix.nonsing_inv_left_right, exact Pso_inv p q R hi, }, }, rfl⟩ lemma indefinite_diagonal_transform {i : R} (hi : i*i = -1) : (Pso p q R i)ᵀ ⬝ (indefinite_diagonal p q R) ⬝ (Pso p q R i) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end /-- An equivalence between the indefinite and definite orthogonal Lie algebras, over a ring containing a square root of -1. -/ noncomputable def so_indefinite_equiv {i : R} (hi : i*i = -1) : so' p q R ≃ₗ⁅R⁆ so (p ⊕ q) R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (indefinite_diagonal p q R) (Pso p q R i) (is_unit_Pso p q R hi)).trans, apply lie_algebra.equiv.of_eq, ext A, rw indefinite_diagonal_transform p q R hi, refl, end lemma so_indefinite_equiv_apply {i : R} (hi : i*i = -1) (A : so' p q R) : (so_indefinite_equiv p q R hi A : matrix (p ⊕ q) (p ⊕ q) R) = (Pso p q R i)⁻¹ ⬝ (A : matrix (p ⊕ q) (p ⊕ q) R) ⬝ (Pso p q R i) := by erw [lie_algebra.equiv.trans_apply, lie_algebra.equiv.of_eq_apply, skew_adjoint_matrices_lie_subalgebra_equiv_apply] /-- A matrix defining a canonical even-rank symmetric bilinear form. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 0 1 ] [ 1 0 ] -/ def JD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 1 1 0 /-- The classical Lie algebra of type D as a Lie subalgebra of matrices associated to the matrix `JD`. -/ def type_D := skew_adjoint_matrices_lie_subalgebra (JD l R) /-- A matrix transforming the bilinear form defined by the matrix `JD` into a split-signature diagonal matrix. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 1 -1 ] [ 1 1 ] -/ def PD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 1 (-1) 1 1 /-- The split-signature diagonal matrix. -/ def S := indefinite_diagonal l l R lemma S_as_blocks : S l R = matrix.from_blocks 1 0 0 (-1) := begin rw [← matrix.diagonal_one, matrix.diagonal_neg, matrix.from_blocks_diagonal], refl, end lemma JD_transform : (PD l R)ᵀ ⬝ (JD l R) ⬝ (PD l R) = (2 : R) • (S l R) := begin have h : (PD l R)ᵀ ⬝ (JD l R) = matrix.from_blocks 1 1 1 (-1) := by { simp [PD, JD, matrix.from_blocks_transpose, matrix.from_blocks_multiply], }, erw [h, S_as_blocks, matrix.from_blocks_multiply, matrix.from_blocks_smul], congr; simp [two_smul], end lemma PD_inv [invertible (2 : R)] : (PD l R) * (⅟(2 : R) • (PD l R)ᵀ) = 1 := begin have h : ⅟(2 : R) • (1 : matrix l l R) + ⅟(2 : R) • 1 = 1 := by rw [← smul_add, ← (two_smul R _), smul_smul, inv_of_mul_self, one_smul], erw [matrix.from_blocks_transpose, matrix.from_blocks_smul, matrix.mul_eq_mul, matrix.from_blocks_multiply], simp [h], end lemma is_unit_PD [invertible (2 : R)] : is_unit (PD l R) := ⟨{ val := PD l R, inv := ⅟(2 : R) • (PD l R)ᵀ, val_inv := PD_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PD_inv l R, }, }, rfl⟩ /-- An equivalence between two possible definitions of the classical Lie algebra of type D. -/ noncomputable def type_D_equiv_so' [invertible (2 : R)] : type_D l R ≃ₗ⁅R⁆ so' l l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JD l R) (PD l R) (is_unit_PD l R)).trans, apply lie_algebra.equiv.of_eq, ext A, rw [JD_transform, ← unit_of_invertible_val (2 : R), lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], refl, end /-- A matrix defining a canonical odd-rank symmetric bilinear form. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 2 0 0 ] [ 0 0 1 ] [ 0 1 0 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def JB := matrix.from_blocks ((2 : R) • 1 : matrix unit unit R) 0 0 (JD l R) /-- The classical Lie algebra of type B as a Lie subalgebra of matrices associated to the matrix `JB`. -/ def type_B := skew_adjoint_matrices_lie_subalgebra (JB l R) /-- A matrix transforming the bilinear form defined by the matrix `JB` into an almost-split-signature diagonal matrix. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 1 0 0 ] [ 0 1 -1 ] [ 0 1 1 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def PB := matrix.from_blocks (1 : matrix unit unit R) 0 0 (PD l R) lemma PB_inv [invertible (2 : R)] : (PB l R) * (matrix.from_blocks 1 0 0 (PD l R)⁻¹) = 1 := begin simp [PB, matrix.from_blocks_multiply, (PD l R).mul_nonsing_inv, is_unit_PD, ← (PD l R).is_unit_iff_is_unit_det] end lemma is_unit_PB [invertible (2 : R)] : is_unit (PB l R) := ⟨{ val := PB l R, inv := matrix.from_blocks 1 0 0 (PD l R)⁻¹, val_inv := PB_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PB_inv l R, }, }, rfl⟩ lemma JB_transform : (PB l R)ᵀ ⬝ (JB l R) ⬝ (PB l R) = (2 : R) • matrix.from_blocks 1 0 0 (S l R) := by simp [PB, JB, JD_transform, matrix.from_blocks_transpose, matrix.from_blocks_multiply, matrix.from_blocks_smul] lemma indefinite_diagonal_assoc : indefinite_diagonal (unit ⊕ l) l R = matrix.reindex_lie_equiv (equiv.sum_assoc unit l l).symm (matrix.from_blocks 1 0 0 (indefinite_diagonal l l R)) := begin ext i j, rcases i with ⟨⟨i₁ | i₂⟩ | i₃⟩; rcases j with ⟨⟨j₁ | j₂⟩ | j₃⟩; simp [indefinite_diagonal, matrix.diagonal], end /-- An equivalence between two possible definitions of the classical Lie algebra of type B. -/ noncomputable def type_B_equiv_so' [invertible (2 : R)] : type_B l R ≃ₗ⁅R⁆ so' (unit ⊕ l) l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JB l R) (PB l R) (is_unit_PB l R)).trans, symmetry, apply (skew_adjoint_matrices_lie_subalgebra_equiv_transpose (indefinite_diagonal (unit ⊕ l) l R) (matrix.reindex_alg_equiv (equiv.sum_assoc punit l l)) (matrix.reindex_transpose _ _)).trans, apply lie_algebra.equiv.of_eq, ext A, rw [JB_transform, ← unit_of_invertible_val (2 : R), lie_subalgebra.mem_coe, lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], simpa [indefinite_diagonal_assoc], end end orthogonal end lie_algebra
4bac7f4bab7459751190ad90c9ad2d5c121e7c7c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/unicode.lean
1c7b9b9b5015ca4b177d7decf26cf181d3175e4b
[ "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
202
lean
print true /\ false set_option pp::unicode false print true /\ false set_option pp::unicode true set_option lean::pp::notation false print true /\ false set_option pp::unicode false print true /\ false
5da40df3b61951702fc0bff437aa26fe5108a6dc
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/topology/metric_space/isometry.lean
26392d51f8620591e9d23473fd0aa9e032c6a442
[ "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
16,020
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Isometries of emetric and metric spaces Authors: Sébastien Gouëzel -/ import topology.bounded_continuous_function import topology.opens /-! # Isometries We define isometries, i.e., maps between emetric spaces that preserve the edistance (on metric spaces, these are exactly the maps that preserve distances), and prove their basic properties. We also introduce isometric bijections. -/ noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set /-- An isometry (also known as isometric embedding) is a map preserving the edistance between emetric spaces, or equivalently the distance between metric space. -/ def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop := ∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2 /-- On metric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} : isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) := ⟨assume H x y, by simp [dist_edist, H x y], assume H x y, by simp [edist_dist, H x y]⟩ /-- An isometry preserves edistances. -/ theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} (hf : isometry f) (x y : α) : edist (f x) (f y) = edist x y := hf x y /-- An isometry preserves distances. -/ theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) (x y : α) : dist (f x) (f y) = dist x y := by rw [dist_edist, dist_edist, hf] section emetric_isometry variables [emetric_space α] [emetric_space β] [emetric_space γ] variables {f : α → β} {x y z : α} {s : set α} lemma isometry.lipschitz (h : isometry f) : lipschitz_with 1 f := lipschitz_with.of_edist_le $ λ x y, le_of_eq (h x y) lemma isometry.antilipschitz (h : isometry f) : antilipschitz_with 1 f := λ x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl] /-- An isometry is injective -/ lemma isometry.injective (h : isometry f) : injective f := h.antilipschitz.injective /-- Any map on a subsingleton is an isometry -/ theorem isometry_subsingleton [subsingleton α] : isometry f := λx y, by rw subsingleton.elim x y; simp /-- The identity is an isometry -/ lemma isometry_id : isometry (id : α → α) := λx y, rfl /-- The composition of isometries is an isometry -/ theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) := assume x y, calc edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _ ... = edist x y : hf _ _ /-- An isometry is an embedding -/ theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f := hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous /-- An isometry is continuous. -/ lemma isometry.continuous (hf : isometry f) : continuous f := hf.lipschitz.continuous /-- The right inverse of an isometry is an isometry. -/ lemma isometry.right_inv {f : α → β} {g : β → α} (h : isometry f) (hg : right_inverse g f) : isometry g := λ x y, by rw [← h, hg _, hg _] /-- Isometries preserve the diameter in emetric spaces. -/ lemma isometry.ediam_image (hf : isometry f) (s : set α) : emetric.diam (f '' s) = emetric.diam s := eq_of_forall_ge_iff $ λ d, by simp only [emetric.diam_le_iff_forall_edist_le, ball_image_iff, hf.edist_eq] lemma isometry.ediam_range (hf : isometry f) : emetric.diam (range f) = emetric.diam (univ : set α) := by { rw ← image_univ, exact hf.ediam_image univ } /-- The injection from a subtype is an isometry -/ lemma isometry_subtype_val {s : set α} : isometry (subtype.val : s → α) := λx y, rfl end emetric_isometry --section /-- An isometry preserves the diameter in metric spaces. -/ lemma isometry.diam_image [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) (s : set α) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, hf.ediam_image] lemma isometry.diam_range [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) : metric.diam (range f) = metric.diam (univ : set α) := by { rw ← image_univ, exact hf.diam_image univ } /-- `α` and `β` are isometric if there is an isometric bijection between them. -/ structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β] extends α ≃ β := (isometry_to_fun : isometry to_fun) infix ` ≃ᵢ `:25 := isometric namespace isometric variables [emetric_space α] [emetric_space β] [emetric_space γ] instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun protected lemma edist_eq (h : α ≃ᵢ β) (x y : α) : edist (h x) (h y) = edist x y := h.isometry.edist_eq x y protected lemma dist_eq {α β : Type*} [metric_space α] [metric_space β] (h : α ≃ᵢ β) (x y : α) : dist (h x) (h y) = dist x y := h.isometry.dist_eq x y protected lemma continuous (h : α ≃ᵢ β) : continuous h := h.isometry.continuous lemma to_equiv_inj : ∀ ⦃h₁ h₂ : α ≃ᵢ β⦄, (h₁.to_equiv = h₂.to_equiv) → h₁ = h₂ | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ H := by { dsimp at H, subst e₁ } @[ext] lemma ext ⦃h₁ h₂ : α ≃ᵢ β⦄ (H : ∀ x, h₁ x = h₂ x) : h₁ = h₂ := to_equiv_inj $ equiv.ext _ _ H /-- Alternative constructor for isometric bijections, taking as input an isometry, and a right inverse. -/ def mk' (f : α → β) (g : β → α) (hfg : ∀ x, f (g x) = x) (hf : isometry f) : α ≃ᵢ β := { to_fun := f, inv_fun := g, left_inv := λ x, hf.injective $ hfg _, right_inv := hfg, isometry_to_fun := hf } /-- The identity isometry of a space. -/ protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α := { isometry_to_fun := isometry_id, .. equiv.refl α } /-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/ protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ := { isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } @[simp] lemma trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : α) : h₁.trans h₂ x = h₂ (h₁ x) := rfl /-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/ protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α := { isometry_to_fun := h.isometry.right_inv h.right_inv, to_equiv := h.to_equiv.symm } @[simp] lemma symm_symm (h : α ≃ᵢ β) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm @[simp] lemma apply_symm_apply (h : α ≃ᵢ β) (y : β) : h (h.symm y) = y := h.to_equiv.apply_symm_apply y @[simp] lemma symm_apply_apply (h : α ≃ᵢ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x lemma symm_apply_eq (h : α ≃ᵢ β) {x : α} {y : β} : h.symm y = x ↔ y = h x := h.to_equiv.symm_apply_eq lemma eq_symm_apply (h : α ≃ᵢ β) {x : α} {y : β} : x = h.symm y ↔ h x = y := h.to_equiv.eq_symm_apply lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ᵢ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm @[simp] lemma symm_trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : γ) : (h₁.trans h₂).symm x = h₁.symm (h₂.symm x) := rfl /-- The (bundled) homeomorphism associated to an isometric isomorphism. -/ protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β := { continuous_to_fun := h.continuous, continuous_inv_fun := h.symm.continuous, .. h } @[simp] lemma coe_to_homeomorph (h : α ≃ᵢ β) : ⇑(h.to_homeomorph) = h := rfl @[simp] lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) : h.to_homeomorph.to_equiv = h.to_equiv := rfl section normed_group variables {G : Type*} [normed_group G] /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : G) : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : G) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : G) : (isometric.add_right x : G → G) = λ y, y + x := rfl lemma add_right_apply (x y : G) : (isometric.add_right x : G → G) y = y + x := rfl @[simp] lemma add_right_symm (x : G) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : G) : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : G) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : G) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : G) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (G) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg G } variable {G} @[simp] lemma neg_symm : (isometric.neg G).symm = isometric.neg G := rfl @[simp] lemma neg_to_equiv : (isometric.neg G).to_equiv = equiv.neg G := rfl @[simp] lemma coe_neg : ⇑(isometric.neg G) = has_neg.neg := rfl end normed_group end isometric /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ def isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) : α ≃ᵢ range f := { isometry_to_fun := λx y, by simpa [subtype.edist_eq] using h x y, .. equiv.set.range f h.injective } @[simp] lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ := rfl /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq], end /-- The space of bounded sequences, with its sup norm -/ @[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ open bounded_continuous_function metric topological_space namespace Kuratowski_embedding /-! ### In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in the next definition, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _) lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine (dist_le dist_nonneg).2 (λn, _), have A : dist a (x n) + (dist (x 0) (x n) + (-dist b (x n) + -dist (x 0) (x n))) = dist a (x n) - dist b (x n), by ring, simp only [embedding_of_subset_coe, real.dist_eq, A, add_comm, neg_add_rev, _root_.neg_neg, sub_eq_add_neg, add_left_comm], exact abs_dist_sub_le _ _ _ end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : closure (range x) = univ) : isometry (embedding_of_subset x) := begin refine isometry_emetric_iff_metric.2 (λa b, _), refine le_antisymm (embedding_of_subset_dist_le x a b) (real.le_of_forall_epsilon_le (λe epos, _)), /- First step: find n with dist a (x n) < e -/ have A : a ∈ closure (range x), by { have B := mem_univ a, rwa [← H] at B }, rcases metric.mem_closure_range_iff.1 A (e/2) (half_pos epos) with ⟨n, hn⟩, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp [embedding_of_subset_coe, sub_eq_add_neg] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) : begin rw [C], apply_rules [add_le_add, mul_le_mul_of_nonneg_left, le_of_lt hn, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin rw [← coe_diff], apply add_le_add_left, rw [coe_diff, ←real.dist_eq], apply dist_coe_le_dist end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin cases (univ : set α).eq_empty_or_nonempty with h h, { use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) }, { /- We construct a map x : ℕ → α with dense image -/ rcases h with basepoint, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, countable s ∧ closure s = univ := separable_space.exists_countable_closure_eq_univ, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩, have : closure (range x) = univ := univ_subset_iff.1 (by { rw [← S_dense], apply closure_mono, assumption }), /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x this⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := ⟨range (Kuratowski_embedding α), range_nonempty _, compact_range (Kuratowski_embedding.isometry α).continuous⟩
4ad50b736fcc3fc175a48db4551fb204941a2e1c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/abelian/non_preadditive.lean
81a03ceb50a578ac4e736c8bb59ef4d7f9b685ff
[]
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
21,352
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.finite_products import Mathlib.category_theory.limits.shapes.kernels import Mathlib.category_theory.limits.shapes.normal_mono import Mathlib.category_theory.preadditive.default import Mathlib.PostPort universes v u l namespace Mathlib /-! # Every non_preadditive_abelian category is preadditive In mathlib, we define an abelian category as a preadditive category with a zero object, kernels and cokernels, products and coproducts and in which every monomorphism and epimorphis is normal. While virtually every interesting abelian category has a natural preadditive structure (which is why it is included in the definition), preadditivity is not actually needed: Every category that has all of the other properties appearing in the definition of an abelian category admits a preadditive structure. This is the construction we carry out in this file. The proof proceeds in roughly five steps: 1. Prove some results (for example that all equalizers exist) that would be trivial if we already had the preadditive structure but are a bit of work without it. 2. Develop images and coimages to show that every monomorphism is the kernel of its cokernel. The results of the first two steps are also useful for the "normal" development of abelian categories, and will be used there. 3. For every object `A`, define a "subtraction" morphism `σ : A ⨯ A ⟶ A` and use it to define subtraction on morphisms as `f - g := prod.lift f g ≫ σ`. 4. Prove a small number of identities about this subtraction from the definition of `σ`. 5. From these identities, prove a large number of other identities that imply that defining `f + g := f - (0 - g)` indeed gives an abelian group structure on morphisms such that composition is bilinear. The construction is non-trivial and it is quite remarkable that this abelian group structure can be constructed purely from the existence of a few limits and colimits. What's even more impressive is that all additive structures on a category are in some sense isomorphic, so for abelian categories with a natural preadditive structure, this construction manages to "almost" reconstruct this natural structure. However, we have not formalized this isomorphism. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ namespace category_theory /-- We call a category `non_preadditive_abelian` if it has a zero object, kernels, cokernels, binary products and coproducts, and every monomorphism and every epimorphism is normal. -/ class non_preadditive_abelian (C : Type u) [category C] where has_zero_object : limits.has_zero_object C has_zero_morphisms : limits.has_zero_morphisms C has_kernels : limits.has_kernels C has_cokernels : limits.has_cokernels C has_finite_products : limits.has_finite_products C has_finite_coproducts : limits.has_finite_coproducts C normal_mono : {X Y : C} → (f : X ⟶ Y) → [_inst_2 : mono f] → normal_mono f normal_epi : {X Y : C} → (f : X ⟶ Y) → [_inst_2 : epi f] → normal_epi f end category_theory namespace category_theory.non_preadditive_abelian /-- In a `non_preadditive_abelian` category, every epimorphism is strong. -/ theorem strong_epi_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := category_theory.strong_epi_of_regular_epi f /-- In a `non_preadditive_abelian` category, a monomorphism which is also an epimorphism is an isomorphism. -/ def is_iso_of_mono_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) [mono f] [epi f] : is_iso f := is_iso_of_mono_of_strong_epi f /-- The pullback of two monomorphisms exists. -/ theorem pullback_of_mono {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C} (a : X ⟶ Z) (b : Y ⟶ Z) [mono a] [mono b] : limits.has_limit (limits.cospan a b) := sorry /-- The pushout of two epimorphisms exists. -/ theorem pushout_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C} (a : X ⟶ Y) (b : X ⟶ Z) [epi a] [epi b] : limits.has_colimit (limits.span a b) := sorry /-- The pullback of `(𝟙 X, f)` and `(𝟙 X, g)` -/ /-- The equalizer of `f` and `g` exists. -/ theorem has_limit_parallel_pair {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : limits.has_limit (limits.parallel_pair f g) := sorry /-- The pushout of `(𝟙 Y, f)` and `(𝟙 Y, g)`. -/ /-- The coequalizer of `f` and `g` exists. -/ theorem has_colimit_parallel_pair {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : limits.has_colimit (limits.parallel_pair f g) := sorry /-- A `non_preadditive_abelian` category has all equalizers. -/ protected instance has_equalizers {C : Type u} [category C] [non_preadditive_abelian C] : limits.has_equalizers C := limits.has_equalizers_of_has_limit_parallel_pair C /-- A `non_preadditive_abelian` category has all coequalizers. -/ protected instance has_coequalizers {C : Type u} [category C] [non_preadditive_abelian C] : limits.has_coequalizers C := limits.has_coequalizers_of_has_colimit_parallel_pair C /-- If a zero morphism is a kernel of `f`, then `f` is a monomorphism. -/ theorem mono_of_zero_kernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (Z : C) (l : limits.is_limit (limits.kernel_fork.of_ι 0 ((fun (this : 0 ≫ f = 0) => this) (eq.mpr (id (Eq.trans ((fun (a a_1 : Z ⟶ Y) (e_1 : a = a_1) (ᾰ ᾰ_1 : Z ⟶ Y) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (0 ≫ f) 0 limits.zero_comp 0 0 (Eq.refl 0)) (propext (eq_self_iff_true 0)))) trivial)))) : mono f := sorry /-- If a zero morphism is a cokernel of `f`, then `f` is an epimorphism. -/ theorem epi_of_zero_cokernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (Z : C) (l : limits.is_colimit (limits.cokernel_cofork.of_π 0 ((fun (this : f ≫ 0 = 0) => this) (eq.mpr (id (Eq.trans ((fun (a a_1 : X ⟶ Z) (e_1 : a = a_1) (ᾰ ᾰ_1 : X ⟶ Z) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (f ≫ 0) 0 limits.comp_zero 0 0 (Eq.refl 0)) (propext (eq_self_iff_true 0)))) trivial)))) : epi f := sorry /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/ def zero_kernel_of_cancel_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X), g ≫ f = 0 → g = 0) : limits.is_limit (limits.kernel_fork.of_ι 0 (zero_kernel_of_cancel_zero._proof_1 f)) := limits.fork.is_limit.mk (limits.kernel_fork.of_ι 0 sorry) (fun (s : limits.fork f 0) => 0) sorry sorry /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/ def zero_cokernel_of_zero_cancel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z), f ≫ g = 0 → g = 0) : limits.is_colimit (limits.cokernel_cofork.of_π 0 (zero_cokernel_of_zero_cancel._proof_1 f)) := limits.cofork.is_colimit.mk (limits.cokernel_cofork.of_π 0 sorry) (fun (s : limits.cofork f 0) => 0) sorry sorry /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `f` is a monomorphism. -/ theorem mono_of_cancel_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X), g ≫ f = 0 → g = 0) : mono f := mono_of_zero_kernel f 0 (zero_kernel_of_cancel_zero f hf) /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `g` is a monomorphism. -/ theorem epi_of_zero_cancel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z), f ≫ g = 0 → g = 0) : epi f := epi_of_zero_cokernel f 0 (zero_cokernel_of_zero_cancel f hf) /-- The kernel of the cokernel of `f` is called the image of `f`. -/ protected def image {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : C := limits.kernel (limits.cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected def image.ι {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : non_preadditive_abelian.image f ⟶ Q := limits.kernel.ι (limits.cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected def factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : P ⟶ non_preadditive_abelian.image f := limits.kernel.lift (limits.cokernel.π f) f sorry /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp] theorem image.fac_assoc {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) {X' : C} (f' : Q ⟶ X') : non_preadditive_abelian.factor_thru_image f ≫ image.ι f ≫ f' = f ≫ f' := sorry /-- The map `p : P ⟶ image f` is an epimorphism -/ protected instance factor_thru_image.category_theory.epi {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : epi (non_preadditive_abelian.factor_thru_image f) := sorry -- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0. protected instance mono_factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) [mono f] : mono (non_preadditive_abelian.factor_thru_image f) := mono_of_mono_fac (image.fac f) protected instance is_iso_factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) [mono f] : is_iso (non_preadditive_abelian.factor_thru_image f) := is_iso_of_mono_of_epi (non_preadditive_abelian.factor_thru_image f) /-- The cokernel of the kernel of `f` is called the coimage of `f`. -/ protected def coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : C := limits.cokernel (limits.kernel.ι f) /-- The projection onto the coimage. -/ protected def coimage.π {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : P ⟶ non_preadditive_abelian.coimage f := limits.cokernel.π (limits.kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected def factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : non_preadditive_abelian.coimage f ⟶ Q := limits.cokernel.desc (limits.kernel.ι f) f sorry /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected theorem coimage.fac {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : coimage.π f ≫ non_preadditive_abelian.factor_thru_coimage f = f := limits.cokernel.π_desc (limits.kernel.ι f) f (factor_thru_coimage._proof_1 f) /-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/ protected instance factor_thru_coimage.category_theory.mono {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) : mono (non_preadditive_abelian.factor_thru_coimage f) := sorry protected instance epi_factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) [epi f] : epi (non_preadditive_abelian.factor_thru_coimage f) := epi_of_epi_fac (coimage.fac f) protected instance is_iso_factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) [epi f] : is_iso (non_preadditive_abelian.factor_thru_coimage f) := is_iso_of_mono_of_epi (non_preadditive_abelian.factor_thru_coimage f) /-- In a `non_preadditive_abelian` category, an epi is the cokernel of its kernel. More precisely: If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel of `fork.ι s`. -/ def epi_is_cokernel_of_kernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {f : X ⟶ Y} [epi f] (s : limits.fork f 0) (h : limits.is_limit s) : limits.is_colimit (limits.cokernel_cofork.of_π f (epi_is_cokernel_of_kernel._proof_1 s)) := limits.is_cokernel.cokernel_iso (limits.fork.ι s) f (limits.cokernel.of_iso_comp (nat_trans.app (limits.cone.π (limits.limit.cone (limits.parallel_pair f 0))) limits.walking_parallel_pair.zero) (limits.fork.ι s) (limits.is_limit.cone_point_unique_up_to_iso (limits.limit.is_limit (limits.parallel_pair f 0)) h) sorry) (as_iso (non_preadditive_abelian.factor_thru_coimage f)) sorry /-- In a `non_preadditive_abelian` category, a mono is the kernel of its cokernel. More precisely: If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel of `cofork.π s`. -/ def mono_is_kernel_of_cokernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {f : X ⟶ Y} [mono f] (s : limits.cofork f 0) (h : limits.is_colimit s) : limits.is_limit (limits.kernel_fork.of_ι f (mono_is_kernel_of_cokernel._proof_1 s)) := limits.is_kernel.iso_kernel (limits.cofork.π s) f (limits.kernel.of_comp_iso (nat_trans.app (limits.cocone.ι (limits.colimit.cocone (limits.parallel_pair f 0))) limits.walking_parallel_pair.one) (limits.cofork.π s) (limits.is_colimit.cocone_point_unique_up_to_iso h (limits.colimit.is_colimit (limits.parallel_pair f 0))) sorry) (as_iso (non_preadditive_abelian.factor_thru_image f)) sorry /-- The composite `A ⟶ A ⨯ A ⟶ cokernel (Δ A)`, where the first map is `(𝟙 A, 0)` and the second map is the canonical projection into the cokernel. -/ def r {C : Type u} [category C] [non_preadditive_abelian C] (A : C) : A ⟶ limits.cokernel (limits.diag A) := limits.prod.lift 𝟙 0 ≫ limits.cokernel.π (limits.diag A) protected instance mono_Δ {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : mono (limits.diag A) := mono_of_mono_fac (limits.prod.lift_fst 𝟙 𝟙) protected instance mono_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : mono (r A) := sorry protected instance epi_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : epi (r A) := sorry protected instance is_iso_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : is_iso (r A) := is_iso_of_mono_of_epi (r A) /-- The composite `A ⨯ A ⟶ cokernel (diag A) ⟶ A` given by the natural projection into the cokernel followed by the inverse of `r`. In the category of modules, using the normal kernels and cokernels, this map is equal to the map `(a, b) ↦ a - b`, hence the name `σ` for "subtraction". -/ def σ {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : A ⨯ A ⟶ A := limits.cokernel.π (limits.diag A) ≫ inv (r A) @[simp] theorem diag_σ {C : Type u} [category C] [non_preadditive_abelian C] {X : C} : limits.diag X ≫ σ = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (limits.diag X ≫ σ = 0)) (limits.cokernel.condition_assoc (limits.diag X) (inv (r X))))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 ≫ inv (r X) = 0)) limits.zero_comp)) (Eq.refl 0)) @[simp] theorem lift_σ_assoc {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {X' : C} (f' : X ⟶ X') : limits.prod.lift 𝟙 0 ≫ limits.cokernel.π (limits.diag X) ≫ inv (r X) ≫ f' = f' := sorry theorem lift_map {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) : limits.prod.lift 𝟙 0 ≫ limits.prod.map f f = f ≫ limits.prod.lift 𝟙 0 := sorry /-- σ is a cokernel of Δ X. -/ def is_colimit_σ {C : Type u} [category C] [non_preadditive_abelian C] {X : C} : limits.is_colimit (limits.cokernel_cofork.of_π σ diag_σ) := limits.cokernel.cokernel_iso (limits.diag X) σ (iso.symm (as_iso (r X))) sorry /-- This is the key identity satisfied by `σ`. -/ theorem σ_comp {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) : σ ≫ f = limits.prod.map f f ≫ σ := sorry /- We write `f - g` for `prod.lift f g ≫ σ`. -/ /-- Subtraction of morphisms in a `non_preadditive_abelian` category. -/ def has_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Sub (X ⟶ Y) := { sub := fun (f g : X ⟶ Y) => limits.prod.lift f g ≫ σ } /- We write `-f` for `0 - f`. -/ /-- Negation of morphisms in a `non_preadditive_abelian` category. -/ def has_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Neg (X ⟶ Y) := { neg := fun (f : X ⟶ Y) => 0 - f } /- We write `f + g` for `f - (-g)`. -/ /-- Addition of morphisms in a `non_preadditive_abelian` category. -/ def has_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Add (X ⟶ Y) := { add := fun (f g : X ⟶ Y) => f - -g } theorem sub_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : a - b = limits.prod.lift a b ≫ σ := rfl theorem add_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : a + b = a - -b := rfl theorem neg_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : -a = 0 - a := rfl theorem sub_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : a - 0 = a := sorry theorem sub_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : a - a = 0 := sorry theorem lift_sub_lift {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) (d : X ⟶ Y) : limits.prod.lift a b - limits.prod.lift c d = limits.prod.lift (a - c) (b - d) := sorry theorem sub_sub_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) (d : X ⟶ Y) : a - c - (b - d) = a - b - (c - d) := sorry theorem neg_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : -a - b = -b - a := sorry theorem neg_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : --a = a := sorry theorem add_comm {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : a + b = b + a := sorry theorem add_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : a + -b = a - b := eq.mpr (id (Eq._oldrec (Eq.refl (a + -b = a - b)) (add_def a (-b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - --b = a - b)) (neg_neg b))) (Eq.refl (a - b))) theorem add_neg_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : a + -a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (add_neg a a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - a = 0)) (sub_self a))) (Eq.refl 0)) theorem neg_add_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : -a + a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (-a + a = 0)) (add_comm (-a) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (add_neg_self a))) (Eq.refl 0)) theorem neg_sub' {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : -(a - b) = -a + b := sorry theorem neg_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) : -(a + b) = -a - b := eq.mpr (id (Eq._oldrec (Eq.refl (-(a + b) = -a - b)) (add_def a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (-(a - -b) = -a - b)) (neg_sub' a (-b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (-a + -b = -a - b)) (add_neg (-a) b))) (Eq.refl (-a - b)))) theorem sub_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) : a - b + c = a - (b - c) := sorry theorem add_assoc {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) : a + b + c = a + (b + c) := sorry theorem add_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) : a + 0 = a := sorry theorem comp_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : Y ⟶ Z) : f ≫ (g - h) = f ≫ g - f ≫ h := sorry theorem sub_comp {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C} (f : X ⟶ Y) (g : X ⟶ Y) (h : Y ⟶ Z) : (f - g) ≫ h = f ≫ h - g ≫ h := sorry theorem comp_add {C : Type u} [category C] [non_preadditive_abelian C] (X : C) (Y : C) (Z : C) (f : X ⟶ Y) (g : Y ⟶ Z) (h : Y ⟶ Z) : f ≫ (g + h) = f ≫ g + f ≫ h := sorry theorem add_comp {C : Type u} [category C] [non_preadditive_abelian C] (X : C) (Y : C) (Z : C) (f : X ⟶ Y) (g : X ⟶ Y) (h : Y ⟶ Z) : (f + g) ≫ h = f ≫ h + g ≫ h := sorry /-- Every `non_preadditive_abelian` category is preadditive. -/ def preadditive {C : Type u} [category C] [non_preadditive_abelian C] : preadditive C := preadditive.mk
adf57352a0b468f809001345761dcd3cf5770da5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/splitting_field.lean
5f12b97c63d6d5e25079b1c5e0b97b17b963ec5b
[ "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
37,526
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.adjoin_root import ring_theory.algebra_tower import ring_theory.algebraic import ring_theory.polynomial import field_theory.minpoly import linear_algebra.finite_dimensional import tactic.field_simp import algebra.polynomial.big_operators /-! # Splitting fields This file introduces the notion of a splitting field of a polynomial and provides an embedding from a splitting field to any field that splits the polynomial. A polynomial `f : polynomial K` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. A field extension of `K` of a polynomial `f : polynomial K` is called a splitting field if it is the smallest field extension of `K` such that `f` splits. ## Main definitions * `polynomial.splits i f`: A predicate on a field homomorphism `i : K → L` and a polynomial `f` saying that `f` is zero or all of its irreducible factors over `L` have degree `1`. * `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`. * `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial `f`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. * `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset `S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in `L`, then `algebra.adjoin F S` embeds into `L`. * `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into another field such that `f` splits. * `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorpic to `splitting_field f` and thus, being a splitting field is unique up to isomorphism. -/ noncomputable theory open_locale classical big_operators universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial variables [field K] [field L] [field F] open polynomial section splits variables (i : K →+* L) /-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/ def splits (f : polynomial K) : Prop := f = 0 ∨ ∀ {g : polynomial L}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial K) := or.inl rfl @[simp] lemma splits_C (a : K) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 K _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((i.injective_iff).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : polynomial K} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial K} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_of_nat_degree_le_one {f : polynomial K} (hf : nat_degree f ≤ 1) : splits i f := splits_of_degree_le_one i (degree_le_of_nat_degree_le hf) lemma splits_of_nat_degree_eq_one {f : polynomial K} (hf : nat_degree f = 1) : splits i f := splits_of_nat_degree_le_one i (le_of_eq hf) lemma splits_mul {f g : polynomial K} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial K} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact hg.trans (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact hg.trans (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : polynomial K} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : L →+* F) {f : polynomial K} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : polynomial K} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : K} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_X : X.splits i := splits_of_degree_eq_one _ $ degree_X theorem splits_id_iff_splits {f : polynomial K} : (f.map i).splits (ring_hom.id L) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial K} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type u} {s : ι → polynomial K} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end lemma splits_pow {f : polynomial K} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i := begin rw [←finset.card_range n, ←finset.prod_const], exact splits_prod i (λ j hj, hf), end lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n theorem splits_prod_iff {ι : Type u} {s : ι → polynomial K} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : polynomial L} (h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id L) p) : p.degree = 1 := begin rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : polynomial K} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial K} : splits i f → ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset L, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : polynomial K} (hf : f.splits i) (hfd : f.degree ≠ 0) : L := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : polynomial K} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : polynomial K} (hf : f.splits $ ring_hom.id K) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : (0 : polynomial K) ∉ m.map (λ r, X - C r), from zero_nmem_multiset_map_X_sub_C _ _, have h2 : (0 : polynomial L) ∉ m.map (λ r, X - C (i r)), from zero_nmem_multiset_map_X_sub_C _ _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_singleton, multiset.bind_singleton, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : polynomial K} {i : K →+* L} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have zero_nmem : (0 : polynomial L) ∉ s.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.singleton_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ zero_nmem, map_bind_roots_eq] end lemma eq_prod_roots_of_splits_id {p : polynomial K} (hsplit : splits (ring_hom.id K) p) : p = C (p.leading_coeff) * (p.roots.map (λ a, X - C a)).prod := by simpa using eq_prod_roots_of_splits hsplit lemma eq_prod_roots_of_monic_of_splits_id {p : polynomial K} (m : monic p) (hsplit : splits (ring_hom.id K) p) : p = (p.roots.map (λ a, X - C a)).prod := begin convert eq_prod_roots_of_splits_id hsplit, simp [m], end lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : polynomial K} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_eq_card_roots {p : polynomial K} {i : K →+* L} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : (0 : polynomial L) ∉ (map i p).roots.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod _ this] end lemma degree_eq_card_roots {p : polynomial K} {i : K →+* L} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : polynomial K} {s : multiset L} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (normalized_factors (f.map i)) (s.map (λ a : L, (X : polynomial L) - C a)) := factors_unique (λ p hp, irreducible_of_normalized_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map C.to_monoid_hom : units L →* units (polynomial L)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs { rw [hs, ← leading_coeff_map i, mul_comm] }; refl⟩ ... ~ᵤ _ : (unique_factorization_monoid.normalized_factors_prod (by simpa using hf0)).symm), let ⟨q, hq, hpq⟩ := exists_mem_normalized_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial K} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 hp.irreducible (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial K} : splits i f ↔ ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : L →+* F) {f : polynomial K} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial K} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin have hprodmonic : (multiset.map (λ (a : K), X - C a) p.roots).prod.monic, { simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic), monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] }, have hdegree : (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree = p.nat_degree, { rw [← hroots, nat_degree_multiset_prod _ (zero_nmem_multiset_map_X_sub_C _ (λ a : K, a))], simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat, multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map] }, obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p, have qzero : q ≠ 0, { rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq }, have degp : p.nat_degree = (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree + q.nat_degree, { nth_rewrite 0 [hq], simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] }, have degq : q.nat_degree = 0, { rw hdegree at degp, exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm }, obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq), have hassoc : associated (multiset.map (λ (a : K), X - C a) p.roots).prod p, { rw associated, use u, rw [hu, ← hq] }, exact eq_of_monic_of_associated hprodmonic hmonic hassoc end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial K} (hroots : p.roots.card = p.nat_degree) : (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree, { rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots, coe_norm_unit, nat_degree_C, add_zero], }, have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero) hrootsnorm, rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod, calc (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) : by rw [hprod, mul_comm, mul_assoc, ← C_mul] ... = p * C 1 : by field_simp ... = p : by simp only [mul_one, ring_hom.map_one], }, end /-- A polynomial splits if and only if it has as many roots as its degree. -/ lemma splits_iff_card_roots {p : polynomial K} : splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, apply (splits_iff_exists_multiset (ring_hom.id K)).2, use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end end splits end polynomial section embeddings variables (F) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly {R : Type*} [comm_ring R] [algebra F R] (x : R) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minpoly.aeval F x) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range_aeval F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minpoly.dvd F x hp, λ y, let ⟨p, hp⟩ := (set_like.ext_iff.1 (algebra.adjoin_singleton_eq_range_aeval F x) (y : R)).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset /-- If a `subalgebra` is finite_dimensional as a submodule then it is `finite_dimensional`. -/ lemma finite_dimensional.of_subalgebra_to_submodule {K V : Type*} [field K] [ring V] [algebra K V] {s : subalgebra K V} (h : finite_dimensional K s.to_submodule) : finite_dimensional K s := h /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union_eq_under], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := ( (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3)).of_subalgebra_to_submodule, letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minpoly.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minpoly.dvd _ _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm, refine ⟨subalgebra.of_under _ _ _⟩, refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _, exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a end end embeddings namespace polynomial variables [field K] [field L] [field F] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : polynomial K) : polynomial K := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : polynomial K) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : polynomial K} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : polynomial K} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial K} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : polynomial K) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : polynomial K) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : polynomial K) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : polynomial K} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : polynomial K), f.nat_degree = n → Type u := nat.rec_on n (λ K _ _ _, K) $ λ n ih K _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : polynomial K} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ K _ _ _, ‹field K›) $ λ n ih K _ f hf, ih _ instance inhabited {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ instance algebra (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : polynomial K} (hfn : f.nat_degree = n), algebra K (splitting_field_aux n f hfn) := nat.rec_on n (λ K _ _ _, by exactI algebra.id K) $ λ n ih K _ f hfn, by exactI @@restrict_scalars.algebra _ _ _ _ _ (ih _) _ _ instance algebra' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := splitting_field_aux.algebra n _ instance algebra'' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra K (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra (n+1) hfn instance algebra''' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ instance scalar_tower {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl instance scalar_tower' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl theorem algebra_map_succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) : by exact algebra_map K (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := rfl protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n), splits (algebra_map K $ splitting_field_aux n f hfn) f := nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI ∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* L, k.comp (algebra_map _ _) = j := nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n), algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih K _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map K (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢, rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton, algebra.adjoin_union_eq_under, ← set.image_singleton, algebra.adjoin_algebra_map K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.range_under_adjoin K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.restrict_scalars_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : polynomial K) := splitting_field_aux _ f rfl namespace splitting_field variables (f : polynomial K) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ instance : algebra K (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map K (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra K L] (hb : splits (algebra_map K L) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[K] L := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin K (↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ := adjoin_roots f end splitting_field variables (K L) [algebra K L] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : polynomial K) : Prop := (splits [] : splits (algebra_map K L) f) (adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤) namespace is_splitting_field variables {K} instance splitting_field (f : polynomial K) : is_splitting_field K (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L] variables {K} instance map (f : polynomial F) [is_splitting_field F L f] : is_splitting_field K L (f.map $ algebra_map F K) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f }, subalgebra.restrict_scalars_injective F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.restrict_scalars_top, eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩ variables {K} (L) theorem splits_iff (f : polynomial K) [is_splitting_field K L f] : polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl K _ ▸ ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩ theorem mul (f g : polynomial F) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f] [is_splitting_field K L (g.map $ algebra_map F K)] : is_splitting_field F L (f * g) := ⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits K f)) ((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)), by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_under, is_scalar_tower.algebra_map_eq F K L, ← map_map, roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots, subalgebra.restrict_scalars_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra K F] (f : polynomial K) [is_splitting_field K L f] (hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F := if hf0 : f = 0 then (algebra.of_id K F).comp $ (algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $ by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : polynomial K) [is_splitting_field K L f] : finite_dimensional K L := is_noetherian.iff_fg.2 ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, map_zero, roots_zero] at hy, cases hy } else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩ instance (f : polynomial K) : _root_.finite_dimensional K f.splitting_field := finite_dimensional f.splitting_field f /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : polynomial K) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f := begin refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional L f, have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) := le_antisymm (linear_map.finrank_le_finrank_of_injective (show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field))) (linear_map.finrank_le_finrank_of_injective (show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))), change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _, exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
038a9f02e6962775b3b72758763f5f6a03994f74
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/complex/upper_half_plane/functions_bounded_at_infty.lean
26d6235065751024b5223a25db33dc7e082df23f
[ "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
3,757
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import algebra.module.submodule.basic import analysis.complex.upper_half_plane.basic import order.filter.zero_and_bounded_at_filter /-! # Bounded at infinity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For complex valued functions on the upper half plane, this file defines the filter `at_im_infty` required for defining when functions are bounded at infinity and zero at infinity. Both of which are relevant for defining modular forms. -/ open complex filter open_locale topology upper_half_plane noncomputable theory namespace upper_half_plane /-- Filter for approaching `i∞`. -/ def at_im_infty := filter.at_top.comap upper_half_plane.im lemma at_im_infty_basis : (at_im_infty).has_basis (λ _, true) (λ (i : ℝ), im ⁻¹' set.Ici i) := filter.has_basis.comap upper_half_plane.im filter.at_top_basis lemma at_im_infty_mem (S : set ℍ) : S ∈ at_im_infty ↔ (∃ A : ℝ, ∀ z : ℍ, A ≤ im z → z ∈ S) := begin simp only [at_im_infty, filter.mem_comap', filter.mem_at_top_sets, ge_iff_le, set.mem_set_of_eq, upper_half_plane.coe_im], refine ⟨λ ⟨a, h⟩, ⟨a, (λ z hz, h (im z) hz rfl)⟩, _⟩, rintro ⟨A, h⟩, refine ⟨A, λ b hb x hx, h x _⟩, rwa hx, end /-- A function ` f : ℍ → α` is bounded at infinity if it is bounded along `at_im_infty`. -/ def is_bounded_at_im_infty {α : Type*} [has_norm α] (f : ℍ → α) : Prop := bounded_at_filter at_im_infty f /-- A function ` f : ℍ → α` is zero at infinity it is zero along `at_im_infty`. -/ def is_zero_at_im_infty {α : Type*} [has_zero α] [topological_space α] (f : ℍ → α) : Prop := zero_at_filter at_im_infty f lemma zero_form_is_bounded_at_im_infty {α : Type*} [normed_field α] : is_bounded_at_im_infty (0 : ℍ → α) := const_bounded_at_filter at_im_infty (0:α) /-- Module of functions that are zero at infinity. -/ def zero_at_im_infty_submodule (α : Type*) [normed_field α] : submodule α (ℍ → α) := zero_at_filter_submodule at_im_infty /-- ubalgebra of functions that are bounded at infinity. -/ def bounded_at_im_infty_subalgebra (α : Type*) [normed_field α] : subalgebra α (ℍ → α) := bounded_filter_subalgebra at_im_infty lemma is_bounded_at_im_infty.mul {f g : ℍ → ℂ} (hf : is_bounded_at_im_infty f) (hg : is_bounded_at_im_infty g) : is_bounded_at_im_infty (f * g) := by simpa only [pi.one_apply, mul_one, norm_eq_abs] using hf.mul hg lemma bounded_mem (f : ℍ → ℂ) : is_bounded_at_im_infty f ↔ ∃ (M A : ℝ), ∀ z : ℍ, A ≤ im z → abs (f z) ≤ M := by simp [is_bounded_at_im_infty, bounded_at_filter, asymptotics.is_O_iff, filter.eventually, at_im_infty_mem] lemma zero_at_im_infty (f : ℍ → ℂ) : is_zero_at_im_infty f ↔ ∀ ε : ℝ, 0 < ε → ∃ A : ℝ, ∀ z : ℍ, A ≤ im z → abs (f z) ≤ ε := begin rw [is_zero_at_im_infty, zero_at_filter, tendsto_iff_forall_eventually_mem], split, { simp_rw [filter.eventually, at_im_infty_mem], intros h ε hε, simpa using (h (metric.closed_ball (0 : ℂ) ε) (metric.closed_ball_mem_nhds (0 : ℂ) hε))}, { simp_rw metric.mem_nhds_iff, intros h s hs, simp_rw [filter.eventually, at_im_infty_mem], obtain ⟨ε, h1, h2⟩ := hs, have h11 : 0 < (ε/2), by {linarith,}, obtain ⟨A, hA⟩ := (h (ε/2) h11), use A, intros z hz, have hzs : f z ∈ s, { apply h2, simp only [mem_ball_zero_iff, norm_eq_abs], apply lt_of_le_of_lt (hA z hz), linarith }, apply hzs,} end end upper_half_plane
f85a1b0820a10e1a8b71e659a3bd35abdd7e8c74
df561f413cfe0a88b1056655515399c546ff32a5
/1-tutorial-world/l4.lean
a185427021267b6fdbbdb2cfaf8045b3519c8d0e
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
100
lean
lemma add_succ_zero (a : mynat) : a + succ(0) = succ(a) := begin rw add_succ, rw add_zero, refl, end
21ca9432c5578baed5ff93cca70c2eaa5314d9cf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/enorm_auto.lean
67ec7520af89d57cafd83d437b932e104febe6d6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,145
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.basic import Mathlib.PostPort universes u_1 u_2 l namespace Mathlib /-! # Extended norm In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for an `enorm` because the same space can have more than one extended norm. For example, the space of measurable functions `f : α → ℝ` has a family of `L_p` extended norms. We prove some basic inequalities, then define * `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`; * the subspace of vectors with finite norm, called `e.finite_subspace`; * a `normed_space` structure on this space. The last definition is an instance because the type involves `e`. ## Implementation notes We do not define extended normed groups. They can be added to the chain once someone will need them. ## Tags normed space, extended norm -/ /-- Extended norm on a vector space. As in the case of normed spaces, we require only `∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/ structure enorm (𝕜 : Type u_1) (V : Type u_2) [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] where to_fun : V → ennreal eq_zero' : ∀ (x : V), to_fun x = 0 → x = 0 map_add_le' : ∀ (x y : V), to_fun (x + y) ≤ to_fun x + to_fun y map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ ↑(nnnorm c) * to_fun x namespace enorm protected instance has_coe_to_fun {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : has_coe_to_fun (enorm 𝕜 V) := has_coe_to_fun.mk (fun (x : enorm 𝕜 V) => V → ennreal) to_fun theorem injective_coe_fn {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : function.injective fun (e : enorm 𝕜 V) (x : V) => coe_fn e x := sorry theorem ext {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] {e₁ : enorm 𝕜 V} {e₂ : enorm 𝕜 V} (h : ∀ (x : V), coe_fn e₁ x = coe_fn e₂ x) : e₁ = e₂ := injective_coe_fn (funext h) theorem ext_iff {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] {e₁ : enorm 𝕜 V} {e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ (x : V), coe_fn e₁ x = coe_fn e₂ x := { mp := fun (h : e₁ = e₂) (x : V) => h ▸ rfl, mpr := ext } @[simp] theorem coe_inj {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] {e₁ : enorm 𝕜 V} {e₂ : enorm 𝕜 V} : ⇑e₁ = ⇑e₂ ↔ e₁ = e₂ := function.injective.eq_iff injective_coe_fn @[simp] theorem map_smul {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (c : 𝕜) (x : V) : coe_fn e (c • x) = ↑(nnnorm c) * coe_fn e x := sorry @[simp] theorem map_zero {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : coe_fn e 0 = 0 := sorry @[simp] theorem eq_zero_iff {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) {x : V} : coe_fn e x = 0 ↔ x = 0 := { mp := eq_zero' e x, mpr := fun (h : x = 0) => Eq.symm h ▸ map_zero e } @[simp] theorem map_neg {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : V) : coe_fn e (-x) = coe_fn e x := sorry theorem map_sub_rev {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : V) (y : V) : coe_fn e (x - y) = coe_fn e (y - x) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn e (x - y) = coe_fn e (y - x))) (Eq.symm (neg_sub y x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn e (-(y - x)) = coe_fn e (y - x))) (map_neg e (y - x)))) (Eq.refl (coe_fn e (y - x)))) theorem map_add_le {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : V) (y : V) : coe_fn e (x + y) ≤ coe_fn e x + coe_fn e y := map_add_le' e x y theorem map_sub_le {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : V) (y : V) : coe_fn e (x - y) ≤ coe_fn e x + coe_fn e y := sorry protected instance partial_order {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : partial_order (enorm 𝕜 V) := partial_order.mk (fun (e₁ e₂ : enorm 𝕜 V) => ∀ (x : V), coe_fn e₁ x ≤ coe_fn e₂ x) (preorder.lt._default fun (e₁ e₂ : enorm 𝕜 V) => ∀ (x : V), coe_fn e₁ x ≤ coe_fn e₂ x) sorry sorry sorry /-- The `enorm` sending each non-zero vector to infinity. -/ protected instance has_top {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : has_top (enorm 𝕜 V) := has_top.mk (mk (fun (x : V) => ite (x = 0) 0 ⊤) sorry sorry sorry) protected instance inhabited {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : Inhabited (enorm 𝕜 V) := { default := ⊤ } theorem top_map {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] {x : V} (hx : x ≠ 0) : coe_fn ⊤ x = ⊤ := if_neg hx protected instance semilattice_sup_top {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] : semilattice_sup_top (enorm 𝕜 V) := semilattice_sup_top.mk ⊤ LessEq Less sorry sorry sorry sorry (fun (e₁ e₂ : enorm 𝕜 V) => mk (fun (x : V) => max (coe_fn e₁ x) (coe_fn e₂ x)) sorry sorry sorry) sorry sorry sorry @[simp] theorem coe_max {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e₁ : enorm 𝕜 V) (e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = fun (x : V) => max (coe_fn e₁ x) (coe_fn e₂ x) := rfl theorem max_map {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e₁ : enorm 𝕜 V) (e₂ : enorm 𝕜 V) (x : V) : coe_fn (e₁ ⊔ e₂) x = max (coe_fn e₁ x) (coe_fn e₂ x) := rfl /-- Structure of an `emetric_space` defined by an extended norm. -/ def emetric_space {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : emetric_space V := emetric_space.mk sorry sorry (map_sub_rev e) sorry (uniform_space_of_edist (fun (x y : V) => coe_fn e (x - y)) sorry (map_sub_rev e) sorry) /-- The subspace of vectors with finite enorm. -/ def finite_subspace {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : subspace 𝕜 V := submodule.mk (set_of fun (x : V) => coe_fn e x < ⊤) sorry sorry sorry /-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist` to ensure that this definition agrees with `e.emetric_space`. -/ protected instance finite_subspace.metric_space {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : metric_space ↥(finite_subspace e) := let _inst : emetric_space V := emetric_space e; emetric_space.to_metric_space_of_dist (fun (x y : ↥(finite_subspace e)) => ennreal.to_real (edist x y)) sorry sorry theorem finite_dist_eq {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : ↥(finite_subspace e)) (y : ↥(finite_subspace e)) : dist x y = ennreal.to_real (coe_fn e (↑x - ↑y)) := rfl theorem finite_edist_eq {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : ↥(finite_subspace e)) (y : ↥(finite_subspace e)) : edist x y = coe_fn e (↑x - ↑y) := rfl /-- Normed group instance on `e.finite_subspace`. -/ protected instance finite_subspace.normed_group {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : normed_group ↥(finite_subspace e) := normed_group.mk sorry theorem finite_norm_eq {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) (x : ↥(finite_subspace e)) : norm x = ennreal.to_real (coe_fn e ↑x) := rfl /-- Normed space instance on `e.finite_subspace`. -/ protected instance finite_subspace.normed_space {𝕜 : Type u_1} {V : Type u_2} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) : normed_space 𝕜 ↥(finite_subspace e) := normed_space.mk sorry end Mathlib
eac4f6ecd0d25d1c46ab3559f2708d952d7b5874
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/uniform_space/separation.lean
65e3dc30ccc383d6b51708f28353afaefa177914
[ "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
21,541
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, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ @[class] def separated_space (α : Type u) [uniform_space α] := 𝓢 α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [not_forall] lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_bInter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i ∈ set_of p, s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simpa [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; intro h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, have : 𝓝 x ⊓ 𝓝 y = ⊥, { rw t2_iff_nhds at h, by_contra H, exact hxy (h H) }, rcases inf_eq_bot_iff.mp this with ⟨U, V, U_in, V_in, H⟩, rcases mem_nhds_iff_symm.mp U_in with ⟨S, S_in, S_symm, S_sub⟩, use [S, S_in], change y ∉ ball x S, intro y_in, have : y ∈ U ∩ V := ⟨S_sub y_in, mem_of_nhds V_in⟩, rwa H at this }, end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, show 𝓢 α = diagonal α, from ‹separated_space α›], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin change _ ↔ 𝓢 ({x // x ∈ s}) = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, apply id_rel_sub_separation_relation α, rw mem_id_rel }, { -- For legibility purpose, let's have explicit coercion C s : ↥s → α for every α and s : set α let C : Π {β : Type*} (s : set β) (x : s), β := λ _ _, subtype.val, let Δ := diagonal, change _ ⊆ Δ _, change (prod.map (C s) (C s)) ⁻¹' (𝓢 α) = Δ _ at h, rw [inter_comm, ← subtype.image_preimage_coe, image_subset_iff], change (C _) ⁻¹' _ ⊆ (C _) ⁻¹' _, let φ : ↥s × ↥s → (s.prod s) := (λ x : s × s, ⟨(x.1.1, x.2.1), mk_mem_prod x.1.2 x.2.2⟩), have φ_surj : surjective φ := λ ⟨⟨x, y⟩, ⟨x_in, y_in⟩⟩, ⟨(⟨x, x_in⟩, ⟨y, y_in⟩), rfl⟩, have CCCφ: prod.map (C s) (C s) = C (s.prod s) ∘ φ, by ext ; refl, have ΔΔ: (prod.map (C s) (C s)) ⁻¹' (Δ α) = Δ s := set.preimage_coe_coe_diagonal s, apply_fun (image φ) at h, rw [ ← ΔΔ, CCCφ, preimage_comp, preimage_comp, image_preimage_eq φ_surj, image_preimage_eq φ_surj] at h, rw h }, end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
60edb8eea1eb593f459cf3ccd1cd1ec1594701e9
7c2dd01406c42053207061adb11703dc7ce0b5e5
/src/solutions/05_sequence_limits.lean
cd797da03ba6e4859c77aa07137f41c8d5629ed5
[ "Apache-2.0" ]
permissive
leanprover-community/tutorials
50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8
79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1
refs/heads/master
1,687,466,144,386
1,672,061,276,000
1,672,061,276,000
189,169,918
186
81
Apache-2.0
1,686,350,300,000
1,559,113,678,000
Lean
UTF-8
Lean
false
false
7,635
lean
import data.real.basic import algebra.group.pi import tuto_lib notation `|`x`|` := abs x /- In this file we manipulate the elementary definition of limits of sequences of real numbers. mathlib has a much more general definition of limits, but here we want to practice using the logical operators and relations covered in the previous files. A sequence u is a function from ℕ to ℝ, hence Lean says u : ℕ → ℝ The definition we'll be using is: -- Definition of « u tends to l » def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε Note the use of `∀ ε > 0, ...` which is an abbreviation of `∀ ε, ε > 0 → ... ` In particular, a statement like `h : ∀ ε > 0, ...` can be specialized to a given ε₀ by `specialize h ε₀ hε₀` where hε₀ is a proof of ε₀ > 0. Also recall that, wherever Lean expects some proof term, we can start a tactic mode proof using the keyword `by` (followed by curly braces if you need more than one tactic invocation). For instance, if the local context contains: δ : ℝ δ_pos : δ > 0 h : ∀ ε > 0, ... then we can specialize h to the real number δ/2 using: `specialize h (δ/2) (by linarith)` where `by linarith` will provide the proof of `δ/2 > 0` expected by Lean. We'll take this opportunity to use two new tactics: `norm_num` will perform numerical normalization on the goal and `norm_num at h` will do the same in assumption `h`. This will get rid of trivial calculations on numbers, like replacing |l - l| by zero in the next exercise. `congr'` will try to prove equalities between applications of functions by recursively proving the arguments are the same. For instance, if the goal is `f x + g y = f z + g t` then congr will replace it by two goals: `x = z` and `y = t`. You can limit the recursion depth by specifying a natural number after `congr'`. For instance, in the above example, `congr' 1` will give new goals `f x = f z` and `g y = g t`, which only inspect arguments of the addition and not deeper. -/ variables (u v w : ℕ → ℝ) (l l' : ℝ) -- If u is constant with value l then u tends to l -- 0033 example : (∀ n, u n = l) → seq_limit u l := begin -- sorry intros h ε ε_pos, use 0, intros n hn, rw h, norm_num, linarith, -- sorry end /- When dealing with absolute values, we'll use lemmas: abs_le {x y : ℝ} : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| You should probably write them down on a sheet of paper that you keep at hand since they are used in many exercises. -/ -- Assume l > 0. Then u tends to l implies u n ≥ l/2 for large enough n -- 0034 example (hl : l > 0) : seq_limit u l → ∃ N, ∀ n ≥ N, u n ≥ l/2 := begin -- sorry intro h, cases h (l/2) (by linarith) with N hN, use N, intros n hn, specialize hN n hn, rw abs_le at hN, linarith, -- sorry end /- When dealing with max, you can use 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 You should probably add them to the sheet of paper where you wrote the `abs` lemmas since they are used in many exercises. Let's see an example. -/ -- If u tends to l and v tends l' then u+v tends to l+l' example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, cases ge_max_iff.mp hn with hn₁ hn₂, have fact₁ : |u n - l| ≤ ε/2, from hN₁ n (by linarith), -- note the use of `from`. -- This is an alias for `exact`, -- but reads nicer in this context have fact₂ : |v n - l'| ≤ ε/2, from hN₂ n (by linarith), calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith, end /- In the above proof, we used `have` to prepare facts for `linarith` consumption in the last line. Since we have direct proof terms for them, we can feed them directly to `linarith` as in the next proof of the same statement. Another variation we introduce is rewriting using `ge_max_iff` and letting `linarith` handle the conjunction, instead of creating two new assumptions. -/ example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, rw ge_max_iff at hn, calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith [hN₁ n (by linarith), hN₂ n (by linarith)], end /- Let's do something similar: the squeezing theorem. -/ -- 0035 example (hu : seq_limit u l) (hw : seq_limit w l) (h : ∀ n, u n ≤ v n) (h' : ∀ n, v n ≤ w n) : seq_limit v l := begin -- sorry intros ε ε_pos, cases hu ε ε_pos with N hN, cases hw ε ε_pos with N' hN', use max N N', intros n hn, rw ge_max_iff at hn, specialize hN n (by linarith), specialize hN' n (by linarith), specialize h n, specialize h' n, rw abs_le at *, split, -- Here `linarith` can finish, but on paper we would write calc -ε ≤ u n - l : by linarith ... ≤ v n - l : by linarith, calc v n - l ≤ w n - l : by linarith ... ≤ ε : by linarith, -- sorry end /- What about < ε? -/ -- 0036 example (u l) : seq_limit u l ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| < ε := begin -- sorry split, { intros hyp ε ε_pos, cases hyp (ε/2) (by linarith) with N hN, use N, intros n hn, calc |u n - l| ≤ ε/2 : by exact hN n hn ... < ε : by linarith, }, { intros hyp ε ε_pos, cases hyp ε ε_pos with N hN, use N, intros n hn, specialize hN n hn, linarith, }, -- sorry end /- In the next exercise, we'll use eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y -/ -- A sequence admits at most one limit -- 0037 example : seq_limit u l → seq_limit u l' → l = l' := begin -- sorry intros hl hl', apply eq_of_abs_sub_le_all, intros ε ε_pos, cases hl (ε/2) (by linarith) with N hN, cases hl' (ε/2) (by linarith) with N' hN', calc |l - l'| = |(l-u (max N N')) + (u (max N N') -l')| : by ring_nf ... ≤ |l - u (max N N')| + |u (max N N') - l'| : by apply abs_add ... = |u (max N N') - l| + |u (max N N') - l'| : by rw abs_sub_comm ... ≤ ε : by linarith [hN (max N N') (le_max_left _ _), hN' (max N N') (le_max_right _ _)] -- sorry end /- Let's now practice deciphering definitions before proving. -/ def non_decreasing (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m def is_seq_sup (M : ℝ) (u : ℕ → ℝ) := (∀ n, u n ≤ M) ∧ ∀ ε > 0, ∃ n₀, u n₀ ≥ M - ε -- 0038 example (M : ℝ) (h : is_seq_sup M u) (h' : non_decreasing u) : seq_limit u M := begin -- sorry intros ε ε_pos, cases h with inf_M sup_M_ep, cases sup_M_ep ε ε_pos with n₀ hn₀, use n₀, intros n hn, rw abs_le, split; linarith [inf_M n, h' n₀ n hn], -- sorry end
fd7ed48bd575178a8ae87e34ec33549db5e2812f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/category_theory/sites/sheaf_of_types.lean
1bba60b570042a634886adcb6de7b343a029e842
[ "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
38,946
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.pretopology import category_theory.limits.shapes.types import category_theory.full_subcategory /-! # Sheaves of types on a Grothendieck topology Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians) on a category equipped with a Grothendieck topology, as well as a range of equivalent conditions useful in different situations. First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular presieve `R` on `X`: * A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in `R`. See `family_of_elements`. * The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of `x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`. See `family_of_elements.compatible`. * An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in `R`, the restriction of `t` on `f` is `x_f`. See `family_of_elements.is_amalgamation`. We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation, and it is a *sheaf* for `R` if every compatible family has a unique amalgamation. See `is_separated_for` and `is_sheaf_for`. In the special case where `R` is a sieve, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of `x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`). See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`. In the special case where `C` has pullbacks, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`, the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g` along `π₂ : pullback f g ⟶ Z`. See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`. Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the topology. See `is_sheaf`. In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for every sieve in the pretopology. See `is_sheaf_pretopology`. We also provide equivalent conditions to satisfy alternate definitions given in the literature. * Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with `is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.) The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries the same information as the unique existence.) * Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf` are equivalent. There are also alternate definitions given: - Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in `yoneda_condition_iff_sheaf_condition`. - Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence in `equalizer.sieve.sheaf_condition`. - Matching family for presieves with pullback: `pullback_compatible_iff`. - Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous. - Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition` combined with the previous. ## Implementation The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u₁ v)`. This doesn't seem to make a big difference, other than making a couple of definitions noncomputable, but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements, which can be convenient. ## References * [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk: Chapter III, Section 4. * [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1. * https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site) * https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology) -/ universes w v₁ v₂ u₁ u₂ namespace category_theory open opposite category_theory category limits sieve classical namespace presieve variables {C : Type u₁} [category.{v₁} C] variables {P Q U : Cᵒᵖ ⥤ Type w} variables {X Y : C} {S : sieve X} {R : presieve X} variables (J J₂ : grothendieck_topology C) /-- A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X` consists of an element of `P Y` for every `f : Y ⟶ X` in `R`. A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one (resp, at most one) amalgamation. This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant]. -/ def family_of_elements (P : Cᵒᵖ ⥤ Type w) (R : presieve X) := Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y) instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩ /-- A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve `R₁`. -/ def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) : family_of_elements P R₂ → family_of_elements P R₁ := λ x Y f hf, x f (h _ hf) /-- A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂` commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and restricting the element of `P Y₂` along `g₂` are the same. In special cases, this condition can be simplified, see `pullback_compatible_iff` and `compatible_iff_sieve_compatible`. This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab: https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents -/ def family_of_elements.compatible (x : family_of_elements P R) : Prop := ∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂) /-- If the category `C` has pullbacks, this is an alternative condition for a family of elements to be compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the given elements for `f` and `g` to the pullback agree. This is equivalent to being compatible (provided `C` has pullbacks), shown in `pullback_compatible_iff`. This is the definition for a "matching" family given in [MM92], Chapter III, Section 4, Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`, using the notation defined there. -/ def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop := ∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂) lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] : x.compatible ↔ x.pullback_compatible := begin split, { intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂, apply t, apply pullback.condition }, { intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm, rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂, ←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] } end /-- The restriction of a compatible family is compatible. -/ lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) {x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible := λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm /-- Extend a family of elements to the sieve generated by an arrow set. This is the construction described as "easy" in Lemma C2.1.3 of [Elephant]. -/ noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) : family_of_elements P (generate R) := λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1) /-- The extension of a compatible family to the generated sieve is compatible. -/ lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) : x.sieve_extend.compatible := begin intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2, ←assoc, ←assoc] at comm, dsimp [family_of_elements.sieve_extend], rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], apply hx _ _ _ _ comm, end /-- The extension of a family agrees with the original family. -/ lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) : x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf := begin have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩, change P.map (some (some_spec h)).op (x _ _) = x f hf, rw t (some (some_spec h)) (𝟙 _) _ hf _, { simp }, simp_rw [id_comp], apply (some_spec (some_spec (some_spec h))).2, end /-- The restriction of an extension is the original. -/ @[simp] lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) : x.sieve_extend.restrict (le_generate R) = x := begin ext Y f hf, exact extend_agrees t hf, end /-- If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the consistency condition can be simplified. This is an equivalent condition, see `compatible_iff_sieve_compatible`. This is the notion of "matching" given for families on sieves given in [MM92], Chapter III, Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family. See also the discussion before Lemma C2.1.4 of [Elephant]. -/ def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop := ∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) lemma compatible_iff_sieve_compatible (x : family_of_elements P S) : x.compatible ↔ x.sieve_compatible := begin split, { intros h Y Z f g hf, simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) }, { intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k, simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] } end lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S} (t : x.compatible) : x.sieve_compatible := (compatible_iff_sieve_compatible x).1 t /-- Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are equal when restricted to `R`. -/ lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)} (t₁ : x₁.compatible) (t₂ : x₂.compatible) : x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ := begin intro h, ext Z f ⟨Y, f, g, hg, rfl⟩, rw compatible_iff_sieve_compatible at t₁ t₂, erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩], congr' 1, apply congr_fun (congr_fun (congr_fun h _) g) hg, end /-- Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted to `R` and then extended back up to `S`, the resulting extension equals `x`. -/ @[simp] lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) : (x.restrict (le_generate R)).sieve_extend = x := begin apply restrict_inj, { exact (t.restrict (le_generate R)).sieve_extend _ }, { exact t }, rw restrict_extend, exact t.restrict (le_generate R), end section functor_pullback variables {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {Z : D} variables {T : presieve (F.obj Z)} {x : family_of_elements P T} /-- Given a family of elements of a sieve `S` on `F(X)`, we can realize it as a family of elements of `S.functor_pullback F`. -/ def family_of_elements.functor_pullback (x : family_of_elements P T) : family_of_elements (F.op ⋙ P) (T.functor_pullback F) := λ Y f hf, x (F.map f) hf lemma family_of_elements.compatible.functor_pullback (h : x.compatible) : (x.functor_pullback F).compatible := begin intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq, exact h (F.map g₁) (F.map g₂) h₁ h₂ (by simp only [← F.map_comp, eq]) end end functor_pullback section pullback /-- Given a family of elements of a sieve `S` on `X`, and a map `Y ⟶ X`, we can obtain a family of elements of `S.pullback f` by taking the same elements. -/ def family_of_elements.pullback (f : Y ⟶ X) (x : family_of_elements P S) : family_of_elements P (S.pullback f) := λ _ g hg, x (g ≫ f) hg lemma family_of_elements.compatible.pullback (f : Y ⟶ X) {x : family_of_elements P S} (h : x.compatible) : (x.pullback f).compatible := begin simp only [compatible_iff_sieve_compatible] at h ⊢, intros W Z f₁ f₂ hf, unfold family_of_elements.pullback, rw ← (h (f₁ ≫ f) f₂ hf), simp only [category.assoc], end end pullback /-- Given a morphism of presheaves `f : P ⟶ Q`, we can take a family of elements valued in `P` to a family of elements valued in `Q` by composing with `f`. -/ def family_of_elements.comp_presheaf_map (f : P ⟶ Q) (x : family_of_elements P R) : family_of_elements Q R := λ Y g hg, f.app (op Y) (x g hg) @[simp] lemma family_of_elements.comp_presheaf_map_id (x : family_of_elements P R) : x.comp_presheaf_map (𝟙 P) = x := rfl @[simp] lemma family_of_elements.comp_prersheaf_map_comp (x : family_of_elements P R) (f : P ⟶ Q) (g : Q ⟶ U) : (x.comp_presheaf_map f).comp_presheaf_map g = x.comp_presheaf_map (f ≫ g) := rfl lemma family_of_elements.compatible.comp_presheaf_map (f : P ⟶ Q) {x : family_of_elements P R} (h : x.compatible) : (x.comp_presheaf_map f).compatible := begin intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq, unfold family_of_elements.comp_presheaf_map, rwa [← functor_to_types.naturality, ← functor_to_types.naturality, h], end /-- The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`. This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents, and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4, equation (2). -/ def family_of_elements.is_amalgamation (x : family_of_elements P R) (t : P.obj (op X)) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h lemma family_of_elements.is_amalgamation.comp_presheaf_map {x : family_of_elements P R} {t} (f : P ⟶ Q) (h : x.is_amalgamation t) : (x.comp_presheaf_map f).is_amalgamation (f.app (op X) t) := begin intros Y g hg, dsimp [family_of_elements.comp_presheaf_map], change (f.app _ ≫ Q.map _) _ = _, simp [← f.naturality, h g hg], end lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R) (h : ∃ t, x.is_amalgamation t) : x.compatible := begin cases h with t ht, intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm], simp, end lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) (x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) : (x.restrict h).is_amalgamation t := λ Y f hf, ht f (h Y hf) lemma is_amalgamation_sieve_extend {R : presieve X} (x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) : x.sieve_extend.is_amalgamation t := begin intros Y f hf, dsimp [family_of_elements.sieve_extend], rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2], end /-- A presheaf is separated for a presieve if there is at most one amalgamation. -/ def is_separated_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop := ∀ (x : family_of_elements P R) (t₁ t₂), x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂ lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R) {t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) : t₁ = t₂ := hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl) lemma is_separated_for_iff_generate : is_separated_for P R ↔ is_separated_for P (generate R) := begin split, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.restrict (le_generate R)) t₁ t₂ _ _, { exact is_amalgamation_restrict _ x t₁ ht₁ }, { exact is_amalgamation_restrict _ x t₂ ht₂ } }, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.sieve_extend), { exact is_amalgamation_sieve_extend x t₁ ht₁ }, { exact is_amalgamation_sieve_extend x t₂ ht₂ } } end lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type w) : is_separated_for P (⊤ : presieve X) := λ x t₁ t₂ h₁ h₂, begin have q₁ := h₁ (𝟙 X) (by simp), have q₂ := h₂ (𝟙 X) (by simp), simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂, rw [q₁, q₂], end /-- We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique amalgamation. This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents. Using `compatible_iff_sieve_compatible`, this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4. -/ def is_sheaf_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop := ∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t /-- This is an equivalent condition to be a sheaf, which is useful for the abstraction to local operators on elementary toposes. However this definition is defined only for sieves, not presieves. The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`. This version is also useful to establish that being a sheaf is preserved under isomorphism of presheaves. See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of [Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8. -/ def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v₁) (S : sieve X) : Prop := ∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f -- TODO: We can generalize the universe parameter v₁ above by composing with -- appropriate `ulift_functor`s. /-- (Implementation). This is a (primarily internal) equivalence between natural transformations and compatible families. Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4. -/ def nat_trans_equiv_compatible_family {P : Cᵒᵖ ⥤ Type v₁} : (S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} := { to_fun := λ α, begin refine ⟨λ Y f hf, _, _⟩, { apply α.app (op Y) ⟨_, hf⟩ }, { rw compatible_iff_sieve_compatible, intros Y Z f g hf, dsimp, rw ← functor_to_types.naturality _ _ α g.op, refl } end, inv_fun := λ t, { app := λ Y f, t.1 _ f.2, naturality' := λ Y Z g, begin ext ⟨f, hf⟩, apply t.2.to_sieve_compatible _, end }, left_inv := λ α, begin ext X ⟨_, _⟩, refl end, right_inv := begin rintro ⟨x, hx⟩, refl, end } /-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/ lemma extension_iff_amalgamation {P : Cᵒᵖ ⥤ Type v₁} (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) : S.functor_inclusion ≫ g = x ↔ (nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) := begin change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩, split, { rintro rfl Y f hf, rw yoneda_equiv_naturality, dsimp, simp }, -- See note [dsimp, simp]. { intro h, ext Y ⟨f, hf⟩, have : _ = x.app Y _ := h f hf, rw yoneda_equiv_naturality at this, rw ← this, dsimp, simp }, -- See note [dsimp, simp]. end /-- The yoneda version of the sheaf condition is equivalent to the sheaf condition. C2.1.4 of [Elephant]. -/ lemma is_sheaf_for_iff_yoneda_sheaf_condition {P : Cᵒᵖ ⥤ Type v₁} : is_sheaf_for P S ↔ yoneda_sheaf_condition P S := begin rw [is_sheaf_for, yoneda_sheaf_condition], simp_rw [extension_iff_amalgamation], rw equiv.forall_congr_left' nat_trans_equiv_compatible_family, rw subtype.forall, apply ball_congr, intros x hx, rw equiv.exists_unique_congr_left _, simp, end /-- If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor) to `P` can be (uniquely) extended to all of `yoneda.obj X`. f S → P ↓ ↗ yX -/ noncomputable def is_sheaf_for.extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (f : S.functor ⟶ P) : yoneda.obj X ⟶ P := classical.some (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie that the triangle below commutes, provided `P` is a sheaf for `S` f S → P ↓ ↗ yX -/ @[simp, reassoc] lemma is_sheaf_for.functor_inclusion_comp_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f := classical.some_spec (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- The extension of `f` to `yoneda.obj X` is unique. -/ lemma is_sheaf_for.unique_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) {f : S.functor ⟶ P} (t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) : t = h.extend f := ((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f)) /-- If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X` to `P` agree when restricted to the subfunctor given by `S`, they are equal. -/ lemma is_sheaf_for.hom_ext {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) : t₁ = t₂ := (h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm /-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/ lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for : is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔ is_sheaf_for P R := begin rw [is_separated_for, ←forall_and_distrib], apply forall_congr, intro x, split, { intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 }, { intros h, refine ⟨_, (exists_of_exists_unique ∘ h)⟩, intros t₁ t₂ ht₁ ht₂, apply (h _).unique ht₁ ht₂, exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ } end /-- If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`. -/ lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) : (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) → is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, exact and.intro t, end /-- If `P` is a sheaf for `R`, it is separated for `R`. -/ lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R := λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1 /-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/ noncomputable def is_sheaf_for.amalgamate (t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) : P.obj (op X) := classical.some (t x hx).exists lemma is_sheaf_for.is_amalgamation (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) : x.is_amalgamation (t.amalgamate x hx) := classical.some_spec (t x hx).exists @[simp] lemma is_sheaf_for.valid_glue (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) : P.map f.op (t.amalgamate x hx) = x f Hf := t.is_amalgamation hx f Hf /-- C2.1.3 in [Elephant] -/ lemma is_sheaf_for_iff_generate (R : presieve X) : is_sheaf_for P R ↔ is_sheaf_for P (generate R) := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_iff_generate, apply and_congr (iff.refl _), split, { intros q x hx, apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))), intros t ht, simpa [hx] using is_amalgamation_sieve_extend _ _ ht }, { intros q x hx, apply exists_imp_exists _ (q _ (hx.sieve_extend _)), intros t ht, simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht }, end /-- Every presheaf is a sheaf for the family {𝟙 X}. [Elephant] C2.1.5(i) -/ lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type w) : is_sheaf_for P (presieve.singleton (𝟙 X)) := begin intros x hx, refine ⟨x _ (presieve.singleton_self _), _, _⟩, { rintro _ _ ⟨rfl, rfl⟩, simp }, { intros t ht, simpa using ht _ (presieve.singleton_self _) } end /-- Every presheaf is a sheaf for the maximal sieve. [Elephant] C2.1.5(ii) -/ lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type w) : is_sheaf_for P ((⊤ : sieve X) : presieve X) := begin rw ← generate_of_singleton_split_epi (𝟙 X), rw ← is_sheaf_for_iff_generate, apply is_sheaf_for_singleton_iso, end /-- If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that "being a sheaf for a presieve" is a mathematical or hygenic property. -/ lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R := begin intros h x hx, let x' := x.comp_presheaf_map i.inv, have : x'.compatible := family_of_elements.compatible.comp_presheaf_map i.inv hx, obtain ⟨t, ht1, ht2⟩ := h x' this, use i.hom.app _ t, fsplit, { convert family_of_elements.is_amalgamation.comp_presheaf_map i.hom ht1, dsimp [x'], simp }, { intros y hy, rw (show y = (i.inv.app (op X) ≫ i.hom.app (op X)) y, by simp), simp [ ht2 (i.inv.app _ y) (family_of_elements.is_amalgamation.comp_presheaf_map i.inv hy)] } end /-- If a presieve `R` on `X` has a subsieve `S` such that: * `P` is a sheaf for `S`. * For every `f` in `R`, `P` is separated for the pullback of `S` along `f`, then `P` is a sheaf for `R`. This is closely related to [Elephant] C2.1.6(i). -/ lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (hS : is_sheaf_for P S) (trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) : is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, split, { intros x t₁ t₂ ht₁ ht₂, exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁) (is_amalgamation_restrict h x t₂ ht₂) }, { intros x hx, use hS.amalgamate _ (hx.restrict h), intros W j hj, apply (trans hj).ext, intros Y f hf, rw [←functor_to_types.map_comp_apply, ←op_comp, hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict, ←hx (𝟙 _) f _ _ (id_comp _)], simp }, end /-- If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which contains `S`. This is closely related to [Elephant] C2.1.6. -/ lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) : is_sheaf_for P R := is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for) /-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/ def is_separated (P : Cᵒᵖ ⥤ Type w) : Prop := ∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S /-- A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology. If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to check the sheaf condition at presieves in the pretopology. -/ def is_sheaf (P : Cᵒᵖ ⥤ Type w) : Prop := ∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type w} (hp : is_sheaf J P) (R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R := (is_sheaf_for_iff_generate R).2 $ hp _ hr lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type w) {J₁ J₂ : grothendieck_topology C} : J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P := λ h t X S hS, t S (h _ hS) lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type w) (h : is_sheaf J P) : is_separated J P := λ X S hS, (h S hS).is_separated_for /-- The property of being a sheaf is preserved by isomorphism. -/ lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' := λ X S hS, is_sheaf_for_iso i (h S hS) lemma is_sheaf_of_yoneda {P : Cᵒᵖ ⥤ Type v₁} (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P := λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS) /-- For a topology generated by a basis, it suffices to check the sheaf condition on the basis presieves only. -/ lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) : is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) := begin split, { intros PJ X R hR, rw is_sheaf_for_iff_generate, apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ }, { rintro PK X S ⟨R, hR, RS⟩, have gRS : ⇑(generate R) ≤ S, { apply gi_generate.gc.monotone_u, rwa sets_iff_generate }, apply is_sheaf_for_subsieve P gRS _, intros Y f, rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate], exact PK (pullback_arrows f R) (K.pullbacks f R hR) } end /-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/ lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P := λ X, by simp [is_sheaf_for_top_sieve] end presieve namespace equalizer variables {C : Type u₁} [category.{v₁} C] (P : Cᵒᵖ ⥤ Type (max v₁ u₁)) {X : C} (R : presieve X) (S : sieve X) noncomputable theory /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def first_obj : Type (max v₁ u₁) := ∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) /-- Show that `first_obj` is isomorphic to `family_of_elements`. -/ @[simps] def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P := { hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t, inv := pi.lift (λ f x, x _ f.2.2), hom_inv_id' := begin ext ⟨Y, f, hf⟩ p, simpa, end, inv_hom_id' := begin ext x Y f hf, apply limits.types.limit.lift_π_apply, end } instance : inhabited (first_obj P (⊥ : presieve X)) := ((first_obj_eq_family P _).to_equiv).inhabited /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def fork_map : P.obj (op X) ⟶ first_obj P R := pi.lift (λ f, P.map f.2.1.op) /-! This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and the definition of `is_sheaf_for`. -/ namespace sieve /-- The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used to check a family is compatible. -/ def second_obj : Type (max v₁ u₁) := ∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1)) /-- The map `p` of Equations (3,4) [MM92]. -/ def first_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f})) instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `a` of Equations (3,4) [MM92]. -/ def second_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op) lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S := begin apply limit.hom_ext, rintro ⟨Y, Z, g, f, hf⟩, simp [first_map, second_map, fork_map], end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P S) : ((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x := begin rw presieve.compatible_iff_sieve_compatible, split, { intro t, ext ⟨Y, Z, g, f, hf⟩, simpa [first_map, second_map] using t _ g hf }, { intros t Y Z f g hf, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ } end /-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/ lemma equalizer_sheaf_condition : presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) := begin rw [types.type_equalizer_iff_unique, ← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm], simp_rw ← compatible_iff, simp only [inv_hom_id_apply, iso.to_equiv_symm_fun], apply ball_congr, intros x tx, apply exists_unique_congr, intro t, rw ← iso.to_equiv_symm_fun, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [first_obj_eq_family, fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [first_obj_eq_family, fork_map] } end end sieve /-! This section establishes the equivalence between the sheaf condition of https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`. -/ namespace presieve variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : Type (max v₁ u₁) := ∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/ def first_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/ def second_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map], simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P R) : ((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x := begin rw presieve.pullback_compatible_iff, split, { intro t, ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩, simpa [first_map, second_map] using t hf hg }, { intros t Y Z f g hf hg, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ } end /-- `P` is a sheaf for `R`, iff the fork given by `w` is an equalizer. See https://stacks.math.columbia.edu/tag/00VM. -/ lemma sheaf_condition : R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) := begin rw types.type_equalizer_iff_unique, erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm, simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply], apply ball_congr, intros x hx, apply exists_unique_congr, intros t, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [fork_map] } end end presieve end equalizer variables {C : Type u₁} [category.{v₁} C] variables (J : grothendieck_topology C) /-- The category of sheaves on a grothendieck topology. -/ @[derive category] def SheafOfTypes (J : grothendieck_topology C) : Type (max u₁ v₁ (w+1)) := {P : Cᵒᵖ ⥤ Type w // presieve.is_sheaf J P} /-- The inclusion functor from sheaves to presheaves. -/ @[simps {rhs_md := semireducible}, derive [full, faithful]] def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type w) := full_subcategory_inclusion (presieve.is_sheaf J) /-- The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category of presheaves. -/ @[simps] def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type w) := { functor := SheafOfTypes_to_presheaf _, inverse := { obj := λ P, ⟨P, presieve.is_sheaf_bot⟩, map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f }, unit_iso := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } }, counit_iso := iso.refl _ } instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) := ⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩ end category_theory
4fac48c151d6a35a43891ea9ca95a2c587963e18
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0105.lean
9c207979e96048d1a6f96bb822c2850b29e7857b
[]
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
300
lean
variables (α : Type) (r : α → α → Prop) variable refl_r : ∀ x, r x x variable symm_r : ∀ {x y}, r x y → r y x variable trans_r : ∀ {x y z}, r x y → r y z → r x z example (a b c d : α) (hab : r a b) (hcb : r c b) (hcd : r c d) : r a d := trans_r (trans_r hab (symm_r hcb)) hcd
e32465b2f2b212848749b5c47a2746cc7355276d
690889011852559ee5ac4dfea77092de8c832e7e
/src/category_theory/sums/basic.lean
a68d6be7cad816a1a259ec03b3dbb2da1c218cc7
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
5,448
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.equivalence import category_theory.eq_to_hom /-# Disjoint unions of categories, functors, and natural transformations. -/ namespace category_theory universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation open sum section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₁) [𝒟 : category.{v₁} D] include 𝒞 𝒟 /-- `sum C D` gives the direct sum of two categories. -/ instance sum : category.{v₁} (C ⊕ D) := { hom := λ X Y, match X, Y with | inl X, inl Y := X ⟶ Y | inl X, inr Y := pempty | inr X, inl Y := pempty | inr X, inr Y := X ⟶ Y end, id := λ X, match X with | inl X := 𝟙 X | inr X := 𝟙 X end, comp := λ X Y Z f g, match X, Y, Z, f, g with | inl X, inl Y, inl Z, f, g := f ≫ g | inr X, inr Y, inr Z, f, g := f ≫ g end } @[simp] lemma sum_comp_inl {P Q R : C} (f : (inl P : C ⊕ D) ⟶ inl Q) (g : inl Q ⟶ inl R) : f ≫ g = (f : P ⟶ Q) ≫ (g : Q ⟶ R) := rfl @[simp] lemma sum_comp_inr {P Q R : D} (f : (inr P : C ⊕ D) ⟶ inr Q) (g : inr Q ⟶ inr R) : f ≫ g = (f : P ⟶ Q) ≫ (g : Q ⟶ R) := rfl end namespace sum variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₁) [𝒟 : category.{v₁} D] include 𝒞 𝒟 /-- `inl_` is the functor `X ↦ inl X`. -/ -- Unfortunate naming here, suggestions welcome. def inl_ : C ⥤ C ⊕ D := { obj := λ X, inl X, map := λ X Y f, f } @[simp] lemma inl_obj (X : C) : (inl_ C D).obj X = inl X := rfl @[simp] lemma inl_map {X Y : C} {f : X ⟶ Y} : (inl_ C D).map f = f := rfl /-- `inr_` is the functor `X ↦ inr X`. -/ def inr_ : D ⥤ C ⊕ D := { obj := λ X, inr X, map := λ X Y f, f } @[simp] lemma inr_obj (X : D) : (inr_ C D).obj X = inr X := rfl @[simp] lemma inr_map {X Y : D} {f : X ⟶ Y} : (inr_ C D).map f = f := rfl /-- The functor exchanging two direct summand categories. -/ def swap : C ⊕ D ⥤ D ⊕ C := { obj := λ X, match X with | inl X := inr X | inr X := inl X end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := f | inr X, inr Y, f := f end } @[simp] lemma swap_obj_inl (X : C) : (swap C D).obj (inl X) = inr X := rfl @[simp] lemma swap_obj_inr (X : D) : (swap C D).obj (inr X) = inl X := rfl @[simp] lemma swap_map_inl {X Y : C} {f : inl X ⟶ inl Y} : (swap C D).map f = f := rfl @[simp] lemma swap_map_inr {X Y : D} {f : inr X ⟶ inr Y} : (swap C D).map f = f := rfl namespace swap /-- `swap` gives an equivalence between `C ⊕ D` and `D ⊕ C`. -/ def equivalence : C ⊕ D ≌ D ⊕ C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by { cases X; refl })) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by { cases X; refl })) (by tidy)) instance is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (equivalence C D).functor) /-- The double swap on `C ⊕ D` is naturally isomorphic to the identity functor. -/ def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C ⊕ D) := (equivalence C D).unit_iso.symm end swap end sum variables {A : Type u₁} [𝒜 : category.{v₁} A] {B : Type u₁} [ℬ : category.{v₁} B] {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₁} [𝒟 : category.{v₁} D] include 𝒜 ℬ 𝒞 𝒟 namespace functor /-- The sum of two functors. -/ def sum (F : A ⥤ B) (G : C ⥤ D) : A ⊕ C ⥤ B ⊕ D := { obj := λ X, match X with | inl X := inl (F.obj X) | inr X := inr (G.obj X) end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := F.map f | inr X, inr Y, f := G.map f end, map_id' := λ X, begin cases X; unfold_aux, erw F.map_id, refl, erw G.map_id, refl end, map_comp' := λ X Y Z f g, match X, Y, Z, f, g with | inl X, inl Y, inl Z, f, g := by { unfold_aux, erw F.map_comp, refl } | inr X, inr Y, inr Z, f, g := by { unfold_aux, erw G.map_comp, refl } end } @[simp] lemma sum_obj_inl (F : A ⥤ B) (G : C ⥤ D) (a : A) : (F.sum G).obj (inl a) = inl (F.obj a) := rfl @[simp] lemma sum_obj_inr (F : A ⥤ B) (G : C ⥤ D) (c : C) : (F.sum G).obj (inr c) = inr (G.obj c) := rfl @[simp] lemma sum_map_inl (F : A ⥤ B) (G : C ⥤ D) {a a' : A} (f : inl a ⟶ inl a') : (F.sum G).map f = F.map f := rfl @[simp] lemma sum_map_inr (F : A ⥤ B) (G : C ⥤ D) {c c' : C} (f : inr c ⟶ inr c') : (F.sum G).map f = G.map f := rfl end functor namespace nat_trans /-- The sum of two natural transformations. -/ def sum {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.sum H ⟶ G.sum I := { app := λ X, match X with | inl X := α.app X | inr X := β.app X end, naturality' := λ X Y f, match X, Y, f with | inl X, inl Y, f := begin unfold_aux, erw α.naturality, refl, end | inr X, inr Y, f := begin unfold_aux, erw β.naturality, refl, end end } @[simp] lemma sum_app_inl {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (a : A) : (sum α β).app (inl a) = α.app a := rfl @[simp] lemma sum_app_inr {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (c : C) : (sum α β).app (inr c) = β.app c := rfl end nat_trans end category_theory
df3fb072b15ba1370dfc3723a0f5f05e877d0e9b
b147e1312077cdcfea8e6756207b3fa538982e12
/algebra/ring.lean
1fd021ecfdc1703c45294373b9d987719e3207b1
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,378
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ import algebra.group tactic data.set.basic universes u v variable {α : Type u} section variable [semiring α] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm end 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 } attribute [trans] dvd.trans section variables [ring α] (a b c d e : α) lemma mul_neg_one (a : α) : a * -1 = -a := by simp lemma neg_one_mul (a : α) : -1 * a = -a := by simp theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end ... = d : begin rewrite h, simp [@add_sub_cancel α] end theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end section comm_ring variable [comm_ring α] @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ end comm_ring class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_add : ∀ {x y}, f (x + y) = f x + f y) (map_mul : ∀ {x y}, f (x * y) = f x * f y) (map_one : f 1 = 1) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] variables (f : α → β) [is_ring_hom f] {x y : α} lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] lemma map_sub : f (x - y) = f x - f y := by simp [map_add f, map_neg f] instance id : is_ring_hom (@id α) := by refine {..}; intros; refl instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl, map_one := by simp [map_one f]; exact map_one g } end is_ring_hom set_option old_structure_cmd true class nonzero_comm_ring (α : Type*) extends zero_ne_one_class α, comm_ring α instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] : nonzero_comm_ring α := { ..id } /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α section domain variable [domain α] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ section variables [s : integral_domain α] (a b c d e : α) include s instance integral_domain.to_domain : domain α := {..s} theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha] theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc] end
b6569e0978cf929e973ad27d4dcf8333e5e63400
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/algebra/ordered_ring.lean
e979bb13104b0efcfac9e091e254619e1cfca125
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
17,196
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import order.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)) ⟩ 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] 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}), .. (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 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 | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm] 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 end with_top
83067d8ee444599f04af225324a147ce7c2bb560
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/algebra/module/basic.lean
ba54b716622dd4fe904f58d87e274136d29d4d83
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,275
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.big_operators.basic import algebra.group.hom import algebra.ring.basic import data.rat.cast import group_theory.group_action.group import tactic.nth_rewrite /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. ## Implementation notes * `vector_space` and `module` are abbreviations for `semimodule R M`. ## Tags semimodule, module, vector space -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x /-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/ protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variable (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `semimodule` over a `ring` carries a natural `add_comm_group` structure. -/ def semimodule.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [semimodule R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul], }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] /-- A structure containing most informations as in a semimodule, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a semimodule structure by checking less properties, in `semimodule.of_core`. -/ @[nolint has_inhabited_instance] structure semimodule.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/ def semimodule.of_core (H : semimodule.core R M) : semimodule R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- Modules are defined as an `abbreviation` for semimodules, if the base semiring is a ring. (A previous definition made `module` a structure defined to be `semimodule`.) This has as advantage that modules are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for modules as well. A cosmetic disadvantage is that one can not extend modules as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "module definition" /-- A module is the same as a semimodule, except the scalar semiring is actually a ring. This is the traditional generalization of spaces like `ℤ^n`, which have a natural addition operation and a way to multiply them by elements of a ring, but no multiplication operation between vectors. -/ abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] := semimodule R M /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h, λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module /-- A semimodule over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ theorem semimodule.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [semimodule R M] : subsingleton M := ⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩ @[priority 910] -- see Note [lower instance priority] instance semiring.to_semimodule [semiring R] : semimodule R R := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero } @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- Vector spaces are defined as an `abbreviation` for semimodules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "vector space definition" /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] := semimodule R M namespace add_comm_monoid open add_monoid variables [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := nsmul, smul_add := λ _ _ _, nsmul_add _ _ _, add_smul := λ _ _ _, add_nsmul _ _ _, mul_smul := λ _ _ _, mul_nsmul _ _ _, one_smul := one_nsmul, zero_smul := zero_nsmul, smul_zero := nsmul_zero } end add_comm_monoid namespace add_comm_group variables [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.nsmul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n •ℕ b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = n •ℕ x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {M : Type*} [add_comm_group M] [module R M] (n : ℤ) (b : M) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.nsmul_eq_smul, }, { dsimp, rw semimodule.nsmul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M] (n : ℤ) (b : M) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.nsmul_eq_smul, f.map_nsmul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module
3a104fac7807789055c5dbc96de61b88288290e8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/with_one.lean
e2e0c8b5b9f4db23d7d0424b47fdc5127761333b
[]
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
7,505
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ring.basic import Mathlib.data.equiv.basic import Mathlib.PostPort universes u_1 u v namespace Mathlib /-- Add an extra element `1` to a type -/ def with_one (α : Type u_1) := Option α namespace with_one protected instance Mathlib.with_zero.monad : Monad with_zero := option.monad protected instance has_one {α : Type u} : HasOne (with_one α) := { one := none } protected instance Mathlib.with_zero.inhabited {α : Type u} : Inhabited (with_zero α) := { default := 0 } protected instance Mathlib.with_zero.nontrivial {α : Type u} [Nonempty α] : nontrivial (with_zero α) := option.nontrivial protected instance Mathlib.with_zero.has_coe_t {α : Type u} : has_coe_t α (with_zero α) := has_coe_t.mk some theorem Mathlib.with_zero.some_eq_coe {α : Type u} {a : α} : some a = ↑a := rfl @[simp] theorem coe_ne_one {α : Type u} {a : α} : ↑a ≠ 1 := option.some_ne_none a @[simp] theorem one_ne_coe {α : Type u} {a : α} : 1 ≠ ↑a := ne.symm coe_ne_one theorem Mathlib.with_zero.ne_zero_iff_exists {α : Type u} {x : with_zero α} : x ≠ 0 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance protected instance can_lift {α : Type u} : can_lift (with_one α) α := can_lift.mk coe (fun (a : with_one α) => a ≠ 1) sorry @[simp] theorem Mathlib.with_zero.coe_inj {α : Type u} {a : α} {b : α} : ↑a = ↑b ↔ a = b := option.some_inj protected theorem Mathlib.with_zero.cases_on {α : Type u} {P : with_zero α → Prop} (x : with_zero α) : P 0 → (∀ (a : α), P ↑a) → P x := option.cases_on protected instance Mathlib.with_zero.has_add {α : Type u} [Add α] : Add (with_zero α) := { add := option.lift_or_get Add.add } protected instance monoid {α : Type u} [semigroup α] : monoid (with_one α) := monoid.mk Mul.mul sorry 1 sorry sorry protected instance Mathlib.with_zero.add_comm_monoid {α : Type u} [add_comm_semigroup α] : add_comm_monoid (with_zero α) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry /-- `coe` as a bundled morphism -/ def coe_mul_hom {α : Type u} [Mul α] : mul_hom α (with_one α) := mul_hom.mk coe sorry /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/ def Mathlib.with_zero.lift {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] : add_hom α β ≃ (with_zero α →+ β) := equiv.mk (fun (f : add_hom α β) => add_monoid_hom.mk (fun (x : with_zero α) => option.cases_on x 0 ⇑f) sorry sorry) (fun (F : with_zero α →+ β) => add_hom.comp (add_monoid_hom.to_add_hom F) with_zero.coe_add_hom) sorry sorry @[simp] theorem Mathlib.with_zero.lift_coe {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] (f : add_hom α β) (x : α) : coe_fn (coe_fn with_zero.lift f) ↑x = coe_fn f x := rfl @[simp] theorem lift_one {α : Type u} [semigroup α] {β : Type v} [monoid β] (f : mul_hom α β) : coe_fn (coe_fn lift f) 1 = 1 := rfl theorem Mathlib.with_zero.lift_unique {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] (f : with_zero α →+ β) : f = coe_fn with_zero.lift (add_hom.comp (add_monoid_hom.to_add_hom f) with_zero.coe_add_hom) := Eq.symm (equiv.apply_symm_apply with_zero.lift f) /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ def Mathlib.with_zero.map {α : Type u} {β : Type v} [add_semigroup α] [add_semigroup β] (f : add_hom α β) : with_zero α →+ with_zero β := coe_fn with_zero.lift (add_hom.comp with_zero.coe_add_hom f) @[simp] theorem Mathlib.with_zero.coe_add {α : Type u} [Add α] (a : α) (b : α) : ↑(a + b) = ↑a + ↑b := rfl end with_one namespace with_zero -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance protected instance can_lift {α : Type u} : can_lift (with_zero α) α := can_lift.mk coe (fun (a : with_zero α) => a ≠ 0) sorry protected instance has_one {α : Type u} [one : HasOne α] : HasOne (with_zero α) := { one := ↑1 } @[simp] theorem coe_one {α : Type u} [HasOne α] : ↑1 = 1 := rfl protected instance mul_zero_class {α : Type u} [Mul α] : mul_zero_class (with_zero α) := mul_zero_class.mk (fun (o₁ o₂ : with_zero α) => option.bind o₁ fun (a : α) => option.map (fun (b : α) => a * b) o₂) 0 sorry sorry @[simp] theorem coe_mul {α : Type u} [Mul α] {a : α} {b : α} : ↑(a * b) = ↑a * ↑b := rfl @[simp] theorem zero_mul {α : Type u} [Mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] theorem mul_zero {α : Type u} [Mul α] (a : with_zero α) : a * 0 = 0 := option.cases_on a (Eq.refl (none * 0)) fun (a : α) => Eq.refl (some a * 0) protected instance semigroup {α : Type u} [semigroup α] : semigroup (with_zero α) := semigroup.mk mul_zero_class.mul sorry protected instance comm_semigroup {α : Type u} [comm_semigroup α] : comm_semigroup (with_zero α) := comm_semigroup.mk semigroup.mul sorry sorry protected instance monoid_with_zero {α : Type u} [monoid α] : monoid_with_zero (with_zero α) := monoid_with_zero.mk mul_zero_class.mul sorry 1 sorry sorry mul_zero_class.zero sorry sorry protected instance comm_monoid_with_zero {α : Type u} [comm_monoid α] : comm_monoid_with_zero (with_zero α) := comm_monoid_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry sorry monoid_with_zero.zero sorry sorry /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ def inv {α : Type u} [has_inv α] (x : with_zero α) : with_zero α := do let a ← x return (a⁻¹) protected instance has_inv {α : Type u} [has_inv α] : has_inv (with_zero α) := has_inv.mk inv @[simp] theorem coe_inv {α : Type u} [has_inv α] (a : α) : ↑(a⁻¹) = (↑a⁻¹) := rfl @[simp] theorem inv_zero {α : Type u} [has_inv α] : 0⁻¹ = 0 := rfl @[simp] theorem inv_one {α : Type u} [group α] : 1⁻¹ = 1 := sorry /-- if `G` is a group then `with_zero G` is a group with zero. -/ protected instance group_with_zero {α : Type u} [group α] : group_with_zero (with_zero α) := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry theorem div_coe {α : Type u} [group α] (a : α) (b : α) : ↑a / ↑b = ↑(a * (b⁻¹)) := rfl protected instance comm_group_with_zero {α : Type u} [comm_group α] : comm_group_with_zero (with_zero α) := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry protected instance semiring {α : Type u} [semiring α] : semiring (with_zero α) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry mul_zero_class.mul sorry monoid_with_zero.one sorry sorry sorry sorry sorry sorry
c4a20e17640b005066b97aab61488f0cf371e478
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/concrete_category.lean
9431a5aa1e86f4bbcf64d10cf60afd92cb9726d4
[ "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
576
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.limits.shapes.kernels import category_theory.concrete_category.basic import category_theory.concrete_category.elementwise /-! # Facts about limits of functors into concrete categories This file doesn't yet attempt to be exhaustive; it just contains lemmas that are useful while comparing categorical limits with existing constructions in concrete categories. -/ universes u open category_theory
e76f841f2e30bec73146bb1ccd00d3abd45bdf54
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/PrettyPrinter/Delaborator/TopDownAnalyze.lean
8f1b41081a18a7c22bc2b30b0190237b4722f298
[ "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
27,771
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Std.Data.RBMap import Lean.Meta.SynthInstance import Lean.Util.FindMVar import Lean.Util.FindLevelMVar import Lean.Util.CollectLevelParams import Lean.Util.ReplaceLevel import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.Elab.Config /-! The top-down analyzer is an optional preprocessor to the delaborator that aims to determine the minimal annotations necessary to ensure that the delaborated expression can be re-elaborated correctly. Currently, the top-down analyzer is neither sound nor complete: there may be edge-cases in which the expression can still not be re-elaborated correctly, and it may also add many annotations that are not strictly necessary. -/ namespace Lean open Lean.Meta open Lean.SubExpr open Std (RBMap) register_builtin_option pp.analyze : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) determine annotations sufficient to ensure round-tripping" } register_builtin_option pp.analyze.checkInstances : Bool := { -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances -- that would otherwise be easy to synthesize. We may consider threading the instances in the future, -- or at least tracking a bool for whether the instances have been lost. defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) confirm that instances can be re-synthesized" } register_builtin_option pp.analyze.typeAscriptions : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) add type ascriptions when deemed necessary" } register_builtin_option pp.analyze.trustSubst : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' applications that can delab to ▸ are 'regular'" } register_builtin_option pp.analyze.trustOfNat : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up" } register_builtin_option pp.analyze.trustOfScientific : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up" } register_builtin_option pp.analyze.trustCoe : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) always assume a coercion can be correctly inserted" } -- TODO: this is an arbitrary special case of a more general principle. register_builtin_option pp.analyze.trustSubtypeMk : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred" } register_builtin_option pp.analyze.trustId : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred" } register_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type" } register_builtin_option pp.analyze.omitMax : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)" } register_builtin_option pp.analyze.knowsType : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the type of the original expression is known" } register_builtin_option pp.analyze.explicitHoles : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) use `_` for explicit arguments that can be inferred" } def getPPAnalyze (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue def getPPAnalyzeCheckInstances (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue def getPPAnalyzeTypeAscriptions (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue def getPPAnalyzeTrustSubst (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue def getPPAnalyzeTrustOfNat (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue def getPPAnalyzeTrustOfScientific (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue def getPPAnalyzeTrustId (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue def getPPAnalyzeTrustCoe (o : Options) : Bool := o.get pp.analyze.trustCoe.name pp.analyze.trustCoe.defValue def getPPAnalyzeTrustSubtypeMk (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue def getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue def getPPAnalyzeOmitMax (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue def getPPAnalyzeKnowsType (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue def getPPAnalyzeExplicitHoles (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue def getPPAnalysisSkip (o : Options) : Bool := o.get `pp.analysis.skip false def getPPAnalysisHole (o : Options) : Bool := o.get `pp.analysis.hole false def getPPAnalysisNamedArg (o : Options) : Bool := o.get `pp.analysis.namedArg false def getPPAnalysisLetVarType (o : Options) : Bool := o.get `pp.analysis.letVarType false def getPPAnalysisNeedsType (o : Options) : Bool := o.get `pp.analysis.needsType false def getPPAnalysisBlockImplicit (o : Options) : Bool := o.get `pp.analysis.blockImplicit false namespace PrettyPrinter.Delaborator def returnsPi (motive : Expr) : MetaM Bool := do lambdaTelescope motive fun _ b => return b.isForall def isNonConstFun (motive : Expr) : MetaM Bool := do match motive with | Expr.lam _ _ b _ => isNonConstFun b | _ => return motive.hasLooseBVars def isSimpleHOFun (motive : Expr) : MetaM Bool := return not (← returnsPi motive) && not (← isNonConstFun motive) def isType2Type (motive : Expr) : MetaM Bool := do match ← inferType motive with | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => return true | _ => return false def isFOLike (motive : Expr) : MetaM Bool := do let f := motive.getAppFn return f.isFVar || f.isConst def isIdLike (arg : Expr) : Bool := -- TODO: allow `id` constant as well? match arg with | Expr.lam _ _ (Expr.bvar ..) .. => true | _ => false def isCoe (e : Expr) : Bool := -- TODO: `coeSort? Builtins doesn't seem to render them anyway -- TODO: should we delete this function, we want to eagerly expand all coercions e.isAppOfArity ``CoeT.coe 4 || (e.isAppOf ``CoeFun.coe && e.getAppNumArgs >= 4) || e.isAppOfArity ``CoeSort.coe 4 def isStructureInstance (e : Expr) : MetaM Bool := do match e.isConstructorApp? (← getEnv) with | some s => return isStructure (← getEnv) s.induct | none => return false namespace TopDownAnalyze partial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findMVar? fun mvarId => match mctx.findDecl? mvarId with | some mdecl => mdecl.depth == mctx.depth | _ => false partial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findLevelMVar? fun mvarId => mctx.findLevelDepth? mvarId == some mctx.depth private def valUnknown (e : Expr) : MetaM Bool := do hasMVarAtCurrDepth (← instantiateMVars e) private def typeUnknown (e : Expr) : MetaM Bool := do valUnknown (← inferType e) def isHBinOp (e : Expr) : Bool := Id.run do -- TODO: instead of tracking these explicitly, -- consider a more general solution that checks for defaultInstances if e.getAppNumArgs != 6 then return false let f := e.getAppFn if !f.isConst then return false -- Note: we leave out `HPow.hPow because we expect its homogeneous -- version will change soon let ops := #[ `HOr.hOr, `HXor.hXor, `HAnd.hAnd, `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen, `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod, `HShiftLeft.hShiftLeft, `HShiftRight] ops.any fun op => op == f.constName! def replaceLPsWithVars (e : Expr) : MetaM Expr := do if !e.hasLevelParam then return e let lps := collectLevelParams {} e |>.params let mut replaceMap : Std.HashMap Name Level := {} for lp in lps do replaceMap := replaceMap.insert lp (← mkFreshLevelMVar) return e.replaceLevel fun | Level.param n .. => replaceMap.find! n | l => if !l.hasParam then some l else none def isDefEqAssigning (t s : Expr) : MetaM Bool := do withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $ Meta.isDefEq t s def checkpointDefEq (t s : Expr) : MetaM Bool := do Meta.checkpointDefEq (mayPostpone := false) do isDefEqAssigning t s def isHigherOrder (type : Expr) : MetaM Bool := do forallTelescopeReducing type fun xs b => return xs.size > 0 && b.isSort def isFunLike (e : Expr) : MetaM Bool := do forallTelescopeReducing (← inferType e) fun xs _ => return xs.size > 0 def isSubstLike (e : Expr) : Bool := e.isAppOfArity ``Eq.ndrec 6 || e.isAppOfArity ``Eq.rec 6 def nameNotRoundtrippable (n : Name) : Bool := n.hasMacroScopes || isPrivateName n || containsNum n where containsNum | Name.str p .. => containsNum p | Name.num .. => true | Name.anonymous => false def mvarName (mvar : Expr) : MetaM Name := return (← mvar.mvarId!.getDecl).userName def containsBadMax : Level → Bool | Level.succ u .. => containsBadMax u | Level.max u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | _ => false open SubExpr structure Context where knowsType : Bool knowsLevel : Bool -- only constants look at this inBottomUp : Bool := false parentIsApp : Bool := false subExpr : SubExpr deriving Inhabited structure State where annotations : OptionsPerPos := {} postponed : Array (Expr × Expr) := #[] -- not currently used abbrev AnalyzeM := ReaderT Context (StateRefT State MetaM) instance (priority := low) : MonadReaderOf SubExpr AnalyzeM where read := Context.subExpr <$> read instance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr } def tryUnify (e₁ e₂ : Expr) : AnalyzeM Unit := do try let r ← isDefEqAssigning e₁ e₂ if !r then modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } pure () catch _ => modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } partial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do let argType ← inferType arg -- HAdd α α α let mvarType ← inferType mvar let fType ← inferType argType.getAppFn -- Type → Type → outParam Type let mType ← inferType mvarType.getAppFn inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs where inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do let fType ← whnf fType let mType ← whnf mType if not (i < args.size) then return () match fType, mType with | Expr.forallE _ fd fb _, Expr.forallE _ _ mb _ => do -- TODO: do I need to check (← okBottomUp? args[i] mvars[i] fuel).isSafe here? -- if so, I'll need to take a callback if fd.isOutParam then tryUnify (args[i]!) (mvars[i]!) inspectAux (fb.instantiate1 args[i]!) (mb.instantiate1 mvars[i]!) (i+1) args mvars | _, _ => return () partial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do let opts ← getOptions return e.isFVar || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity ``OfNat.ofNat 3) || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity ``OfScientific.ofScientific 5) partial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do -- Here we check if `e` can be safely elaborated without its expected type. -- These are incomplete (and possibly unsound) heuristics. -- TODO: do I need to snapshot the state before calling this? match fuel with | 0 => return false | fuel + 1 => if ← isTrivialBottomUp e then return true let f := e.getAppFn if !f.isConst && !f.isFVar then return false let args := e.getAppArgs let fType ← replaceLPsWithVars (← inferType e.getAppFn) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType e.getAppArgs.size for i in [:mvars.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! else if bInfos[i]! == BinderInfo.default then if ← isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! else if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (some mvars[i]!) fuel then tryUnify args[i]! mvars[i]! if ← (pure (isHBinOp e) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! if mvar?.isSome then tryUnify resultType (← inferType mvar?.get!) return !(← valUnknown resultType) def withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM α) : AnalyzeM α := do withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x builtin_initialize analyzeFailureId : InternalExceptionId ← registerInternalExceptionId `analyzeFailure def checkKnowsType : AnalyzeM Unit := do if not (← read).knowsType then throw $ Exception.internal analyzeFailureId def annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do let opts := (← get).annotations.findD pos {} |>.setBool n true trace[pp.analyze.annotate] "{pos} {n}" modify fun s => { s with annotations := s.annotations.insert pos opts } def annotateBool (n : Name) : AnalyzeM Unit := do annotateBoolAt n (← getPos) structure App.Context where f : Expr fType : Expr args : Array Expr mvars : Array Expr bInfos : Array BinderInfo forceRegularApp : Bool structure App.State where bottomUps : Array Bool higherOrders : Array Bool funBinders : Array Bool provideds : Array Bool namedArgs : Array Name := #[] abbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM) mutual partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do checkMaxHeartbeats "Delaborator.topDownAnalyze" trace[pp.analyze] "{(← read).knowsType}.{(← read).knowsLevel}" let e ← getExpr let opts ← getOptions if ← (pure !e.isAtomic) <&&> pure !(getPPProofs opts) <&&> (try Meta.isProof e catch _ => pure false) then if getPPProofsWithType opts then withType $ withKnowing true true $ analyze return () else withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do match (← getExpr) with | Expr.app .. => analyzeApp | Expr.forallE .. => analyzePi | Expr.lam .. => analyzeLam | Expr.const .. => analyzeConst | Expr.sort .. => analyzeSort | Expr.proj .. => analyzeProj | Expr.fvar .. => analyzeFVar | Expr.mdata .. => analyzeMData | Expr.letE .. => analyzeLet | Expr.lit .. => pure () | Expr.mvar .. => pure () | Expr.bvar .. => pure () where analyzeApp := do let mut willKnowType := (← read).knowsType if !(← read).knowsType && !(← canBottomUp (← getExpr)) then annotateBool `pp.analysis.needsType withType $ withKnowing true false $ analyze willKnowType := true else if ← (pure !(← read).knowsType <||> pure (← read).inBottomUp) <&&> isStructureInstance (← getExpr) then withType do annotateBool `pp.structureInstanceTypes withKnowing true false $ analyze willKnowType := true withKnowing willKnowType true $ analyzeAppStaged (← getExpr).getAppFn (← getExpr).getAppArgs analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do let fType ← replaceLPsWithVars (← inferType f) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType args.size let rest := args.extract mvars.size args.size let args := args.shrink mvars.size -- Unify with the expected type if (← read).knowsType then tryUnify (← inferType (mkAppN f args)) resultType let forceRegularApp : Bool := (getPPAnalyzeTrustSubst (← getOptions) && isSubstLike (← getExpr)) || (getPPAnalyzeTrustCoe (← getOptions) && isCoe (← getExpr)) || (getPPAnalyzeTrustSubtypeMk (← getOptions) && (← getExpr).isAppOfArity ``Subtype.mk 4) analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' { bottomUps := mkArray args.size false, higherOrders := mkArray args.size false, provideds := mkArray args.size false, funBinders := mkArray args.size false } if not rest.isEmpty then -- Note: this shouldn't happen for type-correct terms if !args.isEmpty then analyzeAppStaged (mkAppN f args) rest maybeAddBlockImplicit : AnalyzeM Unit := do -- See `MonadLift.noConfusion for an example where this is necessary. if !(← read).parentIsApp then let type ← inferType (← getExpr) if type.isForall && type.bindingInfo! == BinderInfo.implicit then annotateBool `pp.analysis.blockImplicit analyzeConst : AnalyzeM Unit := do let Expr.const _ ls .. ← getExpr | unreachable! if !(← read).knowsLevel && !ls.isEmpty then -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590 unless getPPAnalyzeOmitMax (← getOptions) && ls.any containsBadMax do annotateBool `pp.universes maybeAddBlockImplicit analyzePi : AnalyzeM Unit := do withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLam : AnalyzeM Unit := do if !(← read).knowsType then annotateBool `pp.funBinderTypes withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLet : AnalyzeM Unit := do let Expr.letE _ _ v _ .. ← getExpr | unreachable! if !(← canBottomUp v) then annotateBool `pp.analysis.letVarType withLetVarType $ withKnowing true false analyze withLetValue $ withKnowing true true analyze else withReader (fun ctx => { ctx with inBottomUp := true }) do withLetValue $ withKnowing true true analyze withLetBody analyze analyzeSort : AnalyzeM Unit := pure () analyzeProj : AnalyzeM Unit := withProj analyze analyzeFVar : AnalyzeM Unit := maybeAddBlockImplicit analyzeMData : AnalyzeM Unit := withMDataExpr analyze partial def analyzeAppStagedCore : AnalyzeAppM Unit := do collectBottomUps checkOutParams collectHigherOrders hBinOpHeuristic collectTrivialBottomUps discard <| processPostponed (mayPostpone := true) applyFunBinderHeuristic analyzeFn for i in [:(← read).args.size] do analyzeArg i maybeSetExplicit where collectBottomUps := do let { args, mvars, bInfos, ..} ← read for target in [fun _ => none, fun i => some mvars[i]!] do for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (target i) then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } checkOutParams := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! collectHigherOrders := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if not (bInfos[i]! == BinderInfo.implicit || bInfos[i]! == BinderInfo.strictImplicit) then continue if not (← isHigherOrder (← inferType args[i]!)) then continue if getPPAnalyzeTrustId (← getOptions) && isIdLike args[i]! then continue if getPPAnalyzeTrustKnownFOType2TypeHOFuns (← getOptions) && not (← valUnknown mvars[i]!) && (← isType2Type (args[i]!)) && (← isFOLike (args[i]!)) then continue tryUnify args[i]! mvars[i]! modify fun s => { s with higherOrders := s.higherOrders.set! i true } hBinOpHeuristic := do let { mvars, ..} ← read if ← (pure (isHBinOp (← getExpr)) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! collectTrivialBottomUps := do -- motivation: prevent levels from printing in -- Boo.mk : {α : Type u_1} → {β : Type u_2} → α → β → Boo.{u_1, u_2} α β let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← valUnknown mvars[i]! <&&> isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } applyFunBinderHeuristic := do let { args, mvars, bInfos, .. } ← read let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do match ← getExpr, mvarType with | Expr.lam .., Expr.forallE _ t b .. => let mut annotated := false for i in [:argIdx] do if ← pure (bInfos[i]! == BinderInfo.implicit) <&&> valUnknown mvars[i]! <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]!) then annotateBool `pp.funBinderTypes tryUnify args[i]! mvars[i]! -- Note: currently we always analyze the lambda binding domains in `analyzeLam` -- (so we don't need to analyze it again here) annotated := true break let annotatedBody ← withBindingBody Name.anonymous (core argIdx b) return annotated || annotatedBody | _, _ => return false for i in [:args.size] do if bInfos[i]! == BinderInfo.default then let b ← withNaryArg i (core i (← inferType mvars[i]!)) if b then modify fun s => { s with funBinders := s.funBinders.set! i true } analyzeFn := do -- Now, if this is the first staging, analyze the n-ary function without expected type let {f, fType, forceRegularApp ..} ← read if !f.isApp then withKnowing false (forceRegularApp || !(← hasLevelMVarAtCurrDepth (← instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true)) annotateNamedArg (n : Name) : AnalyzeAppM Unit := do annotateBool `pp.analysis.namedArg modify fun s => { s with namedArgs := s.namedArgs.push n } analyzeArg (i : Nat) := do let { f, args, mvars, bInfos, forceRegularApp ..} ← read let { bottomUps, higherOrders, funBinders, ..} ← get let arg := args[i]! let argType ← inferType arg let processNaturalImplicit : AnalyzeAppM Unit := do if (← valUnknown mvars[i]! <||> pure higherOrders[i]!) && !forceRegularApp then annotateNamedArg (← mvarName mvars[i]!) modify fun s => { s with provideds := s.provideds.set! i true } else annotateBool `pp.analysis.skip withNaryArg (f.getAppNumArgs + i) do withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i]! }) do match bInfos[i]! with | BinderInfo.default => if ← pure (getPPAnalyzeExplicitHoles (← getOptions)) <&&> pure !(← valUnknown mvars[i]!) <&&> pure !(← readThe Context).inBottomUp <&&> pure !(← isFunLike arg) <&&> pure !funBinders[i]! <&&> checkpointDefEq mvars[i]! arg then annotateBool `pp.analysis.hole else modify fun s => { s with provideds := s.provideds.set! i true } | BinderInfo.implicit => processNaturalImplicit | BinderInfo.strictImplicit => processNaturalImplicit | BinderInfo.instImplicit => -- Note: apparently checking valUnknown here is not sound, because the elaborator -- will not happily assign instImplicits that it cannot synthesize let mut provided := true if !getPPInstances (← getOptions) then annotateBool `pp.analysis.skip provided := false else if getPPAnalyzeCheckInstances (← getOptions) then let instResult ← try trySynthInstance argType catch _ => pure LOption.undef match instResult with | LOption.some inst => if ← checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false else annotateNamedArg (← mvarName mvars[i]!) | _ => annotateNamedArg (← mvarName mvars[i]!) else annotateBool `pp.analysis.skip; provided := false modify fun s => { s with provideds := s.provideds.set! i provided } | BinderInfo.auxDecl => pure () if (← get).provideds[i]! then withKnowing (not (← typeUnknown mvars[i]!)) true analyze tryUnify mvars[i]! args[i]! maybeSetExplicit := do let { f, args, bInfos, ..} ← read if (← get).namedArgs.any nameNotRoundtrippable then annotateBool `pp.explicit for i in [:args.size] do if !(← get).provideds[i]! then withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole if bInfos[i]! == BinderInfo.instImplicit && getPPInstanceTypes (← getOptions) then withType (withKnowing true false analyze) end end TopDownAnalyze open TopDownAnalyze SubExpr def topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do let s₀ ← get traceCtx `pp.analyze do withReader (fun ctx => { ctx with config := Elab.Term.setElabConfig ctx.config }) do let ϕ : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; pure (← get).annotations try let knowsType := getPPAnalyzeKnowsType (← getOptions) ϕ { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e } |>.run' { : TopDownAnalyze.State } catch _ => trace[pp.analyze.error] "failed" pure {} finally set s₀ builtin_initialize registerTraceClass `pp.analyze registerTraceClass `pp.analyze.annotate registerTraceClass `pp.analyze.tryUnify registerTraceClass `pp.analyze.error end Lean.PrettyPrinter.Delaborator
59dd434023363057257b24206e4576e2d11d0d14
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/parseCore.lean
80334957f82196242f124b6646c90a842dc63ad0
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
338
lean
#lang lean4 import Lean.Parser def test : IO Unit := if System.Platform.isWindows then pure () -- TODO investigate why the following doesn't work on Windows else do let env ← Lean.mkEmptyEnvironment; Lean.Parser.parseFile env (System.mkFilePath ["..", "..", "..", "src", "Init", "Prelude.lean"]); IO.println "done" #eval test
99cde86f4c0eb35910341aa319c9e08906b7589b
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/ring/prod.lean
e3b5c9b826518757e76226457a3b9f018d572b86
[ "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
7,396
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Chris Hughes, Mario Carneiro, Yury Kudryashov -/ import algebra.group.prod import algebra.ring.basic import algebra.ring.equiv /-! # Semiring, ring etc structures on `R × S` In this file we define two-binop (`semiring`, `ring` etc) structures on `R × S`. We also prove trivial `simp` lemmas, and define the following operations on `ring_hom`s: * `fst R S : R × S →+* R`, `snd R S : R × S →+* S`: projections `prod.fst` and `prod.snd` as `ring_hom`s; * `f.prod g : `R →+* S × T`: sends `x` to `(f x, g x)`; * `f.prod_map g : `R × S → R' × S'`: `prod.map f g` as a `ring_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {R : Type*} {R' : Type*} {S : Type*} {S' : Type*} {T : Type*} {T' : Type*} namespace prod /-- Product of two distributive types is distributive. -/ instance [distrib R] [distrib S] : distrib (R × S) := { left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, .. prod.has_add, .. prod.has_mul } /-- Product of two `non_unital_non_assoc_semiring`s is a `non_unital_non_assoc_semiring`. -/ instance [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] : non_unital_non_assoc_semiring (R × S) := { .. prod.add_comm_monoid, .. prod.mul_zero_class, .. prod.distrib } /-- Product of two `non_unital_semiring`s is a `non_unital_semiring`. -/ instance [non_unital_semiring R] [non_unital_semiring S] : non_unital_semiring (R × S) := { .. prod.non_unital_non_assoc_semiring, .. prod.semigroup } /-- Product of two `non_assoc_semiring`s is a `non_assoc_semiring`. -/ instance [non_assoc_semiring R] [non_assoc_semiring S] : non_assoc_semiring (R × S) := { .. prod.non_unital_non_assoc_semiring, .. prod.mul_one_class } /-- Product of two semirings is a semiring. -/ instance [semiring R] [semiring S] : semiring (R × S) := { .. prod.add_comm_monoid, .. prod.monoid_with_zero, .. prod.distrib } /-- Product of two `non_unital_comm_semiring`s is a `non_unital_comm_semiring`. -/ instance [non_unital_comm_semiring R] [non_unital_comm_semiring S] : non_unital_comm_semiring (R × S) := { .. prod.non_unital_semiring, .. prod.comm_semigroup } /-- Product of two commutative semirings is a commutative semiring. -/ instance [comm_semiring R] [comm_semiring S] : comm_semiring (R × S) := { .. prod.semiring, .. prod.comm_monoid } instance [non_unital_non_assoc_ring R] [non_unital_non_assoc_ring S] : non_unital_non_assoc_ring (R × S) := { .. prod.add_comm_group, .. prod.non_unital_non_assoc_semiring } instance [non_unital_ring R] [non_unital_ring S] : non_unital_ring (R × S) := { .. prod.add_comm_group, .. prod.non_unital_semiring } instance [non_assoc_ring R] [non_assoc_ring S] : non_assoc_ring (R × S) := { .. prod.add_comm_group, .. prod.non_assoc_semiring } /-- Product of two rings is a ring. -/ instance [ring R] [ring S] : ring (R × S) := { .. prod.add_comm_group, .. prod.semiring } /-- Product of two `non_unital_comm_ring`s is a `non_unital_comm_ring`. -/ instance [non_unital_comm_ring R] [non_unital_comm_ring S] : non_unital_comm_ring (R × S) := { .. prod.non_unital_ring, .. prod.comm_semigroup } /-- Product of two commutative rings is a commutative ring. -/ instance [comm_ring R] [comm_ring S] : comm_ring (R × S) := { .. prod.ring, .. prod.comm_monoid } end prod namespace ring_hom variables (R S) [non_assoc_semiring R] [non_assoc_semiring S] /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `R`.-/ def fst : R × S →+* R := { to_fun := prod.fst, .. monoid_hom.fst R S, .. add_monoid_hom.fst R S } /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `S`.-/ def snd : R × S →+* S := { to_fun := prod.snd, .. monoid_hom.snd R S, .. add_monoid_hom.snd R S } variables {R S} @[simp] lemma coe_fst : ⇑(fst R S) = prod.fst := rfl @[simp] lemma coe_snd : ⇑(snd R S) = prod.snd := rfl section prod variables [non_assoc_semiring T] (f : R →+* S) (g : R →+* T) /-- Combine two ring homomorphisms `f : R →+* S`, `g : R →+* T` into `f.prod g : R →+* S × T` given by `(f.prod g) x = (f x, g x)` -/ protected def prod (f : R →+* S) (g : R →+* T) : R →+* S × T := { to_fun := λ x, (f x, g x), .. monoid_hom.prod (f : R →* S) (g : R →* T), .. add_monoid_hom.prod (f : R →+ S) (g : R →+ T) } @[simp] lemma prod_apply (x) : f.prod g x = (f x, g x) := rfl @[simp] lemma fst_comp_prod : (fst S T).comp (f.prod g) = f := ext $ λ x, rfl @[simp] lemma snd_comp_prod : (snd S T).comp (f.prod g) = g := ext $ λ x, rfl lemma prod_unique (f : R →+* S × T) : ((fst S T).comp f).prod ((snd S T).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables [non_assoc_semiring R'] [non_assoc_semiring S'] [non_assoc_semiring T] variables (f : R →+* R') (g : S →+* S') /-- `prod.map` as a `ring_hom`. -/ def prod_map : R × S →+* R' × S' := (f.comp (fst R S)).prod (g.comp (snd R S)) lemma prod_map_def : prod_map f g = (f.comp (fst R S)).prod (g.comp (snd R S)) := rfl @[simp] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl lemma prod_comp_prod_map (f : T →+* R) (g : T →+* S) (f' : R →+* R') (g' : S →+* S') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map end ring_hom namespace ring_equiv variables {R S} [non_assoc_semiring R] [non_assoc_semiring S] /-- Swapping components as an equivalence of (semi)rings. -/ def prod_comm : R × S ≃+* S × R := { ..add_equiv.prod_comm, ..mul_equiv.prod_comm } @[simp] lemma coe_prod_comm : ⇑(prod_comm : R × S ≃+* S × R) = prod.swap := rfl @[simp] lemma coe_prod_comm_symm : ⇑((prod_comm : R × S ≃+* S × R).symm) = prod.swap := rfl @[simp] lemma fst_comp_coe_prod_comm : (ring_hom.fst S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.snd R S := ring_hom.ext $ λ _, rfl @[simp] lemma snd_comp_coe_prod_comm : (ring_hom.snd S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.fst R S := ring_hom.ext $ λ _, rfl variables (R S) [subsingleton S] /-- A ring `R` is isomorphic to `R × S` when `S` is the zero ring -/ @[simps] def prod_zero_ring : R ≃+* R × S := { to_fun := λ x, (x, 0), inv_fun := prod.fst, map_add' := by simp, map_mul' := by simp, left_inv := λ x, rfl, right_inv := λ x, by cases x; simp } /-- A ring `R` is isomorphic to `S × R` when `S` is the zero ring -/ @[simps] def zero_ring_prod : R ≃+* S × R := { to_fun := λ x, (0, x), inv_fun := prod.snd, map_add' := by simp, map_mul' := by simp, left_inv := λ x, rfl, right_inv := λ x, by cases x; simp } end ring_equiv /-- The product of two nontrivial rings is not a domain -/ lemma false_of_nontrivial_of_product_domain (R S : Type*) [ring R] [ring S] [is_domain (R × S)] [nontrivial R] [nontrivial S] : false := begin have := is_domain.eq_zero_or_eq_zero_of_mul_eq_zero (show ((0 : R), (1 : S)) * (1, 0) = 0, by simp), rw [prod.mk_eq_zero,prod.mk_eq_zero] at this, rcases this with (⟨_,h⟩|⟨h,_⟩), { exact zero_ne_one h.symm }, { exact zero_ne_one h.symm } end
b2e256ccf3d024c723ce5349615dedd4a61c08dc
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/order/rel_iso.lean
6c6ffc8938bbb759e3f087833697fcda7f9894bf
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,047
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 logic.embedding import order.rel_classes import data.set.intervals.basic open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- A relation homomorphism with respect to a given pair of relations `r` and `s` is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/ @[nolint has_inhabited_instance] structure rel_hom {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) := (to_fun : α → β) (map_rel' : ∀ {a b}, r a b → s (to_fun a) (to_fun b)) infix ` →r `:25 := rel_hom namespace rel_hom instance : has_coe_to_fun (r →r s) := ⟨λ _, α → β, λ o, o.to_fun⟩ theorem map_rel (f : r →r s) : ∀ {a b}, r a b → s (f a) (f b) := f.map_rel' @[simp] theorem coe_fn_mk (f : α → β) (o) : (@rel_hom.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_fun (f : r →r s) : (f.to_fun : α → β) = f := rfl /-- The map `coe_fn : (r →r s) → (α → β)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r →r s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ h := by { congr, exact h } @[ext] theorem ext ⦃f g : r →r s⦄ (h : ∀ x, f x = g x) : f = g := coe_fn_inj (funext h) theorem ext_iff {f g : r →r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Identity map is a relation homomorphism. -/ @[refl] protected def id (r : α → α → Prop) : r →r r := ⟨id, λ a b, id⟩ /-- Composition of two relation homomorphisms is a relation homomorphism. -/ @[trans] protected def comp (g : s →r t) (f : r →r s) : r →r t := ⟨g.1 ∘ f.1, λ a b h, g.2 (f.2 h)⟩ @[simp] theorem id_apply (x : α) : rel_hom.id r x = x := rfl @[simp] theorem comp_apply (g : s →r t) (f : r →r s) (a : α) : (g.comp f) a = g (f a) := rfl /-- A relation homomorphism is also a relation homomorphism between dual relations. -/ protected def swap (f : r →r s) : swap r →r swap s := ⟨f, λ a b, f.map_rel⟩ /-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/ def preimage (f : α → β) (s : β → β → Prop) : f ⁻¹'o s →r s := ⟨f, λ a b, id⟩ protected theorem is_irrefl : ∀ (f : r →r s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o h)⟩ protected theorem is_asymm : ∀ (f : r →r s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o h₁) (o h₂)⟩ protected theorem acc (f : r →r s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.map_rel h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r →r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ lemma map_inf {α β : Type*} [semilattice_inf α] [linear_order β] (a : ((<) : β → β → Prop) →r ((<) : α → α → Prop)) (m n : β) : a (m ⊓ n) = a m ⊓ a n := begin symmetry, cases le_or_lt n m with h, { rw [inf_eq_right.mpr h, inf_eq_right], exact strict_mono.monotone (λ x y, a.map_rel) h, }, { rw [inf_eq_left.mpr (le_of_lt h), inf_eq_left], exact le_of_lt (a.map_rel h), }, end lemma map_sup {α β : Type*} [semilattice_sup α] [linear_order β] (a : ((>) : β → β → Prop) →r ((>) : α → α → Prop)) (m n : β) : a (m ⊔ n) = a m ⊔ a n := begin symmetry, cases le_or_lt m n with h, { rw [sup_eq_right.mpr h, sup_eq_right], exact strict_mono.monotone (λ x y, a.swap.map_rel) h, }, { rw [sup_eq_left.mpr (le_of_lt h), sup_eq_left], exact le_of_lt (a.map_rel h), }, end end rel_hom /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀{x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An increasing function is injective -/ lemma rel_hom.injective_of_increasing [is_trichotomous α r] [is_irrefl β s] (f : r →r s) : injective f := injective_of_increasing r s f (λ x y, f.map_rel) theorem surjective.well_founded_iff {f : α → β} (hf : surjective f) (o : ∀ {a b}, r a b ↔ s (f a) (f b)) : well_founded r ↔ well_founded s := iff.intro (begin apply rel_hom.well_founded, refine rel_hom.mk _ _, {exact classical.some hf.has_right_inverse}, intros a b h, apply o.2, convert h, iterate 2 { apply classical.some_spec hf.has_right_inverse }, end) (rel_hom.well_founded ⟨f, λ _ _, o.1⟩) /-- A relation embedding with respect to a given pair of relations `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure rel_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (map_rel_iff' : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ↪r `:25 := rel_embedding /-- An order embedding is an embedding `f : α ↪ β` such that `a ≤ b ↔ (f a) ≤ (f b)`. This definition is an abbreviation of `rel_embedding (≤) (≤)`. -/ abbreviation order_embedding (α β : Type*) [has_le α] [has_le β] := @rel_embedding α β (≤) (≤) infix ` ↪o `:25 := order_embedding /-- The induced relation on a subtype is an embedding under the natural inclusion. -/ definition subtype.rel_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ↪r r := ⟨embedding.subtype p, λ x y, iff.rfl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace rel_embedding /-- A relation embedding is also a relation homomorphism -/ def to_rel_hom (f : r ↪r s) : (r →r s) := { to_fun := f.to_embedding.to_fun, map_rel' := λ x y, (map_rel_iff' f).mp } instance : has_coe (r ↪r s) (r →r s) := ⟨to_rel_hom⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ↪r s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ @[simp] lemma to_rel_hom_eq_coe (f : r ↪r s) : f.to_rel_hom = f := rfl @[simp] lemma coe_coe_fn (f : r ↪r s) : ((f : r →r s) : α → β) = f := rfl theorem injective (f : r ↪r s) : injective f := f.inj' theorem map_rel_iff (f : r ↪r s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@rel_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ↪r s) : (f.to_embedding : α → β) = f := rfl /-- The map `coe_fn : (r ↪r s) → (α → β)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r ↪r s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by { congr, exact h } @[ext] theorem ext ⦃f g : r ↪r s⦄ (h : ∀ x, f x = g x) : f = g := coe_fn_inj (funext h) theorem ext_iff {f g : r ↪r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Identity map is a relation embedding. -/ @[refl] protected def refl (r : α → α → Prop) : r ↪r r := ⟨embedding.refl _, λ a b, iff.rfl⟩ /-- Composition of two relation embeddings is a relation embedding. -/ @[trans] protected def trans (f : r ↪r s) (g : s ↪r t) : r ↪r t := ⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩ instance (r : α → α → Prop) : inhabited (r ↪r r) := ⟨rel_embedding.refl _⟩ @[simp] theorem refl_apply (x : α) : rel_embedding.refl r x = x := rfl theorem trans_apply (f : r ↪r s) (g : s ↪r t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem coe_trans (f : r ↪r s) (g : s ↪r t) : ⇑(f.trans g) = g ∘ f := rfl /-- A relation embedding is also a relation embedding between dual relations. -/ protected def swap (f : r ↪r s) : swap r ↪r swap s := ⟨f.to_embedding, λ a b, f.map_rel_iff⟩ /-- If `f` is injective, then it is a relation embedding from the preimage relation of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ↪r s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ↪r s) : r = f ⁻¹'o s := by { ext a b, exact f.map_rel_iff } protected theorem is_irrefl : ∀ (f : r ↪r s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ↪r s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ↪r s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ↪r s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ↪r s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ↪r s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ↪r s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ↪r s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ↪r s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ↪r s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ↪r s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ↪r s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ↪r s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ↪r s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.map_rel_iff.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ↪r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ↪r s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict relations to show it is a relation embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ↪r s := begin haveI := @is_asymm.is_irrefl β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl /-- Embeddings of partial orders that preserve `<` also preserve `≤` -/ def order_embedding_of_lt_embedding [partial_order α] [partial_order β] (f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)) : α ↪o β := { map_rel_iff' := by { intros, simp [le_iff_lt_or_eq,f.map_rel_iff, f.injective] }, .. f } end rel_embedding namespace order_embedding variables [preorder α] [preorder β] (f : α ↪o β) /-- lt is preserved by order embeddings of preorders -/ def lt_embedding : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop) := { map_rel_iff' := by intros; simp [lt_iff_le_not_le, f.map_rel_iff], .. f } @[simp] lemma lt_embedding_apply (x : α) : f.lt_embedding x = f x := rfl theorem map_le_iff : ∀ {a b}, a ≤ b ↔ (f a) ≤ (f b) := f.map_rel_iff' @[simp] lemma apply_le_apply {a b} : f a ≤ f b ↔ a ≤ b := f.map_le_iff.symm theorem map_lt_iff : ∀ {a b}, a < b ↔ (f a) < (f b) := f.lt_embedding.map_rel_iff' @[simp] lemma apply_lt_apply {a b} : f a < f b ↔ a < b := f.map_lt_iff.symm @[simp] lemma apply_eq_apply {a b} : f a = f b ↔ a = b := f.injective.eq_iff protected theorem monotone : monotone f := λ x y, f.map_le_iff.1 protected theorem strict_mono : strict_mono f := λ x y, f.map_lt_iff.1 protected theorem acc (a : α) : acc (<) (f a) → acc (<) a := f.lt_embedding.acc a protected theorem well_founded : well_founded ((<) : β → β → Prop) → well_founded ((<) : α → α → Prop) := f.lt_embedding.well_founded protected theorem is_well_order [is_well_order β (<)] : is_well_order α (<) := f.lt_embedding.is_well_order /-- An order embedding is also an order embedding between dual orders. -/ protected def dual : order_dual α ↪o order_dual β := ⟨f.to_embedding, λ a b, f.map_rel_iff⟩ /-- A sctrictly monotone map from a linear order is an order embedding. --/ def of_strict_mono {α β} [linear_order α] [preorder β] (f : α → β) (h : strict_mono f) : α ↪o β := { to_fun := f, inj' := strict_mono.injective h, map_rel_iff' := λ a b, h.le_iff_le.symm } @[simp] lemma coe_of_strict_mono {α β} [linear_order α] [preorder β] {f : α → β} (h : strict_mono f) : ⇑(of_strict_mono f h) = f := rfl /-- Embedding of a subtype into the ambient type as an `order_embedding`. -/ def subtype (p : α → Prop) : subtype p ↪o α := ⟨embedding.subtype p, λ x y, iff.rfl⟩ @[simp] lemma coe_subtype (p : α → Prop) : ⇑(subtype p) = coe := rfl end order_embedding /-- A relation isomorphism is an equivalence that is also a relation embedding. -/ structure rel_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (map_rel_iff' : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃r `:25 := rel_iso /-- An order isomorphism is an equivalence such that `a ≤ b ↔ (f a) ≤ (f b)`. This definition is an abbreviation of `rel_iso (≤) (≤)`. -/ abbreviation order_iso (α β : Type*) [has_le α] [has_le β] := @rel_iso α β (≤) (≤) infix ` ≃o `:25 := order_iso namespace rel_iso /-- Convert an `rel_iso` to an `rel_embedding`. This function is also available as a coercion but often it is easier to write `f.to_rel_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_rel_embedding (f : r ≃r s) : r ↪r s := ⟨f.to_equiv.to_embedding, f.map_rel_iff'⟩ instance : has_coe (r ≃r s) (r ↪r s) := ⟨to_rel_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃r s) := ⟨λ _, α → β, λ f, f⟩ @[simp] lemma to_rel_embedding_eq_coe (f : r ≃r s) : f.to_rel_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃r s) : ((f : r ↪r s) : α → β) = f := rfl theorem map_rel_iff (f : r ≃r s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.map_rel_iff' lemma map_rel_iff'' {r : α → α → Prop} {s : β → β → Prop} (f : r ≃r s) {x y : α} : r x y ↔ s ((↑f : r ↪r s) x) ((↑f : r ↪r s) y) := f.map_rel_iff @[simp] theorem coe_fn_mk (f : α ≃ β) (o : ∀ ⦃a b⦄, r a b ↔ s (f a) (f b)) : (rel_iso.mk f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃r s) : (f.to_equiv : α → β) = f := rfl theorem injective_to_equiv : injective (to_equiv : (r ≃r s) → α ≃ β) | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h } /-- The map `coe_fn : (r ≃r s) → (α → β)` is injective. Lean fails to parse `function.injective (λ e : r ≃r s, (e : α → β))`, so we use a trick to say the same. -/ theorem injective_coe_fn : function.injective (λ (e : r ≃r s) (x : α), e x) := equiv.injective_coe_fn.comp injective_to_equiv @[ext] theorem ext ⦃f g : r ≃r s⦄ (h : ∀ x, f x = g x) : f = g := injective_coe_fn (funext h) theorem ext_iff {f g : r ≃r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Identity map is a relation isomorphism. -/ @[refl] protected def refl (r : α → α → Prop) : r ≃r r := ⟨equiv.refl _, λ a b, iff.rfl⟩ /-- Inverse map of a relation isomorphism is a relation isomorphism. -/ @[symm] protected def symm (f : r ≃r s) : s ≃r r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ /-- Composition of two relation isomorphisms is a relation isomorphism. -/ @[trans] protected def trans (f₁ : r ≃r s) (f₂ : s ≃r t) : r ≃r t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₁.map_rel_iff.trans f₂.map_rel_iff⟩ instance (r : α → α → Prop) : inhabited (r ≃r r) := ⟨rel_iso.refl _⟩ @[simp] lemma default_def (r : α → α → Prop) : default (r ≃r r) = rel_iso.refl r := rfl /-- a relation isomorphism is also a relation isomorphism between dual relations. -/ protected def swap (f : r ≃r s) : (swap r) ≃r (swap s) := ⟨f.to_equiv, λ _ _, f.map_rel_iff⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@rel_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : rel_iso.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≃r s) (g : s ≃r t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : r ≃r s) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃r s) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [e.map_rel_iff, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [e.map_rel_iff, e.apply_symm_apply] protected lemma bijective (e : r ≃r s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃r s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃r s) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : r ≃r s) : set.range e = set.univ := e.surjective.range_eq /-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/ protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃r s := ⟨f, λ a b, iff.rfl⟩ /-- A surjective relation embedding is a relation isomorphism. -/ noncomputable def of_surjective (f : r ↪r s) (H : surjective f) : r ≃r s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, by simp [f.map_rel_iff']⟩ @[simp] theorem of_surjective_coe (f : r ↪r s) (H) : (of_surjective f H : α → β) = f := rfl /-- Given relation isomorphisms `r₁ ≃r r₂` and `s₁ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the sum. -/ def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ α₂ r₁ r₂) (e₂ : @rel_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃r sum.lex r₂ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ /-- Given relation isomorphisms `r₁ ≃r r₂` and `s₁ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the product. -/ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ α₂ r₁ r₂) (e₂ : @rel_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃r prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.injective e, subst b₁, right, exact hg.2 h } } end⟩ instance : group (r ≃r r) := { one := rel_iso.refl r, mul := λ f₁ f₂, f₂.trans f₁, inv := rel_iso.symm, mul_assoc := λ f₁ f₂ f₃, rfl, one_mul := λ f, ext $ λ _, rfl, mul_one := λ f, ext $ λ _, rfl, mul_left_inv := λ f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃r r) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : r ≃r r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : r ≃r r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : r ≃r r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃r r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x end rel_iso namespace order_iso /-- Reinterpret an order isomorphism as an order embedding. -/ def to_order_embedding [has_le α] [has_le β] (e : α ≃o β) : α ↪o β := e.to_rel_embedding @[simp] lemma coe_to_order_embedding [has_le α] [has_le β] (e : α ≃o β) : ⇑(e.to_order_embedding) = e := rfl variables [preorder α] [preorder β] [preorder γ] protected lemma monotone (e : α ≃o β) : monotone e := e.to_order_embedding.monotone protected lemma strict_mono (e : α ≃o β) : strict_mono e := e.to_order_embedding.strict_mono @[simp] lemma apply_le_apply (e : α ≃o β) {x y : α} : e x ≤ e y ↔ x ≤ y := e.map_rel_iff.symm @[simp] lemma apply_lt_apply (e : α ≃o β) {x y : α} : e x < e y ↔ x < y := e.to_order_embedding.map_lt_iff.symm protected lemma bijective (e : α ≃o β) : bijective e := e.to_equiv.bijective protected lemma injective (e : α ≃o β) : injective e := e.to_equiv.injective protected lemma surjective (e : α ≃o β) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : α ≃o β) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma apply_eq_iff_eq (e : α ≃o β) {x y : α} : e x = e y ↔ x = y := e.to_equiv.apply_eq_iff_eq /-- Inverse of an order isomorphism. -/ def symm (e : α ≃o β) : β ≃o α := e.symm @[simp] lemma apply_symm_apply (e : α ≃o β) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (e : α ≃o β) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem symm_apply_eq (e : α ≃o β) {x : α} {y : β} : e.symm y = x ↔ y = e x := e.to_equiv.symm_apply_eq @[simp] lemma symm_symm (e : α ≃o β) : e.symm.symm = e := by { ext, refl } lemma symm_injective : injective (symm : (α ≃o β) → (β ≃o α)) := λ e e' h, by rw [← e.symm_symm, h, e'.symm_symm] /-- Composition of two order isomorphisms is an order isomorphism. -/ @[trans] def trans (e : α ≃o β) (e' : β ≃o γ) : α ≃o γ := e.trans e' @[simp] lemma coe_trans (e : α ≃o β) (e' : β ≃o γ) : ⇑(e.trans e') = e' ∘ e := rfl lemma trans_apply (e : α ≃o β) (e' : β ≃o γ) (x : α) : e.trans e' x = e' (e x) := rfl open set @[simp] lemma preimage_Iic (e : α ≃o β) (b : β) : e ⁻¹' (Iic b) = Iic (e.symm b) := by { ext x, simp [← e.apply_le_apply] } @[simp] lemma preimage_Ici (e : α ≃o β) (b : β) : e ⁻¹' (Ici b) = Ici (e.symm b) := by { ext x, simp [← e.apply_le_apply] } @[simp] lemma preimage_Iio (e : α ≃o β) (b : β) : e ⁻¹' (Iio b) = Iio (e.symm b) := by { ext x, simp [← e.apply_lt_apply] } @[simp] lemma preimage_Ioi (e : α ≃o β) (b : β) : e ⁻¹' (Ioi b) = Ioi (e.symm b) := by { ext x, simp [← e.apply_lt_apply] } @[simp] lemma preimage_Icc (e : α ≃o β) (a b : β) : e ⁻¹' (Icc a b) = Icc (e.symm a) (e.symm b) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_Ico (e : α ≃o β) (a b : β) : e ⁻¹' (Ico a b) = Ico (e.symm a) (e.symm b) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_Ioc (e : α ≃o β) (a b : β) : e ⁻¹' (Ioc a b) = Ioc (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_Ioo (e : α ≃o β) (a b : β) : e ⁻¹' (Ioo a b) = Ioo (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iio] /-- To show that `f : α → β`, `g : β → α` make up an order isomorphism of linear orders, it suffices to prove `cmp a (g b) = cmp (f a) b`. --/ def of_cmp_eq_cmp {α β} [linear_order α] [linear_order β] (f : α → β) (g : β → α) (h : ∀ (a : α) (b : β), cmp a (g b) = cmp (f a) b) : α ≃o β := have gf : ∀ (a : α), a = g (f a) := by { intro, rw [←cmp_eq_eq_iff, h, cmp_self_eq_eq] }, { to_fun := f, inv_fun := g, left_inv := λ a, (gf a).symm, right_inv := by { intro, rw [←cmp_eq_eq_iff, ←h, cmp_self_eq_eq] }, map_rel_iff' := by { intros, apply le_iff_le_of_cmp_eq_cmp, convert h _ _, apply gf } } /-- Order isomorphism between two equal sets. -/ def set_congr (s t : set α) (h : s = t) : s ≃o t := { to_equiv := equiv.set_congr h, map_rel_iff' := λ x y, iff.rfl } /-- Order isomorphism between `univ : set α` and `α`. -/ def set.univ : (set.univ : set α) ≃o α := { to_equiv := equiv.set.univ α, map_rel_iff' := λ x y, iff.rfl } end order_iso /-- If a function `f` is strictly monotone on a set `s`, then it defines an order isomorphism between `s` and its image. -/ protected noncomputable def strict_mono_incr_on.order_iso {α β} [linear_order α] [preorder β] (f : α → β) (s : set α) (hf : strict_mono_incr_on f s) : s ≃o f '' s := { to_equiv := hf.inj_on.bij_on_image.equiv _, map_rel_iff' := λ x y, iff.symm $ hf.le_iff_le x.2 y.2 } /-- A strictly monotone function from a linear order is an order isomorphism between its domain and its range. -/ protected noncomputable def strict_mono.order_iso {α β} [linear_order α] [preorder β] (f : α → β) (h_mono : strict_mono f) : α ≃o set.range f := { to_equiv := equiv.set.range f h_mono.injective, map_rel_iff' := λ a b, h_mono.le_iff_le.symm } /-- A strictly monotone surjective function from a linear order is an order isomorphism. -/ noncomputable def strict_mono.order_iso_of_surjective {α β} [linear_order α] [preorder β] (f : α → β) (h_mono : strict_mono f) (h_surj : surjective f) : α ≃o β := (h_mono.order_iso f).trans $ (order_iso.set_congr _ _ h_surj.range_eq).trans order_iso.set.univ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := (coe : p → α) ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel /-- The relation embedding from the inherited relation on a subset. -/ protected def rel_embedding (r : α → α → Prop) (p : set α) : subrel r p ↪r r := ⟨embedding.subtype _, λ a b, iff.rfl⟩ @[simp] theorem rel_embedding_apply (r : α → α → Prop) (p a) : subrel.rel_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := rel_embedding.is_well_order (subrel.rel_embedding r p) end subrel /-- Restrict the codomain of a relation embedding. -/ def rel_embedding.cod_restrict (p : set β) (f : r ↪r s) (H : ∀ a, f a ∈ p) : r ↪r subrel s p := ⟨f.to_embedding.cod_restrict p H, f.map_rel_iff'⟩ @[simp] theorem rel_embedding.cod_restrict_apply (p) (f : r ↪r s) (H a) : rel_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- An order isomorphism is also an order isomorphism between dual orders. -/ protected def order_iso.dual [preorder α] [preorder β] (f : α ≃o β) : order_dual α ≃o order_dual β := ⟨f.to_equiv, λ _ _, f.map_rel_iff⟩ section lattice_isos lemma order_iso.map_bot' [partial_order α] [partial_order β] (f : α ≃o β) {x : α} {y : β} (hx : ∀ x', x ≤ x') (hy : ∀ y', y ≤ y') : f x = y := by { refine le_antisymm _ (hy _), rw [← f.apply_symm_apply y, ← f.map_rel_iff], apply hx } lemma order_iso.map_bot [order_bot α] [order_bot β] (f : α ≃o β) : f ⊥ = ⊥ := f.map_bot' (λ _, bot_le) (λ _, bot_le) lemma order_iso.map_top' [partial_order α] [partial_order β] (f : α ≃o β) {x : α} {y : β} (hx : ∀ x', x' ≤ x) (hy : ∀ y', y' ≤ y) : f x = y := f.dual.map_bot' hx hy lemma order_iso.map_top [order_top α] [order_top β] (f : α ≃o β) : f ⊤ = ⊤ := f.dual.map_bot lemma order_embedding.map_inf_le [semilattice_inf α] [semilattice_inf β] (f : α ↪o β) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := f.monotone.map_inf_le x y lemma order_iso.map_inf [semilattice_inf α] [semilattice_inf β] (f : α ≃o β) (x y : α) : f (x ⊓ y) = f x ⊓ f y := begin refine (f.to_order_embedding.map_inf_le x y).antisymm _, simpa [← f.symm.apply_le_apply] using f.symm.to_order_embedding.map_inf_le (f x) (f y) end lemma order_embedding.le_map_sup [semilattice_sup α] [semilattice_sup β] (f : α ↪o β) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := f.monotone.le_map_sup x y lemma order_iso.map_sup [semilattice_sup α] [semilattice_sup β] (f : α ≃o β) (x y : α) : f (x ⊔ y) = f x ⊔ f y := f.dual.map_inf x y end lattice_isos
d4e3e2889847865235ea893211bbc8871f15b115
4727251e0cd73359b15b664c3170e5d754078599
/src/data/mv_polynomial/rename.lean
d4239c2e5f58b0e989121f5fb556b72519f04ea6
[ "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
10,924
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.basic /-! # Renaming variables of polynomials This file establishes the `rename` operation on multivariate polynomials, which modifies the set of variables. ## Main declarations * `mv_polynomial.rename` * `mv_polynomial.rename_equiv` ## Notation As in other polynomial files, we typically use the notation: + `σ τ α : Type*` (indexing the variables) + `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` elements of the coefficient ring + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ α` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators variables {σ τ α R S : Type*} [comm_semiring R] [comm_semiring S] namespace mv_polynomial section rename /-- Rename all the variables in a multivariable polynomial. -/ def rename (f : σ → τ) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval (X ∘ f) @[simp] lemma rename_C (f : σ → τ) (r : R) : rename f (C r) = C r := eval₂_C _ _ _ @[simp] lemma rename_X (f : σ → τ) (i : σ) : rename f (X i : mv_polynomial σ R) = X (f i) := eval₂_X _ _ _ lemma map_rename (f : R →+* S) (g : σ → τ) (p : mv_polynomial σ R) : map f (rename g p) = rename g (map f p) := mv_polynomial.induction_on p (λ a, by simp only [map_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, alg_hom.map_add, ring_hom.map_add]) (λ p n hp, by simp only [hp, rename_X, map_X, ring_hom.map_mul, alg_hom.map_mul]) @[simp] lemma rename_rename (f : σ → τ) (g : τ → α) (p : mv_polynomial σ R) : rename g (rename f p) = rename (g ∘ f) p := show rename g (eval₂ C (X ∘ f) p) = _, begin simp only [rename, aeval_eq_eval₂_hom], simp [eval₂_comp_left _ C (X ∘ f) p, (∘), eval₂_C, eval_X], apply eval₂_hom_congr _ rfl rfl, ext1, simp only [comp_app, ring_hom.coe_comp, eval₂_hom_C], end @[simp] lemma rename_id (p : mv_polynomial σ R) : rename id p = p := eval₂_eta p lemma rename_monomial (f : σ → τ) (d : σ →₀ ℕ) (r : R) : rename f (monomial d r) = monomial (d.map_domain f) r := begin rw [rename, aeval_monomial, monomial_eq, finsupp.prod_map_domain_index], { refl }, { exact assume n, pow_zero _ }, { exact assume n i₁ i₂, pow_add _ _ _ } end lemma rename_eq (f : σ → τ) (p : mv_polynomial σ R) : rename f p = finsupp.map_domain (finsupp.map_domain f) p := begin simp only [rename, aeval_def, eval₂, finsupp.map_domain, algebra_map_eq, X_pow_eq_monomial, ← monomial_finsupp_sum_index], refl end lemma rename_injective (f : σ → τ) (hf : function.injective f) : function.injective (rename f : mv_polynomial σ R → mv_polynomial τ R) := have (rename f : mv_polynomial σ R → mv_polynomial τ R) = finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f), begin rw this, exact finsupp.map_domain_injective (finsupp.map_domain_injective hf) end section variables {f : σ → τ} (hf : function.injective f) open_locale classical /-- Given a function between sets of variables `f : σ → τ` that is injective with proof `hf`, `kill_compl hf` is the `alg_hom` from `R[τ]` to `R[σ]` that is left inverse to `rename f : R[σ] → R[τ]` and sends the variables in the complement of the range of `f` to `0`. -/ def kill_compl : mv_polynomial τ R →ₐ[R] mv_polynomial σ R := aeval (λ i, if h : i ∈ set.range f then X $ (equiv.of_injective f hf).symm ⟨i,h⟩ else 0) lemma kill_compl_comp_rename : (kill_compl hf).comp (rename f) = alg_hom.id R _ := alg_hom_ext $ λ i, by { dsimp, rw [rename, kill_compl, aeval_X, aeval_X, dif_pos, equiv.of_injective_symm_apply] } @[simp] lemma kill_compl_rename_app (p : mv_polynomial σ R) : kill_compl hf (rename f p) = p := alg_hom.congr_fun (kill_compl_comp_rename hf) p end section variables (R) /-- `mv_polynomial.rename e` is an equivalence when `e` is. -/ @[simps apply] def rename_equiv (f : σ ≃ τ) : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R := { to_fun := rename f, inv_fun := rename f.symm, left_inv := λ p, by rw [rename_rename, f.symm_comp_self, rename_id], right_inv := λ p, by rw [rename_rename, f.self_comp_symm, rename_id], ..rename f} @[simp] lemma rename_equiv_refl : rename_equiv R (equiv.refl σ) = alg_equiv.refl := alg_equiv.ext rename_id @[simp] lemma rename_equiv_symm (f : σ ≃ τ) : (rename_equiv R f).symm = rename_equiv R f.symm := rfl @[simp] lemma rename_equiv_trans (e : σ ≃ τ) (f : τ ≃ α): (rename_equiv R e).trans (rename_equiv R f) = rename_equiv R (e.trans f) := alg_equiv.ext (rename_rename e f) end section variables (f : R →+* S) (k : σ → τ) (g : τ → S) (p : mv_polynomial σ R) lemma eval₂_rename : (rename k p).eval₂ f g = p.eval₂ f (g ∘ k) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_hom_rename : eval₂_hom f g (rename k p) = eval₂_hom f (g ∘ k) p := eval₂_rename _ _ _ _ lemma aeval_rename [algebra R S] : aeval g (rename k p) = aeval (g ∘ k) p := eval₂_hom_rename _ _ _ _ lemma rename_eval₂ (g : τ → mv_polynomial σ R) : rename k (p.eval₂ C (g ∘ k)) = (rename k p).eval₂ C (rename k ∘ g) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma rename_prodmk_eval₂ (j : τ) (g : σ → mv_polynomial σ R) : rename (prod.mk j) (p.eval₂ C g) = p.eval₂ C (λ x, rename (prod.mk j) (g x)) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_rename_prodmk (g : σ × τ → S) (i : σ) (p : mv_polynomial τ R) : (rename (prod.mk i) p).eval₂ f g = eval₂ f (λ j, g (i, j)) p := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval_rename_prodmk (g : σ × τ → R) (i : σ) (p : mv_polynomial τ R) : eval g (rename (prod.mk i) p) = eval (λ j, g (i, j)) p := eval₂_rename_prodmk (ring_hom.id _) _ _ _ end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_finset_rename (p : mv_polynomial σ R) : ∃ (s : finset σ) (q : mv_polynomial {x // x ∈ s} R), p = rename coe q := begin apply induction_on p, { intro r, exact ⟨∅, C r, by rw rename_C⟩ }, { rintro p q ⟨s, p, rfl⟩ ⟨t, q, rfl⟩, refine ⟨s ∪ t, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p + rename (subtype.map id _) q; simp only [id.def, true_or, or_true, finset.mem_union, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, alg_hom.map_add], refl, }, }, { rintro p n ⟨s, p, rfl⟩, refine ⟨insert n s, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p * X ⟨n, s.mem_insert_self n⟩, simp only [id.def, or_true, finset.mem_insert, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, rename_X, subtype.coe_mk, alg_hom.map_mul], refl, }, }, end /-- `exists_finset_rename` for two polyonomials at once: for any two polynomials `p₁`, `p₂` in a polynomial semiring `R[σ]` of possibly infinitely many variables, `exists_finset_rename₂` yields a finite subset `s` of `σ` such that both `p₁` and `p₂` are contained in the polynomial semiring `R[s]` of finitely many variables. -/ lemma exists_finset_rename₂ (p₁ p₂ : mv_polynomial σ R) : ∃ (s : finset σ) (q₁ q₂ : mv_polynomial s R), p₁ = rename coe q₁ ∧ p₂ = rename coe q₂ := begin obtain ⟨s₁,q₁,rfl⟩ := exists_finset_rename p₁, obtain ⟨s₂,q₂,rfl⟩ := exists_finset_rename p₂, classical, use s₁ ∪ s₂, use rename (set.inclusion $ s₁.subset_union_left s₂) q₁, use rename (set.inclusion $ s₁.subset_union_right s₂) q₂, split; simpa, end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_fin_rename (p : mv_polynomial σ R) : ∃ (n : ℕ) (f : fin n → σ) (hf : injective f) (q : mv_polynomial (fin n) R), p = rename f q := begin obtain ⟨s, q, rfl⟩ := exists_finset_rename p, let n := fintype.card {x // x ∈ s}, let e := fintype.equiv_fin {x // x ∈ s}, refine ⟨n, coe ∘ e.symm, subtype.val_injective.comp e.symm.injective, rename e q, _⟩, rw [← rename_rename, rename_rename e], simp only [function.comp, equiv.symm_apply_apply, rename_rename] end end rename lemma eval₂_cast_comp (f : σ → τ) (c : ℤ →+* R) (g : τ → R) (p : mv_polynomial σ ℤ) : eval₂ c (g ∘ f) p = eval₂ c g (rename f p) := mv_polynomial.induction_on p (λ n, by simp only [eval₂_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, rename, eval₂_add, alg_hom.map_add]) (λ p n hp, by simp only [hp, rename, aeval_def, eval₂_X, eval₂_mul]) section coeff @[simp] lemma coeff_rename_map_domain (f : σ → τ) (hf : injective f) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) : (rename f φ).coeff (d.map_domain f) = φ.coeff d := begin apply induction_on' φ, { intros u r, rw [rename_monomial, coeff_monomial, coeff_monomial], simp only [(finsupp.map_domain_injective hf).eq_iff] }, { intros, simp only [*, alg_hom.map_add, coeff_add], } end lemma coeff_rename_eq_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ) (h : ∀ u : σ →₀ ℕ, u.map_domain f = d → φ.coeff u = 0) : (rename f φ).coeff d = 0 := begin rw [rename_eq, ← not_mem_support_iff], intro H, replace H := map_domain_support H, rw [finset.mem_image] at H, obtain ⟨u, hu, rfl⟩ := H, specialize h u rfl, simp at h hu, contradiction end lemma coeff_rename_ne_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ) (h : (rename f φ).coeff d ≠ 0) : ∃ u : σ →₀ ℕ, u.map_domain f = d ∧ φ.coeff u ≠ 0 := by { contrapose! h, apply coeff_rename_eq_zero _ _ _ h } @[simp] lemma constant_coeff_rename {τ : Type*} (f : σ → τ) (φ : mv_polynomial σ R) : constant_coeff (rename f φ) = constant_coeff φ := begin apply φ.induction_on, { intro a, simp only [constant_coeff_C, rename_C]}, { intros p q hp hq, simp only [hp, hq, ring_hom.map_add, alg_hom.map_add] }, { intros p n hp, simp only [hp, rename_X, constant_coeff_X, ring_hom.map_mul, alg_hom.map_mul] } end end coeff section support lemma support_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) : (rename f p).support = finset.image (map_domain f) p.support := begin rw rename_eq, exact finsupp.map_domain_support_of_injective (map_domain_injective h) _, end end support end mv_polynomial
60c137ebe6165a4bccd475429950dc05c79b3905
2c819623a83d8c53b7282622429e344389ce4030
/proofs/lib.lean
e15a25fe4727e9d241bd7a783463b3b7379b5fe0
[]
no_license
uw-unsat/jitsynth
6bc97dd1ede9da42c0b9313a4766095345493adc
69529e18d4a8d4dace884bfde91aa26b549523fa
refs/heads/master
1,653,802,737,129
1,588,361,732,000
1,588,361,732,000
260,513,113
14
0
null
null
null
null
UTF-8
Lean
false
false
7,476
lean
import tactic import tactic.find import tactic.core -- Includes structural definitions and assumptions namespace jitsynth inductive aparam : Type | reg : aparam | bv : ℕ → aparam inductive cparam : Type | reg : ℕ → cparam | bv : ℕ → ℕ → cparam structure ainstr : Type := mk :: (op : ℕ) (F : list aparam) structure cinstr : Type := mk :: (op : ℕ) (F : list cparam) def cparam_in_aparam : aparam → cparam → Prop | aparam.reg (cparam.reg n) := true | aparam.reg (cparam.bv b c) := false | (aparam.bv a) (cparam.reg n) := false | (aparam.bv a) (cparam.bv b c) := a = b def cinstr_in_ainstr : ainstr → cinstr → Prop | (ainstr.mk n []) (cinstr.mk m []) := n = m | (ainstr.mk n []) (cinstr.mk m l) := n = m ∧ l = [] | (ainstr.mk n l) (cinstr.mk m []) := n = m ∧ l = [] | (ainstr.mk n (ha::ta)) (cinstr.mk m (hc::tc)) := (cparam_in_aparam ha hc) ∧ (cinstr_in_ainstr (ainstr.mk n ta) (cinstr.mk m tc)) def cprog_in_aprog : list ainstr → list cinstr → Prop | [] [] := true | [] l := l = [] | l [] := l = [] | (ha::ta) (hc::tc) := (cinstr_in_ainstr ha hc) ∧ (cprog_in_aprog ta tc) def empty_cinstr : cinstr := (cinstr.mk 0 []) def P : ainstr → list ℕ → option cinstr | (ainstr.mk op list.nil) list.nil := option.some (cinstr.mk op list.nil) | (ainstr.mk op list.nil) (list.cons h t) := option.none | (ainstr.mk op (list.cons h t)) list.nil := option.none | (ainstr.mk op (list.cons aparam.reg l)) (list.cons h t) := let pres := P (ainstr.mk op l) t in match pres with | option.none := option.none | option.some p := option.some (cinstr.mk op (list.cons (cparam.reg h) (p.F))) end | (ainstr.mk op (list.cons (aparam.bv n) l)) (list.cons h t) := let pres := P (ainstr.mk op l) t in match pres with | option.none := option.none | option.some p := option.some (cinstr.mk op (list.cons (cparam.bv n h) (p.F))) end structure state : Type := mk :: (regs : list ℕ) (mem : list ℕ) (pc : ℕ) structure arm : Type := mk :: (T : cinstr → state → state) (Φ : list cinstr → ℕ) -- ASSUMPTION: A congruence function exists, constant reg_cong : list ℕ → list ℕ → Prop constant mem_cong : list ℕ → list ℕ → Prop inductive imp_param : Type | sparam_sreg : ℕ → imp_param | sparam_smem : ℕ → imp_param | sparam_imm : ℕ → imp_param | treg : ℕ → imp_param | imm : ℕ → ℕ → imp_param -- Exclusively produces an imm | exp : (ℕ→ℕ) → imp_param → imp_param structure imp_instr : Type := mk :: (op : ℕ) (F : list imp_param) -- Takes a reg index mapping, a mem index mapping, -- a concrete source instruction parameter list, -- a target implementation instruction parameter list, -- and outputs a concrete target parameter list def concretize_param : (ℕ→ℕ) → (ℕ→ℕ) → list cparam → imp_param → option cparam | reg_map mem_map [] ip := none | reg_map mem_map clist (imp_param.sparam_sreg n) := match (list.nth clist n) with | option.none := none | option.some (cparam.bv a b) := none | option.some (cparam.reg r) := some (cparam.reg (reg_map r)) end | reg_map mem_map clist (imp_param.sparam_smem n) := match (list.nth clist n) with | option.none := none | option.some (cparam.bv a b) := some (cparam.bv a (mem_map b)) | option.some (cparam.reg r) := none end | reg_map mem_map clist (imp_param.sparam_imm n) := match (list.nth clist n) with | option.none := none | option.some (cparam.bv a b) := some (cparam.bv a b) | option.some (cparam.reg r) := none end | reg_map mem_map clist (imp_param.treg n) := some (cparam.reg n) | reg_map mem_map clist (imp_param.imm l n) := (cparam.bv l n) | reg_map mem_map clist (imp_param.exp m ip) := match (concretize_param reg_map mem_map clist ip) with | none := none | some (cparam.reg r) := none | some (cparam.bv n v) := some (cparam.bv n (m v)) end def concretize_params : (ℕ→ℕ) → (ℕ→ℕ) → list cparam → list imp_param → list (option cparam) | rm mm clist [] := [] | rm mm clist (hi::ti) := (concretize_param rm mm clist hi) :: (concretize_params rm mm clist ti) def remove_option_helper {α : Type} : list (option α) → list α → option (list α) | [] acc := some acc | (h::t) acc := match h with | none := none | some x := remove_option_helper t (x::acc) end def remove_option {α : Type} : list (option α) → option (list α) | l := remove_option_helper l [] def concretize_instr : (ℕ→ℕ) → (ℕ→ℕ) → cinstr → imp_instr → option cinstr | reg_map mem_map (cinstr.mk cop cl) (imp_instr.mk iop il) := match (remove_option (concretize_params reg_map mem_map cl il)) with | none := none | some params := some (cinstr.mk iop params) end -- TODO should I use option? def concretize_prog : (ℕ→ℕ) → (ℕ→ℕ) → cinstr → list imp_instr → list (option cinstr) | reg_map mem_map ci [] := [] | reg_map mem_map ci (ii::il) := (concretize_instr reg_map mem_map ci ii) :: (concretize_prog reg_map mem_map ci il) -- ASSUMPTION: PC congruence is defined by pc_mult constant pc_mult : ℕ -- source PC -> target PC -> bool def pc_cong (spc : ℕ) (tpc : ℕ) : Prop := pc_mult * spc = tpc -- PC map is implicitly pc_mult * source PC -- ASSUMPTION: no backwards jumps constant no_back_jumps : ∀ m : arm, ∀ i : cinstr, ∀ σ : state, σ.pc < (m.T i σ).pc def cong (σ₁ : state) (σ₂ : state) : Prop := (reg_cong σ₁.regs σ₂.regs) ∧ (mem_cong σ₁.mem σ₂.mem) ∧ (pc_cong σ₁.pc σ₂.pc) def run : list cinstr → state → (cinstr → state → state) → ℕ → state | p σ T nat.zero := σ | p σ T (nat.succ n) := match (list.nth p σ.pc) with | option.none := σ | option.some pi := run p (T pi σ) T n end -- def implementation : (sai : ainstr) def correct_impl (reg_map mem_map : ℕ→ℕ) (s t : arm) (sai : ainstr) (tap : list imp_instr) : Prop := ∀ tp : list cinstr, ∀ sci : cinstr, ∀ tcp : list cinstr, ∀ σs σt : state, ∀ f : ℕ, (∃ conc_params : list ℕ, P sai conc_params = some sci) → remove_option (concretize_prog reg_map mem_map sci tap) = some tcp → cong σs σt → tp.length = σt.pc → pc_mult ≤ f → cong (s.T sci σs) (run (tp ++ tcp) σt t.T f) def 𝔸 (mach : arm) (prog : list cinstr) (σ : state) : state := run prog σ mach.T (mach.Φ prog) def sound_minic (s t : arm) (C : cinstr → list cinstr) : Prop := ∀ tp : list cinstr, ∀ si : cinstr, ∀ σs σt : state, ∀ f : ℕ, (cong σs σt) → tp.length = σt.pc → pc_mult ≤ f → (cong (s.T si σs) (run (tp ++ (C si)) σt (t.T) f)) def sound_minic_instr (s t : arm) (C : cinstr → list cinstr) (si : cinstr): Prop := ∀ tp : list cinstr, ∀ σs σt : state, ∀ f : ℕ, (cong σs σt) → tp.length = σt.pc → pc_mult ≤ f → (cong (s.T si σs) (run (tp ++ (C si)) σt (t.T) f)) def compile : (cinstr → list cinstr) → list cinstr → list cinstr | C list.nil := list.nil | C (list.cons si t) := (C si) ++ (compile C t) end jitsynth
4185cd996b547eab8788687f002ffff7f9af94af
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/lie/matrix.lean
b7572a379a5fd6856f3668cfbb2ac11e4128e662
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
3,476
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import linear_algebra.matrix.reindex import linear_algebra.matrix.to_linear_equiv /-! # Lie algebras of matrices An important class of Lie algebras are those arising from the associative algebra structure on square matrices over a commutative ring. This file provides some very basic definitions whose primary value stems from their utility when constructing the classical Lie algebras using matrices. ## Main definitions * `lie_equiv_matrix'` * `matrix.lie_conj` * `matrix.reindex_lie_equiv` ## Tags lie algebra, matrix -/ universes u v w w₁ w₂ section matrices open_locale matrix variables {R : Type u} [comm_ring R] variables {n : Type w} [decidable_eq n] [fintype n] /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the Lie algebra structures. -/ def lie_equiv_matrix' : module.End R (n → R) ≃ₗ⁅R⁆ matrix n n R := { map_lie' := λ T S, begin let f := @linear_map.to_matrix' R _ n n _ _ _, change f (T.comp S - S.comp T) = (f T) * (f S) - (f S) * (f T), have h : ∀ (T S : module.End R _), f (T.comp S) = (f T) ⬝ (f S) := linear_map.to_matrix'_comp, rw [linear_equiv.map_sub, h, h, matrix.mul_eq_mul, matrix.mul_eq_mul], end, ..linear_map.to_matrix' } @[simp] lemma lie_equiv_matrix'_apply (f : module.End R (n → R)) : lie_equiv_matrix' f = f.to_matrix' := rfl @[simp] lemma lie_equiv_matrix'_symm_apply (A : matrix n n R) : (@lie_equiv_matrix' R _ n _ _).symm A = A.to_lin' := rfl /-- An invertible matrix induces a Lie algebra equivalence from the space of matrices to itself. -/ noncomputable def matrix.lie_conj (P : matrix n n R) (h : is_unit P) : matrix n n R ≃ₗ⁅R⁆ matrix n n R := ((@lie_equiv_matrix' R _ n _ _).symm.trans (P.to_linear_equiv' h).lie_conj).trans lie_equiv_matrix' @[simp] lemma matrix.lie_conj_apply (P A : matrix n n R) (h : is_unit P) : P.lie_conj h A = P ⬝ A ⬝ P⁻¹ := by simp [linear_equiv.conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp, linear_map.to_matrix'_to_lin'] @[simp] lemma matrix.lie_conj_symm_apply (P A : matrix n n R) (h : is_unit P) : (P.lie_conj h).symm A = P⁻¹ ⬝ A ⬝ P := by simp [linear_equiv.symm_conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp, linear_map.to_matrix'_to_lin'] /-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent types, `matrix.reindex`, is an equivalence of Lie algebras. -/ def matrix.reindex_lie_equiv {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) : matrix n n R ≃ₗ⁅R⁆ matrix m m R := { to_fun := matrix.reindex e e, map_lie' := λ M N, by simp only [lie_ring.of_associative_ring_bracket, matrix.reindex_apply, ←matrix.minor_mul_equiv _ _ _ _, matrix.mul_eq_mul, matrix.minor_sub, pi.sub_apply], ..(matrix.reindex_linear_equiv R R e e) } @[simp] lemma matrix.reindex_lie_equiv_apply {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) (M : matrix n n R) : matrix.reindex_lie_equiv e M = matrix.reindex e e M := rfl @[simp] lemma matrix.reindex_lie_equiv_symm {m : Type w₁} [decidable_eq m] [fintype m] (e : n ≃ m) : (matrix.reindex_lie_equiv e : _ ≃ₗ⁅R⁆ _).symm = matrix.reindex_lie_equiv e.symm := rfl end matrices
dc0c273ffb488156a64c863bc4644f097a76b686
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/seminorm_auto.lean
ebe10c4fa94ca2ce47008f5aceee6041af50c479
[]
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
7,850
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.pointwise import Mathlib.analysis.normed_space.basic import Mathlib.PostPort universes u_1 u_2 l namespace Mathlib /-! # Seminorms and Local Convexity This file introduces the following notions, defined for a vector space over a normed field: - the subset properties of being `absorbent` and `balanced`, - a `seminorm`, a function to the reals that is positive-semidefinite, absolutely homogeneous, and subadditive. We prove related properties. ## TODO Define and show equivalence of two notions of local convexity for a topological vector space over ℝ or ℂ: that it has a local base of balanced convex absorbent sets, and that it carries the initial topology induced by a family of seminorms. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] -/ /-! ### Subset Properties Absorbent and balanced sets in a vector space over a nondiscrete normed field. -/ /-- A set `A` absorbs another set `B` if `B` is contained in scaling `A` by elements of sufficiently large norms. -/ def absorbs (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (A : set E) (B : set E) := ∃ (r : ℝ), ∃ (H : r > 0), ∀ (a : 𝕜), r ≤ norm a → B ⊆ a • A /-- A set is absorbent if it absorbs every singleton. -/ def absorbent (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (A : set E) := ∀ (x : E), ∃ (r : ℝ), ∃ (H : r > 0), ∀ (a : 𝕜), r ≤ norm a → x ∈ a • A /-- A set `A` is balanced if `a • A` is contained in `A` whenever `a` has norm no greater than one. -/ def balanced (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (A : set E) := ∀ (a : 𝕜), norm a ≤ 1 → a • A ⊆ A /-- A balanced set absorbs itself. -/ theorem balanced.absorbs_self {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] {A : set E} (hA : balanced 𝕜 A) : absorbs 𝕜 A A := sorry /-! Properties of balanced and absorbing sets in a topological vector space: -/ /-- Every neighbourhood of the origin is absorbent. -/ theorem absorbent_nhds_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] {A : set E} [topological_space E] [topological_vector_space 𝕜 E] (hA : A ∈ nhds 0) : absorbent 𝕜 A := sorry /-- The union of `{0}` with the interior of a balanced set is balanced. -/ theorem balanced_zero_union_interior {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] {A : set E} [topological_space E] [topological_vector_space 𝕜 E] (hA : balanced 𝕜 A) : balanced 𝕜 (singleton 0 ∪ interior A) := sorry /-- The interior of a balanced set is balanced if it contains the origin. -/ theorem balanced.interior {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] {A : set E} [topological_space E] [topological_vector_space 𝕜 E] (hA : balanced 𝕜 A) (h : 0 ∈ interior A) : balanced 𝕜 (interior A) := sorry /-- The closure of a balanced set is balanced. -/ theorem balanced.closure {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] {A : set E} [topological_space E] [topological_vector_space 𝕜 E] (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) := sorry /-! ### Seminorms -/ /-- A seminorm on a vector space over a normed field is a function to the reals that is positive semidefinite, positive homogeneous, and subadditive. -/ structure seminorm (𝕜 : Type u_1) (E : Type u_2) [normed_field 𝕜] [add_comm_group E] [vector_space 𝕜 E] where to_fun : E → ℝ smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = norm a * to_fun x triangle' : ∀ (x y : E), to_fun (x + y) ≤ to_fun x + to_fun y protected instance seminorm.inhabited {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] : Inhabited (seminorm 𝕜 E) := { default := seminorm.mk (fun (_x : E) => 0) sorry sorry } protected instance seminorm.has_coe_to_fun {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] : has_coe_to_fun (seminorm 𝕜 E) := has_coe_to_fun.mk (fun (p : seminorm 𝕜 E) => E → ℝ) fun (p : seminorm 𝕜 E) => seminorm.to_fun p namespace seminorm protected theorem smul {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (c : 𝕜) (x : E) : coe_fn p (c • x) = norm c * coe_fn p x := smul' p c x protected theorem triangle {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) (y : E) : coe_fn p (x + y) ≤ coe_fn p x + coe_fn p y := triangle' p x y @[simp] protected theorem zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) : coe_fn p 0 = 0 := sorry @[simp] protected theorem neg {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) : coe_fn p (-x) = coe_fn p x := sorry theorem nonneg {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) : 0 ≤ coe_fn p x := sorry theorem sub_rev {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) (y : E) : coe_fn p (x - y) = coe_fn p (y - x) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn p (x - y) = coe_fn p (y - x))) (Eq.symm (neg_sub y x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn p (-(y - x)) = coe_fn p (y - x))) (seminorm.neg p (y - x)))) (Eq.refl (coe_fn p (y - x)))) /-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with `p (y - x) < `r`. -/ def ball {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) (r : ℝ) : set E := set_of fun (y : E) => coe_fn p (y - x) < r theorem mem_ball {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (x : E) (y : E) (r : ℝ) : y ∈ ball p x r ↔ coe_fn p (y - x) < r := iff.rfl theorem mem_ball_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (y : E) (r : ℝ) : y ∈ ball p 0 r ↔ coe_fn p y < r := eq.mpr (id (Eq._oldrec (Eq.refl (y ∈ ball p 0 r ↔ coe_fn p y < r)) (propext (mem_ball p 0 y r)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn p (y - 0) < r ↔ coe_fn p y < r)) (sub_zero y))) (iff.refl (coe_fn p y < r))) theorem ball_zero_eq {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (r : ℝ) : ball p 0 r = set_of fun (y : E) => coe_fn p y < r := sorry /-- Seminorm-balls at the origin are balanced. -/ theorem balanced_ball_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [add_comm_group E] [vector_space 𝕜 E] (p : seminorm 𝕜 E) (r : ℝ) : balanced 𝕜 (ball p 0 r) := sorry end Mathlib
86992565fa5698a427ea804c65440fdbee455c36
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/yoneda/limits.lean
ebbec2599df58f7a912835f60f3f1011a6458b5f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,902
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.preadditive.yoneda.basic import algebra.category.Module.abelian /-! # The Yoneda embedding for preadditive categories preserves limits > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The Yoneda embedding for preadditive categories preserves limits. ## Implementation notes This is in a separate file to avoid having to import the development of the abelian structure on `Module` in the main file about the preadditive Yoneda embedding. -/ universes v u open category_theory.preadditive opposite category_theory.limits noncomputable theory namespace category_theory variables {C : Type u} [category.{v} C] [preadditive C] instance preserves_limits_preadditive_yoneda_obj (X : C) : preserves_limits (preadditive_yoneda_obj X) := have preserves_limits (preadditive_yoneda_obj X ⋙ forget _), from (infer_instance : preserves_limits (yoneda.obj X)), by exactI preserves_limits_of_reflects_of_preserves _ (forget _) instance preserves_limits_preadditive_coyoneda_obj (X : Cᵒᵖ) : preserves_limits (preadditive_coyoneda_obj X) := have preserves_limits (preadditive_coyoneda_obj X ⋙ forget _), from (infer_instance : preserves_limits (coyoneda.obj X)), by exactI preserves_limits_of_reflects_of_preserves _ (forget _) instance preserves_limits_preadditive_yoneda.obj (X : C) : preserves_limits (preadditive_yoneda.obj X) := show preserves_limits (preadditive_yoneda_obj X ⋙ forget₂ _ _), from infer_instance instance preserves_limits_preadditive_coyoneda.obj (X : Cᵒᵖ) : preserves_limits (preadditive_coyoneda.obj X) := show preserves_limits (preadditive_coyoneda_obj X ⋙ forget₂ _ _), from infer_instance end category_theory
ab6f4573785ed5a7f1e4970fca2c9c41cccbd256
a6b711a4e8db20755026231f7ed529a9014b2b6d
/03_Conjunction/00_and.lean
1c9b5faf8ff247f8c519f24192dc74dd8006ff91
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,587
lean
/- Intuitively, if a proposition P is true and a second proposition Q is true, then the more complex proposition, "P and Q" is also true. This proposition is written symbolically as P ∧ Q. In mathematical logic, we say that the proposition, P ∧ Q, is the conjunction of the individual propositions, P and Q. There's an inference rule for that. It says that if P and Q are propositions (types of type Prop), and if you have a proof of P and you have a proof of Q then you can derive a proof of P ∧ Q. Moreover, the form of that proof is basically the pair of proofs, (p, q). {P Q : Prop }, p : P, q : Q --------------------------- (∧-intro) (p, q): P ∧ Q To give us some propositions and proofs to use in examples, let's define P and Q to be simple equality propositions, and let's then define p and q to be proofs of P and Q. -/ def P : Prop := 0 = 0 def Q := 1 = 1 -- type inference works here theorem pfP : P := eq.refl 0 theorem pfQ : Q := eq.refl 1 /- We note that rfl doesn't work here. It's the right idea, but the proposition, P, to be proved isn't written as an equality, so rfl doesn't know what to do with it. We just just eq.refl directly instead. -/ /- * SYNTAX OF CONJUNCTIONS * -/ /--/ Now the syntax of proposition logic allows us to form a new proposition, P ∧ Q. -/ def P_and_Q : Prop := P ∧ Q #check P_and_Q -- it's a proposition #check P ∧ Q -- same thing /- * SEMANTICS OF CONJUNCTIONS * -/ /- * AND INTRODUCTION RULE * -/ /- Now intuitively, P ∧ Q should be true if and only if P is true and Q is true, which in the logic of Lean is to say if we have a proof of P and a proof of Q. The and.intro inference rule formalizes this idea. It says if you give me propositions, P and Q, and proofs, p and q of P and Q respectively, then I will give you back a proof of P ∧ Q. { P, Q : Prop } (p: P) (q: Q) ----------------------------- and.intro pf_PQ : P ∧ Q The and.intro takes two explicit arguments: a proof of P and a proof of Q. It infers P and Q from pf_P and pf_Q. It then derives a proof of P ∧ Q. Here is an example of its use in Lean -/ theorem pf_PQ: P ∧ Q := and.intro pfP pfQ -- study this carefully! /- Ok, let's decode that. We're proposing a theorem. The proposition we aim to prove is P ∧ Q, which is really just 0 = 0 ∧ 1 = 1. To produce a proof of this proposition, we need a proof of 0 = 0. That is p. We also need a proof of 1 = 1. That is q. If we then apply the rule to p and q we can expect to get back a proof of P ∧ Q,=. The Lean checker confirms that we do. You might be getting the sense that these inference rules are sort of like functions: They take propositions, proofs, and other values as arguments and they compute and return proofs as results. This is exactly what is happening here. What you're seeing is how programs like Lean turns propositions and proofs into objects that can be handled and transformed by programs! It's like your ordinary discrete math class on steroids. -/ /- * PROOF TREES * -/ /- A key point is that what we just did is to build a larger proof, pf, from two smaller ones, p and q. Those proofs in turn we built using the eq.refl inference rule applied to the values 0 and 1, respectively. We can now visualize the whole construction as what we call a proof tree, or derivation (with more than one level of rules being applied). eq.refl 0 eq.refl 1 --------- --------- 0 = 0 1 = 1 ---------------------- 0 = 0 ∧ 1 = 1 We can read such a proof tree either from the top to the bottom or from the bottom to the top. We can also translate such a tree into English. Most mathematicians would just provide the English language proof, leaving it to human and social processes to check that it's good. We now have the benefit of automated proof checking. Reading it from the top we might say the following. By the reflexive property of equality, we derive that 0 = 0 and that 1 = 1. These lemmas both now been proved separately, a proof of their conjunction follows immediately. QED Now as one seeking to prove P ∧ Q (the conclusion), one would work from bottom to top. The reasoning would go like this: To prove the conclusion, we need proofs of ach conjunct. We obtain a proof of the first, 0 = 0, by noting that this follows from the reflexive property of equality. So does a proof of 1 = 1. Now having proved the individual conjuncts, the truth of the conjunction follows immediately. QED. You can see that the everyday working mathematician elides many details, such as the precise principle used to derive the truth of the conjunction. The lack of detail in informal proofs makes them at best nearly impossible for machines to check. Reading and checking them really relies on human mathematical understanding. Nevertheless, whether you are asked to write an informal proof or a formal one, the process of deriving a proof often involves this kind of "backwards chaining." When asked to prove a proposition, X, we generally try to find other propositions, such as S and T, such that if we had proofs of S and T, we could then apply a valid reasoning step (inference rule) to derive a proof of X. One thus reduces the problem of proving X to the sub-problems of proving S and T. One then backward-chains this way until one finally reaches ... axioms, i.e., rules with no proofs required above the line. Axioms are the "base cases" in the recursive decomposition of the overall problem: there is no need to recurse any further once you've reach the bottom! To be really precise about it, there is one more layer in the proof tree: it's where the Lean type checker gives us proofs that 0 and 1 are of type nat; and that's what eq.refl needs as its input. The type checker in turn gives us proofs of these type judgments by means of yet further, but not hidden, logic reasoning. 0: nat 1 : nat --------- --------- eq.refl 0 eq.refl 1 --------- --------- 0 = 0 1 = 1 ---------------------- 0 = 0 ∧ 1 = 1 QED! Now you're looking at a depiction of a mathematically precise proof. The English just presents such an object in a more natural language, but at the cost of a massive loss of precision and checkability. The downside of the formal proof object is that it's not in the form of a story; and as you can imagine, in cases where proofs get massive, understanding why they are the way they are can be near impossible. But that's why we have machines. In practice, you should really know how to produce both formal and informal proofs. Better yet, you might someday try some tools that produce formal proofs for you. (Such a tool is Dafny. We will perhaps see it later.) -/ /- EXERCISE: What "smaller" propositions might you want to prove to prove that 5 = 1 + 4 ∧ "Strike" = "S" ++ "trike". Prove those smaller propositions giving them whatever names you choose. Then write the theorem in Lean that proves the final result using and.intro. -/ /- * Proving conjunctions with tactics * -/ /- One can always prove a proposition by giving an exact proof term, but these terms are like programs, and they can get large and complicated. Sometimes, indeed often, it's easier to develop them step by step. A key idea is that we start with the goal at the bottom of a proof tree, the goal (proposition) to be proved, and by working backwards through the tree, we can identify the smaller propositions for which we need proofs so as to be able to apply a final rule to construct the desired proof. Consider again the goal of proving the conjunctive proposition P ∧ Q. If we have a proof of P and a proof of Q then we can apply the and.intro rule to build the proof we need. Well, that breaks the overall goal into two subgoals, and we can then solve them recursively (i.e., as sub-problems to solve nested within the solution to the overall problem). In particular, we can *split* the goal of proving a conjunction into sub-goals, one for each conjunct. We then solve the sub-problems and finally combine the partial solutions into a final result using and.intro. Whether you are using a tool like Lean or are just writing informal mathematical proofs, the use of decomposition of a large problem into pieces, recursively solving of the parts, and ultimately the combination of the partial results into a final result, is essential and ubiquitous. Indeed, it's a general way to solve complex problems in almost any domain. The key is being able to break a problem into parts that can be solved independently. -/ /- In Lean, we can build proofs this way using tactic scripts. First we apply the and.intro rule. Used in a script in this way, it works backwards! Rather than combining proofs for P and Q into a proof of P ∧ Q, it decomposes the top-level goal of proving P ∧ Q into two sub-goals: to prove P and to prove Q. The problem of proving P ∧ Q is thus decomposed into the problem of proving premises needed to make the and.intro rule succeed. We then use additional tactics too solve each of the sub-problems, one by one. Open the Messages view, then put your cursor at the beginning of each line in the following script and study how the tactic state changes as you go. -/ theorem pf_PQ': P ∧ Q := begin apply and.intro, exact (eq.refl 0), exact (eq.refl 1), end /- An English-language rendition of this proof-constructing procedure would go like this: "We split the problem of proving P ∧ Q into the sub-problems, of proving P and proving Q. This is a valid step because the and.intro rule tells us that having such proofs will suffice to prove the main goal. A proof of P follows from the reflexive property of equality, and a proof of Q also then follows similarly. QED." Constructing proofs in this way is very much like writing programs by first writing the Main routine, having it call subroutines, and then writing the subroutines. Here instead we start with the main goal, P ∧ Q. We apply an inference rule to break down the problem of proving the goal into one or more problems of proving sub-goals, and once we're done with that, a proof of the top-level goals follows by the application of the mai inference rule. We call this approach to development of programs, and of proofs, top-down decomposition. Sometimes a software will say that she's using "top-down structured programming" to design her code. Learning to think this way is a major step forward for a computer scientist. -/ /- There's another way, of course, to build a proof, or a program, and that iss to write the sub-routines first and then to integrate them into a larger program by writing code that uses them. We call such an approach "bottom-up." You can similarly develop proofs using a bottom-up approach. You first obtain the proofs of sub-goals that you'll need and then you "integrate" (combine) them by applying some inference rule. We now introduce a style of Lean proof scripts that supports such a bottom-up approach to constructing proofs. Here's an example where we prove the same proposition but in a bottom-up manner. -/ theorem pf_PQ'': P ∧ Q := begin have X := (eq.refl 0), have Y := (eq.refl 1), apply and.intro X Y end /- Study very carefully how the tactic state changes as you advance through the script. The first tactic we use is "have." It gives a name to a proof for a sub-goal that you will then use later on. Here, the name X is given to a proof of 0 = 0. Once this tactic has run, you will see the proof state update to a new state in which you have a proof X of 0 = 0 (before the ⊢), with P ∧ Q as desired proposition to be proved. Next we give a name to, and then subsequently also have a proof of Q. And finally, we apply the and.intro rule to these two proofs, which are now available in the "context" of the proof state (before the ⊢) to build a proof of the overall goal. Lean checks and accepts that proof thereby solving the overall problem. QED, as they say. This style of proof scripts starts to look like proofs that a mathematician might write. This one could be read like this: "We have a proof of P, (eq.refl 0). Let's call it X. We also have a proof of Q, (eq.refl 1). Let's call it Y. Given proofs X and Y we now apply the and.intro rule to X and Y to derive the proof we need. QED." -/ /- Whether you write exact proof objects, or use top-down or bottom-up scripting methods, the key point to bear in mind is that everything ultimately relies on the inference rules. They are what is most fundamental. Moving from the conclusion to the premises of and.intro is how we decompose the top-level goal, P ∧ Q, into sub-goals. Moving from the premises X and Y down through the and.intro rule to a proof of P ∧ Q is how we merge bottom-up partial results into an overall solution. And of course if we're going to write a proof object exactly, the expression we need is one in which eq.refl is used. It's thus very important that you familiarize yourself deeply with the introduction (and also the elimination) inference rules for predicate logic. Now we move on to the elimination rules for and (∧). -/ /- * AND ELIMINATION * -/ /- Given a proof of P ∧ Q, it's clear that P should be true individually, and Q too. The and elimination rules provide us with these reasoning principles, allowing us to derive P from P ∧ Q, and Q from P ∧ Q. We call them and.elim_left and and.elim_right. { P Q: Prop } (paq : P ∧ Q) --------------------------- and.elim_left pfP : P { P Q: Prop } (paq : P ∧ Q) --------------------------- and.elim_right pfQ : Q -/ -- recall that t is a proof of P ∧ Q #check and.elim_left pf_PQ #check and.elim_right pf_PQ /- EXERCISE: Fill in the "sorry" words in the following incomplete theorems with explicit proof objects obtained by applying the and elimination rules to our proof, pf_PQ, of P ∧ Q. Note: Sorry says, "please just accept the theorem as proved: an axiom. It's dangerous to use sorry except as a temporary placeholder for a proof that you plan fill in later." -/ theorem pfP' : P := and.elim_left pf_PQ theorem pfQ' : Q := sorry /- Here are two script-based proofs. -/ theorem pfP'' : P := begin exact and.elim_left pf_PQ end theorem pfP''' : P := begin have pfP := and.elim_left pf_PQ, exact pfP end /- * COMMUTATIVITY OF CONJUNCTION *-/ /- Now we've really got some power tools. We can prove equalities. From constituent proofs we can prove conjunctions, and from proofs of conjunctions we can obtain proofs of the individual conjuncts. With these tools in hand we can now start to state and prove essential mathematical properties of logical operators, here of conjunction (and, ∧) . Let's first state a claim informally. If P ∧ Q is true then Q ∧ P must be true as well. We won't prove the general case here, but we will show that from a proof of (0 = 0 ∧ 1 = 1) we can derive a proof of (1 = 1 ∧ 0 = 0). We already have the propositions, P := 0 = 0, Q := 1 = 1, and a proof, t, of P ∧ Q (i.e., of 0 = 0 ∧ 1 =1 ). Now let's give a name to the proposition that (1 = 1 ∧ 0 = 0). -/ def Q_and_P : Prop := Q ∧ P -- reverse! /- How can we generate a proof of Q_and_P? Let's think in a top-down manner. Start with the goal, Q ∧ P, and ask how it can be proved. The only way we can prove it at present is by applying and.intro to a proof of Q and a proof of P (in this new and reversed order!). So the form of a proof simply has to be (and.intro _ _), where the first _ is a proof of Q and the second _ is a proof of P. If all we start with is a proof, t, of P ∧ Q, how can get the proofs, pfP of P and pfQ of Q, that we need? Easy! Apply the and.elimination rules to t to get first a proof of Q then a proof of P, and then use those proofs as arguments to and.intro. -/ theorem pfQaP : Q ∧ P := and.intro (and.elim_right pf_PQ) (and.elim_left pf_PQ) /- EXERCISE: Write a top-down proof script to prove the same proposition, calling the result pfQaP'. EXERCISE: Write a bottom-up proof script to prove the same proposition, calling the result pfQaP''. -/ theorem pfQaP' : Q ∧ P := begin split, exact (and.elim_right pf_PQ), exact (and.elim_left pf_PQ), end theorem pfQaP'' : Q ∧ P := begin have pfQ := (and.elim_right pf_PQ), have pfP := (and.elim_left pf_PQ), apply and.intro pfQ pfP end /- The general inference rule, which we will call and.comm, short for "and commutes", says that if P and Q are *any* propositions, and we have a proof, paq, of P ∧ Q, then we can obtain a proof, qap, of Q ∧ P. We could write the rule like this (with the arguments P and Q again being implicit, insofar as they can be inferred from paq). { P Q: Prop }, paq : P ∧ Q -------------------------- and_commutes qap: Q ∧ P We can now even see how we might implement this rule ourselves -- literally as a program! We'll call it "and_commutes". -/ def and_commutes { P Q: Prop } (paq: P ∧ Q) := and.intro (and.elim_right paq) (and.elim_left paq) /- In this program we use the same curly brace notation as introduced informally above to indicate parameters that are to be inferred from context. That is, we can apply this function to a proof of P ∧ Q, without explicitly giving P and Q as parameters, to obtain a proof of Q ∧ P. Does it work? -/ theorem qap : Q ∧ P := and_commutes pf_PQ /- Holy cow, it does! We applied our new *proof converter* to convert a proof of 0 = 0 ∧ 1 = 1 into a proof of 1 = 1 ∧ 0 = 0. We might guess that this will work no matter what P and Q are, and indeed that is the case, because we wrote our program to be general with respect to what the propositions P and Q are. We have thus in effect proven that conjunction is commutative: that for any propositions, P and Q, if P ∧ Q is true, then so must be Q ∧ P. Now things are getting interesting. -/ /- EXERCISE: From a proof of 1 = 1 ∧ tt = tt, use and_commutes to prove tt = tt ∧ 1 = 1. -/ /- Having now proved that "and commutes," as mathematicians would say, we can now use this principle in all future reasoning. Indeed in the work of everyday mathematics, if one had proved P ∧ Q and needed a proof of Q ∧ P, it'd be a simple matter of saying "Q ∧ P follows from the commutativity of conjunction." Many mathematicians would just say, "Q ∧ P follows immediately," leaving it to the reader to know that the commutativity property of ∧ is the real justification for the conclusion. -/
682ffb1078e6c2e88861d72aae003f33ed1fb1bb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/bitraversable/lemmas_auto.lean
be083b2dc2a6e48fc40123e49d6c8480aad6875d
[]
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
4,298
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.bitraversable.basic import Mathlib.PostPort universes u l_1 u_1 namespace Mathlib /-! # Bitraversable Lemmas ## Main definitions * tfst - traverse on first functor argument * tsnd - traverse on second functor argument ## Lemmas Combination of * bitraverse * tfst * tsnd with the applicatives `id` and `comp` ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ namespace bitraversable /-- traverse on the first functor argument -/ def tfst {t : Type u → Type u → Type u} [bitraversable t] {β : Type u} {F : Type u → Type u} [Applicative F] {α : Type u} {α' : Type u} (f : α → F α') : t α β → F (t α' β) := bitraverse f pure /-- traverse on the second functor argument -/ def tsnd {t : Type u → Type u → Type u} [bitraversable t] {β : Type u} {F : Type u → Type u} [Applicative F] {α : Type u} {α' : Type u} (f : α → F α') : t β α → F (t β α') := bitraverse pure f theorem id_tfst {t : Type u → Type u → Type u} [bitraversable t] [is_lawful_bitraversable t] {α : Type u} {β : Type u} (x : t α β) : tfst id.mk x = id.mk x := id_bitraverse theorem id_tsnd {t : Type u → Type u → Type u} [bitraversable t] [is_lawful_bitraversable t] {α : Type u} {β : Type u} (x : t α β) : tsnd id.mk x = id.mk x := id_bitraverse theorem tfst_comp_tfst {t : Type l_1 → Type l_1 → Type l_1} [bitraversable t] {F : Type l_1 → Type l_1} {G : Type l_1 → Type l_1} [Applicative F] [Applicative G] [is_lawful_bitraversable t] [is_lawful_applicative F] [is_lawful_applicative G] {α₀ : Type l_1} {α₁ : Type l_1} {α₂ : Type l_1} {β : Type l_1} (f : α₀ → F α₁) (f' : α₁ → G α₂) : functor.comp.mk ∘ Functor.map (tfst f') ∘ tfst f = tfst (functor.comp.mk ∘ Functor.map f' ∘ f) := funext fun (x : t α₀ β) => comp_tfst f f' x theorem tfst_tsnd {t : Type u → Type u → Type u} [bitraversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [Applicative G] [is_lawful_bitraversable t] [is_lawful_applicative F] [is_lawful_applicative G] {α₀ : Type u} {α₁ : Type u} {β₀ : Type u} {β₁ : Type u} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) : functor.comp.mk (tfst f <$> tsnd f' x) = bitraverse (functor.comp.mk ∘ pure ∘ f) (functor.comp.mk ∘ Functor.map pure ∘ f') x := sorry theorem tsnd_tfst {t : Type u → Type u → Type u} [bitraversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [Applicative G] [is_lawful_bitraversable t] [is_lawful_applicative F] [is_lawful_applicative G] {α₀ : Type u} {α₁ : Type u} {β₀ : Type u} {β₁ : Type u} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) : functor.comp.mk (tsnd f' <$> tfst f x) = bitraverse (functor.comp.mk ∘ Functor.map pure ∘ f) (functor.comp.mk ∘ pure ∘ f') x := sorry theorem comp_tsnd {t : Type u → Type u → Type u} [bitraversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [Applicative G] [is_lawful_bitraversable t] [is_lawful_applicative F] [is_lawful_applicative G] {α : Type u} {β₀ : Type u} {β₁ : Type u} {β₂ : Type u} (g : β₀ → F β₁) (g' : β₁ → G β₂) (x : t α β₀) : functor.comp.mk (tsnd g' <$> tsnd g x) = tsnd (functor.comp.mk ∘ Functor.map g' ∘ g) x := sorry theorem tfst_eq_fst_id {t : Type u → Type u → Type u} [bitraversable t] [is_lawful_bitraversable t] {α : Type u} {α' : Type u} {β : Type u} (f : α → α') (x : t α β) : tfst (id.mk ∘ f) x = id.mk (bifunctor.fst f x) := sorry theorem tsnd_eq_snd_id {t : Type u → Type u → Type u} [bitraversable t] [is_lawful_bitraversable t] {α : Type u} {β : Type u} {β' : Type u} (f : β → β') (x : t α β) : tsnd (id.mk ∘ f) x = id.mk (bifunctor.snd f x) := sorry end Mathlib
0b89ef98544269317a8b31101de5a3ebbe5f9555
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1609.lean
c80d9ef656e23adc0b060d83038bccf4e68ce63f
[ "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
158
lean
universe variable u inductive pred : ∀ (X : Type u), list X → Type (u+1) | foo X (l1 : list X) (l2 : list (option X)) : pred (option X) l2 → pred X l1
4a9983d123b1a56195b6a482e7ab21da847655db
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/manifold/instances/units_of_normed_algebra.lean
09550e6f0f7bbff3dad8f59d2ec1dc85711217c3
[ "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,527
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Heather Macbeth -/ import geometry.manifold.smooth_manifold_with_corners import analysis.normed_space.units /-! # Units of a normed algebra This file is a stub, containing a construction of the charted space structure on the group of units of a complete normed ring `R`, and of the smooth manifold structure on the group of units of a complete normed `𝕜`-algebra `R`. This manifold is actually a Lie group, which eventually should be the main result of this file. An important special case of this construction is the general linear group. For a normed space `V` over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see `continuous_linear_map.to_normed_algebra`), so this construction provides a Lie group structure on its group of units, the general linear group GL(`𝕜`, `V`). ## TODO The Lie group instance requires the following fields: ``` instance : lie_group 𝓘(𝕜, R) (units R) := { smooth_mul := sorry, smooth_inv := sorry, ..units.smooth_manifold_with_corners } ``` The ingredients needed for the construction are * smoothness of multiplication and inversion in the charts, i.e. as functions on the normed `𝕜`-space `R`: see `times_cont_diff_at_ring_inverse` for the inversion result, and `times_cont_diff_mul` (needs to be generalized from field to algebra) for the multiplication result * for an open embedding `f`, whose domain is equipped with the induced manifold structure `f.singleton_smooth_manifold_with_corners`, characterization of smoothness of functions to/from this manifold in terms of smoothness in the target space. See the pair of lemmas `times_cont_mdiff_coe_sphere` and `times_cont_mdiff.cod_restrict_sphere` for a model. None of this should be particularly difficult. -/ noncomputable theory open_locale manifold namespace units variables {R : Type*} [normed_ring R] [complete_space R] instance : charted_space R (units R) := open_embedding_coe.singleton_charted_space lemma chart_at_apply {a : units R} {b : units R} : chart_at R a b = b := rfl lemma chart_at_source {a : units R} : (chart_at R a).source = set.univ := rfl variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_algebra 𝕜 R] instance : smooth_manifold_with_corners 𝓘(𝕜, R) (units R) := open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(𝕜, R) end units
48ae5c3126acaa0160f6a1ce3f63bcec73686f52
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/analytic/basic.lean
500fe6492ac0c6b14257a8b02a412a681a5e70b5
[ "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
50,599
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, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import data.equiv.fin /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥₊ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma le_radius_of_eventually_le (C) (h : ∀ᶠ n in at_top, ∥p n∥ * r ^ n ≤ C) : ↑r ≤ p.radius := p.le_radius_of_is_O $ is_O.of_bound C $ h.mono $ λ n hn, by simpa lemma le_radius_of_summable_nnnorm (h : summable (λ n, ∥p n∥₊ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_bound_nnreal (∑' n, ∥p n∥₊ * r ^ n) $ λ n, le_tsum' h _ lemma le_radius_of_summable (h : summable (λ n, ∥p n∥ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_summable_nnnorm $ by { simp only [← coe_nnnorm] at h, exact_mod_cast h } lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, nat.sub_add_cancel hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc |∥p n∥ * r ^ n| = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, rw [← pos_iff_ne_zero, ← nnreal.coe_pos] at h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := by simpa only [div_one] using (div_lt_div_left h₀ zero_lt_one ha.1).2 ha.2, norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥₊ * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < ∥x∥₊) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥ * r ^ n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, exact summable_of_nonneg_of_le (λ n, mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg _)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _), end lemma summable_norm_apply (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, ∥p n (λ _, x)∥) := begin rw mem_emetric_ball_zero_iff at hx, refine summable_of_nonneg_of_le (λ _, norm_nonneg _) (λ n, ((p n).le_op_norm _).trans_eq _) (p.summable_norm_mul_pow hx), simp end lemma summable_nnnorm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥₊ * r ^ n) := by { rw ← nnreal.summable_coe, push_cast, exact p.summable_norm_mul_pow h } protected lemma summable [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, p n (λ _, x)) := summable_of_summable_norm (p.summable_norm_apply hx) lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow₀ _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) protected lemma has_sum [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : has_sum (λ n : ℕ, p n (λ _, x)) (p.sum x) := (p.summable hx).has_sum /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_zero_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_zero_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_zero_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp only [is_O_bot, emetric.ball_zero, principal_empty, ennreal.coe_zero] }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)) using 1, rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa only [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp only [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ protected lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, by { rw zero_add, exact p.has_sum hy } } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := (h.has_sum hy).unique (p.has_sum (lt_of_lt_of_le hy h.r_le)) /-- The sum of a converging power series is continuous in its disk of convergence. -/ protected lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series section variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} /-- A term of `formal_multilinear_series.change_origin_series`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Each term of `p.change_origin x` is itself an analytic function of `x` given by the series `p.change_origin_series`. Each term in `change_origin_series` is the sum of `change_origin_series_term`'s over all `s` of cardinality `l`. -/ def change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : E [×l]→L[𝕜] E [×k]→L[𝕜] F := continuous_multilinear_map.curry_fin_finset 𝕜 E F hs (by erw [finset.card_compl, fintype.card_fin, hs, nat.add_sub_cancel]) (p $ k + l) lemma change_origin_series_term_apply (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y)) := continuous_multilinear_map.curry_fin_finset_apply_const _ _ _ _ _ @[simp] lemma norm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥ = ∥p (k + l)∥ := by simp only [change_origin_series_term, linear_isometry_equiv.norm_map] @[simp] lemma nnnorm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥₊ = ∥p (k + l)∥₊ := by simp only [change_origin_series_term, linear_isometry_equiv.nnnorm_map] lemma nnnorm_change_origin_series_term_apply_le (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : ∥p.change_origin_series_term k l s hs (λ _, x) (λ _, y)∥₊ ≤ ∥p (k + l)∥₊ * ∥x∥₊ ^ l * ∥y∥₊ ^ k := begin rw [← p.nnnorm_change_origin_series_term k l s hs, ← fin.prod_const, ← fin.prod_const], apply continuous_multilinear_map.le_of_op_nnnorm_le, apply continuous_multilinear_map.le_op_nnnorm end /-- The power series for `f.change_origin k`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin_series (k : ℕ) : formal_multilinear_series 𝕜 E (E [×k]→L[𝕜] F) := λ l, ∑ s : {s : finset (fin (k + l)) // finset.card s = l}, p.change_origin_series_term k l s s.2 lemma nnnorm_change_origin_series_le_tsum (k l : ℕ) : ∥p.change_origin_series k l∥₊ ≤ ∑' (x : {s : finset (fin (k + l)) // s.card = l}), ∥p (k + l)∥₊ := (nnnorm_sum_le _ _).trans_eq $ by simp only [tsum_fintype, nnnorm_change_origin_series_term] lemma nnnorm_change_origin_series_apply_le_tsum (k l : ℕ) (x : E) : ∥p.change_origin_series k l (λ _, x)∥₊ ≤ ∑' s : {s : finset (fin (k + l)) // s.card = l}, ∥p (k + l)∥₊ * ∥x∥₊ ^ l := begin rw [nnreal.tsum_mul_right, ← fin.prod_const], exact (p.change_origin_series k l).le_of_op_nnnorm_le _ (p.nnnorm_change_origin_series_le_tsum _ _) end /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, (p.change_origin_series k).sum x /-- An auxiliary equivalence useful in the proofs about `formal_multilinear_series.change_origin_series`: the set of triples `(k, l, s)`, where `s` is a `finset (fin (k + l))` of cardinality `l` is equivalent to the set of pairs `(n, s)`, where `s` is a `finset (fin n)`. The forward map sends `(k, l, s)` to `(k + l, s)` and the inverse map sends `(n, s)` to `(n - finset.card s, finset.card s, s)`. The actual definition is less readable because of problems with non-definitional equalities. -/ @[simps] def change_origin_index_equiv : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}) ≃ Σ n : ℕ, finset (fin n) := { to_fun := λ s, ⟨s.1 + s.2.1, s.2.2⟩, inv_fun := λ s, ⟨s.1 - s.2.card, s.2.card, ⟨s.2.map (fin.cast $ (nat.sub_add_cancel $ card_finset_fin_le s.2).symm).to_equiv.to_embedding, finset.card_map _⟩⟩, left_inv := begin rintro ⟨k, l, ⟨s : finset (fin $ k + l), hs : s.card = l⟩⟩, dsimp only [subtype.coe_mk], -- Lean can't automatically generalize `k' = k + l - s.card`, `l' = s.card`, so we explicitly -- formulate the generalized goal suffices : ∀ k' l', k' = k → l' = l → ∀ (hkl : k + l = k' + l') hs', (⟨k', l', ⟨finset.map (fin.cast hkl).to_equiv.to_embedding s, hs'⟩⟩ : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l})) = ⟨k, l, ⟨s, hs⟩⟩, { apply this; simp only [hs, nat.add_sub_cancel] }, rintro _ _ rfl rfl hkl hs', simp only [equiv.refl_to_embedding, fin.cast_refl, finset.map_refl, eq_self_iff_true, order_iso.refl_to_equiv, and_self, heq_iff_eq] end, right_inv := begin rintro ⟨n, s⟩, simp [nat.sub_add_cancel (card_finset_fin_le s), fin.cast_to_equiv] end } lemma change_origin_series_summable_aux₁ {r r' : ℝ≥0} (hr : (r + r' : ℝ≥0∞) < p.radius) : summable (λ s : Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (s.1 + s.2.1)∥₊ * r ^ s.2.1 * r' ^ s.1) := begin rw ← change_origin_index_equiv.symm.summable_iff, dsimp only [(∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst], have : ∀ n : ℕ, has_sum (λ s : finset (fin n), ∥p (n - s.card + s.card)∥₊ * r ^ s.card * r' ^ (n - s.card)) (∥p n∥₊ * (r + r') ^ n), { intro n, -- TODO: why `simp only [nat.sub_add_cancel (card_finset_fin_le _)]` fails? convert_to has_sum (λ s : finset (fin n), ∥p n∥₊ * (r ^ s.card * r' ^ (n - s.card))) _, { ext1 s, rw [nat.sub_add_cancel (card_finset_fin_le _), mul_assoc] }, rw ← fin.sum_pow_mul_eq_add_pow, exact (has_sum_fintype _).mul_left _ }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact p.summable_nnnorm_mul_pow hr end lemma change_origin_series_summable_aux₂ (hr : (r : ℝ≥0∞) < p.radius) (k : ℕ) : summable (λ s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * r ^ s.1) := begin rcases ennreal.lt_iff_exists_add_pos_lt.1 hr with ⟨r', h0, hr'⟩, simpa only [mul_inv_cancel_right₀ (pow_pos h0 _).ne'] using ((nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr')).1 k).mul_right (r' ^ k)⁻¹ end lemma change_origin_series_summable_aux₃ {r : ℝ≥0} (hr : ↑r < p.radius) (k : ℕ) : summable (λ l : ℕ, ∥p.change_origin_series k l∥₊ * r ^ l) := begin refine nnreal.summable_of_le (λ n, _) (nnreal.summable_sigma.1 $ p.change_origin_series_summable_aux₂ hr k).2, simp only [nnreal.tsum_mul_right], exact mul_le_mul' (p.nnnorm_change_origin_series_le_tsum _ _) le_rfl end lemma le_change_origin_series_radius (k : ℕ) : p.radius ≤ (p.change_origin_series k).radius := ennreal.le_of_forall_nnreal_lt $ λ r hr, le_radius_of_summable_nnnorm _ (p.change_origin_series_summable_aux₃ hr k) lemma nnnorm_change_origin_le (k : ℕ) (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : ∥p.change_origin x k∥₊ ≤ ∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1 := begin refine tsum_of_nnnorm_bounded _ (λ l, p.nnnorm_change_origin_series_apply_le_tsum k l x), have := p.change_origin_series_summable_aux₂ h k, refine has_sum.sigma this.has_sum (λ l, _), exact ((nnreal.summable_sigma.1 this).1 l).has_sum end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - ∥x∥₊ ≤ (p.change_origin x).radius := begin refine ennreal.le_of_forall_pos_nnreal_lt (λ r h0 hr, _), rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, have hr' : (∥x∥₊ : ℝ≥0∞) < p.radius, from (le_add_right le_rfl).trans_lt hr, apply le_radius_of_summable_nnnorm, have : ∀ k : ℕ, ∥p.change_origin x k∥₊ * r ^ k ≤ (∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1) * r ^ k, from λ k, mul_le_mul_right' (p.nnnorm_change_origin_le k hr') (r ^ k), refine nnreal.summable_of_le this _, simpa only [← nnreal.tsum_mul_right] using (nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr)).2 end end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variables [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} lemma has_fpower_series_on_ball_change_origin (k : ℕ) (hr : 0 < p.radius) : has_fpower_series_on_ball (λ x, p.change_origin x k) (p.change_origin_series k) 0 p.radius := have _ := p.le_change_origin_series_radius k, ((p.change_origin_series k).has_fpower_series_on_ball (hr.trans_le this)).mono hr this /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (∥x∥₊ + ∥y∥₊ : ℝ≥0∞) < p.radius) : (p.change_origin x).sum y = (p.sum (x + y)) := begin have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, have x_mem_ball : x ∈ emetric.ball (0 : E) p.radius, from mem_emetric_ball_zero_iff.2 ((le_add_right le_rfl).trans_lt h), have y_mem_ball : y ∈ emetric.ball (0 : E) (p.change_origin x).radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_lt_of_le _ p.change_origin_radius), rwa [ennreal.lt_sub_iff_add_lt, add_comm] }, have x_add_y_mem_ball : x + y ∈ emetric.ball (0 : E) p.radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ h), exact_mod_cast nnnorm_add_le x y }, set f : (Σ (k l : ℕ), {s : finset (fin (k + l)) // s.card = l}) → F := λ s, p.change_origin_series_term s.1 s.2.1 s.2.2 s.2.2.2 (λ _, x) (λ _, y), have hsf : summable f, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₁ h) _, rintro ⟨k, l, s, hs⟩, dsimp only [subtype.coe_mk], exact p.nnnorm_change_origin_series_term_apply_le _ _ _ _ _ _ }, have hf : has_sum f ((p.change_origin x).sum y), { refine has_sum.sigma_of_has_sum ((p.change_origin x).summable y_mem_ball).has_sum (λ k, _) hsf, { dsimp only [f], refine continuous_multilinear_map.has_sum_eval _ _, have := (p.has_fpower_series_on_ball_change_origin k radius_pos).has_sum x_mem_ball, rw zero_add at this, refine has_sum.sigma_of_has_sum this (λ l, _) _, { simp only [change_origin_series, continuous_multilinear_map.sum_apply], apply has_sum_fintype }, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₂ (mem_emetric_ball_zero_iff.1 x_mem_ball) k) (λ s, _), refine (continuous_multilinear_map.le_op_nnnorm _ _).trans_eq _, simp } } }, refine hf.unique (change_origin_index_equiv.symm.has_sum_iff.1 _), refine has_sum.sigma_of_has_sum (p.has_sum x_add_y_mem_ball) (λ n, _) (change_origin_index_equiv.symm.summable_iff.2 hsf), erw [(p n).map_add_univ (λ _, x) (λ _, y)], convert has_sum_fintype _, ext1 s, dsimp only [f, change_origin_series_term, (∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst, change_origin_index_equiv_symm_apply_snd_snd_coe], rw continuous_multilinear_map.curry_fin_finset_apply_const, have : ∀ m (hm : n = m), p n (s.piecewise (λ _, x) (λ _, y)) = p m ((s.map (fin.cast hm).to_equiv.to_embedding).piecewise (λ _, x) (λ _, y)), { rintro m rfl, simp, congr /- probably different `decidable_eq` instances -/ }, apply this end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (∥y∥₊ : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - ∥y∥₊) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := λ z hz, begin convert (p.change_origin y).has_sum _, { rw [mem_emetric_ball_zero_iff, ennreal.lt_sub_iff_add_lt, add_comm] at hz, rw [p.change_origin_eval (hz.trans_le hf.r_le), add_assoc, hf.sum], refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ hz), exact_mod_cast nnnorm_add_le y z }, { refine emetric.ball_subset_ball (le_trans _ p.change_origin_radius) hz, exact ennreal.sub_le_sub hf.r_le le_rfl } end } /-- If a function admits a power series expansion `p` on an open ball `B (x, r)`, then it is analytic at every point of this ball. -/ lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (∥y - x∥₊ : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) /-- For any function `f` from a normed vector space to a Banach space, the set of points `x` such that `f` is analytic at `x` is open. -/ lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_mem_nhds, rintro x ⟨p, r, hr⟩, exact mem_of_superset (emetric.ball_mem_nhds _ hr.r_pos) (λ y hy, hr.analytic_at_of_mem hy) end end
a6753a0fa1e25c0e659f80bbf6f5959c482f784d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/normed_space/basic.lean
b51783cc84e8207f5cf1e6c9d215d1e86fb80425
[ "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
73,758
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.punit_instances import topology.instances.nnreal import topology.algebra.module import topology.algebra.algebra import topology.metric_space.antilipschitz import topology.algebra.ordered.liminf_limsup /-! # Normed spaces Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory of `semi_normed_group` and we specialize to `normed_group` at the end. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal ennreal /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a pseudometric space structure. -/ class semi_normed_group (α : Type*) extends has_norm α, add_comm_group α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is a seminormed group. -/ @[priority 100] -- see Note [lower instance priority] instance normed_group.to_semi_normed_group [β : normed_group α] : semi_normed_group α := { ..β } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist' [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A seminormed group can be built from a seminorm that satisfies algebraic properties. This is formalised in this structure. -/ structure semi_normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_zero : ∥(0 : α)∥ = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a seminormed group from core properties of a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. -/ noncomputable def semi_normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : semi_normed_group.core α) : semi_normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, by simp [C.norm_zero], dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } instance : normed_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ∥r∥ = 0 := rfl instance : normed_group ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl } lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl section semi_normed_group variables [semi_normed_group α] [semi_normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := semi_normed_group.dist_eq _ _ lemma dist_eq_norm' (g h : α) : dist g h = ∥h - g∥ := by rw [dist_comm, dist_eq_norm] @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] @[simp] lemma dist_zero_left : dist (0:α) = norm := funext $ λ g, by rw [dist_comm, dist_zero_right] lemma tendsto_norm_cocompact_at_top [proper_space α] : tendsto norm (cocompact α) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0:α) lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := by simpa only [sub_eq_add_neg] using dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂) lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := by rw [← dist_zero_right, dist_self] @[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma mem_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] @[simp] lemma mem_ball_0_iff {ε : ℝ} {x : α} : x ∈ ball (0 : α) ε ↔ ∥x∥ < ε := by rw [mem_ball, dist_zero_right] lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] lemma mem_closed_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r := by rw [mem_closed_ball', dist_eq_norm] lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_le_norm_add_const_of_dist_le {a b : α} {c : ℝ} (h : dist a b ≤ c) : ∥a∥ ≤ ∥b∥ + c := norm_le_of_mem_closed_ball h lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_norm_add_const_of_dist_lt {a b : α} {c : ℝ} (h : dist a b < c) : ∥a∥ < ∥b∥ + c := norm_lt_of_mem_ball h @[simp] lemma mem_sphere_iff_norm (v w : α) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r := by simp [dist_eq_norm] @[simp] lemma mem_sphere_zero_iff_norm {w : α} {r : ℝ} : w ∈ sphere (0:α) r ↔ ∥w∥ = r := by simp [dist_eq_norm] @[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:α) r) : ∥(x:α)∥ = r := mem_sphere_zero_iff_norm.mp x.2 lemma ne_zero_of_norm_pos {g : α} : 0 < ∥ g ∥ → g ≠ 0 := begin intros hpos hzero, rw [hzero, norm_zero] at hpos, exact lt_irrefl 0 hpos, end lemma nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:α) r) : (x:α) ≠ 0 := begin refine ne_zero_of_norm_pos _, rwa norm_eq_of_mem_sphere x, end lemma nonzero_of_mem_unit_sphere (x : sphere (0:α) 1) : (x:α) ≠ 0 := by { apply nonzero_of_mem_sphere, norm_num } /-- We equip the sphere, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_neg (sphere (0:α) r) := { neg := λ w, ⟨-↑w, by simp⟩ } @[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0:α) r) : (((-v) : sphere _ _) : α) = - (v:α) := rfl theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s) {x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.continuous_of_bound (f : α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : ℝ≥0 := ⟨norm a, norm_nonneg a⟩ @[simp, norm_cast] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ℝ≥0∞) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ℝ≥0∞) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma mem_emetric_ball_0_iff {x : β} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : β) r ↔ ↑(nnnorm x) < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [pseudo_emetric_space α] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end lemma antilipschitz_with.add_sub_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg (g - f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.sub_apply, add_sub_cancel'_right] using hf.add_lipschitz_with hg hK /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ instance add_subgroup.semi_normed_group {E : Type*} [semi_normed_group E] (s : add_subgroup E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp] lemma coe_norm_subgroup {E : Type*} [semi_normed_group E] {s : add_subgroup E} (x : s) : ∥x∥ = ∥(x:E)∥ := rfl /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.semi_normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. See note [implicit instance arguments]. -/ @[simp, norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : E)∥ = ∥x∥ := rfl @[simp] lemma submodule.norm_mk {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : E) (hx : x ∈ s) : ∥(⟨x, hx⟩ : s)∥ = ∥x∥ := rfl /-- seminormed group instance on the product of two seminormed groups, using the sup norm. -/ instance prod.semi_normed_group : semi_normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.semi_norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnsemi_norm_def (x : α × β) : nnnorm x = max (nnnorm x.1) (nnnorm x.2) := by { have := x.semi_norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma semi_norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma semi_norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma semi_norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- seminormed group instance on the product of finitely many seminormed groups, using the sup norm. -/ instance pi.semi_normed_group {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] : semi_normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : ℝ≥0) : ℝ), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_semi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_semi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma semi_norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_semi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_semi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnsemi_norm_const [nonempty ι] [fintype ι] (a : α) : nnnorm (λ i : ι, a) = nnnorm a := nnreal.eq $ pi_semi_norm_const a lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] } lemma is_bounded_under_of_tendsto {l : filter ι} {f : ι → α} {c : α} (h : filter.tendsto f l (𝓝 c)) : is_bounded_under (≤) l (λ x, ∥f x∥) := ⟨∥c∥ + 1, @tendsto.eventually ι α f _ _ (λ k, ∥k∥ ≤ ∥c∥ + 1) h (filter.eventually_iff_exists_mem.mpr ⟨metric.closed_ball c 1, metric.closed_ball_mem_nhds c zero_lt_one, λ y hy, norm_le_norm_add_const_of_dist_le hy⟩)⟩ lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) := by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] } /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ (n:γ), ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' lemma tendsto_norm_sub_self (x : α) : tendsto (λ g : α, ∥g - x∥) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:α)) (𝓝 x) _) lemma tendsto_norm {x : α} : tendsto (λg : α, ∥g∥) (𝓝 x) (𝓝 ∥x∥) := by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (0:α)) _ _) lemma tendsto_norm_zero : tendsto (λg : α, ∥g∥) (𝓝 0) (𝓝 0) := by simpa using tendsto_norm_sub_self (0:α) @[continuity] lemma continuous_norm : continuous (λg:α, ∥g∥) := by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:α))) @[continuity] lemma continuous_nnnorm : continuous (nnnorm : α → ℝ≥0) := continuous_subtype_mk _ continuous_norm lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : α → ℝ) := by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : α) lemma uniform_continuous_norm : uniform_continuous (norm : α → ℝ) := lipschitz_with_one_norm.uniform_continuous lemma uniform_continuous_nnnorm : uniform_continuous (nnnorm : α → ℝ≥0) := uniform_continuous_subtype_mk uniform_continuous_norm _ section variables {l : filter γ} {f : γ → α} {a : α} lemma filter.tendsto.norm {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto_norm.comp h lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h end section variables [topological_space γ] {f : γ → α} {s : set γ} {a : γ} {b : α} lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h lemma continuous.nnnorm (h : continuous f) : continuous (λ x, nnnorm (f x)) := continuous_nnnorm.comp h lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, nnnorm (f x)) a := h.nnnorm lemma continuous_within_at.norm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥) s a := h.norm lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) : continuous_within_at (λ x, nnnorm (f x)) s a := h.nnnorm lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s := λ x hx, (h x hx).norm lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, nnnorm (f x)) s := λ x hx, (h x hx).nnnorm end /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference lemma nat.norm_cast_le [has_one α] : ∀ n : ℕ, ∥(n : α)∥ ≤ n * ∥(1 : α)∥ | 0 := by simp | (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul], exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl } end semi_normed_group section normed_group /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- The `semi_normed_group.core` induced by a `normed_group.core`. -/ lemma normed_group.core.to_semi_normed_group.core {α : Type*} [add_comm_group α] [has_norm α] (C : normed_group.core α) : semi_normed_group.core α := { norm_zero := (C.norm_eq_zero_iff 0).2 rfl, triangle := C.triangle, norm_neg := C.norm_neg } /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { eq_of_dist_eq_zero := λ x y h, begin rw [dist_eq_norm] at h, exact sub_eq_zero.mp ((C.norm_eq_zero_iff _).1 h) end ..semi_normed_group.of_core α (normed_group.core.to_semi_normed_group.core C) } variables [normed_group α] [normed_group β] @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma eq_of_norm_sub_le_zero {g h : α} (a : ∥g - h∥ ≤ 0) : g = h := by rwa [← sub_eq_zero, ← norm_le_zero_iff] lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_sub_eq_zero_iff {u v : α} : ∥u - v∥ = 0 ↔ u = v := begin convert dist_eq_zero, rwa dist_eq_norm end @[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] /-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/ instance add_subgroup.normed_group {E : Type*} [normed_group E] (s : add_subgroup E) : normed_group s := { ..add_subgroup.semi_normed_group s } /-- A submodule of a normed group is also a normed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { ..submodule.semi_normed_group s } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { ..prod.semi_normed_group } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : α × β) : nnnorm x = max (nnnorm x.1) (nnnorm x.2) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { ..pi.semi_normed_group } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The norm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnnorm_const [nonempty ι] [fintype ι] (a : α) : nnnorm (λ i : ι, a) = nnnorm a := nnreal.eq $ pi_norm_const a lemma tendsto_norm_nhds_within_zero : tendsto (norm : α → ℝ) (𝓝[{0}ᶜ] 0) (𝓝[set.Ioi 0] 0) := (continuous_norm.tendsto' (0 : α) 0 norm_zero).inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff.2 end normed_group section semi_normed_ring /-- A seminormed ring is a ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_ring (α : Type*) extends has_norm α, ring α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_semi_normed_ring [β : normed_ring α] : semi_normed_ring α := { ..β } /-- A seminormed commutative ring is a commutative ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_comm_ring (α : Type*) extends semi_normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_comm_ring (α : Type*) extends normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a seminormed commutative ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_comm_ring.to_semi_normed_comm_ring [β : normed_comm_ring α] : semi_normed_comm_ring α := { ..β } instance : normed_comm_ring punit := { norm_mul := λ _ _, by simp, ..punit.normed_group, ..punit.comm_ring, } /-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop := (norm_one : ∥(1:α)∥ = 1) export norm_one_class (norm_one) attribute [simp] norm_one @[simp] lemma nnnorm_one [semi_normed_group α] [has_one α] [norm_one_class α] : nnnorm (1:α) = 1 := nnreal.eq norm_one @[priority 100] -- see Note [lower instance priority] instance semi_normed_comm_ring.to_comm_ring [β : semi_normed_comm_ring α] : comm_ring α := { ..β } @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring.to_semi_normed_group [β : semi_normed_ring α] : semi_normed_group α := { ..β } instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α] [normed_group β] [has_one β] [norm_one_class β] : norm_one_class (α × β) := ⟨by simp [prod.norm_def]⟩ variables [semi_normed_ring α] lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := semi_normed_ring.norm_mul _ _ /-- A subalgebra of a seminormed ring is also a seminormed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.semi_normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [semi_normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : semi_normed_ring s := { norm_mul := λ a b, norm_mul_le a.1 b.1, ..s.to_submodule.semi_normed_group } /-- A subalgebra of a normed ring is also a normed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : normed_ring s := { ..s.semi_normed_ring } lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod | [] h := (h rfl).elim | [a] _ := by simp | (a :: b :: l) _ := begin rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥], refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)), exact list.norm_prod_le' (list.cons_ne_nil b l) end lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod | [] := by simp | (a::l) := list.norm_prod_le' (list.cons_ne_nil a l) lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, have : l.map f ≠ [], by simpa using hs, simpa using list.norm_prod_le' this end lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, simpa using (l.map f).norm_prod_le end /-- If `α` is a seminormed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/ lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := by { rw [pow_succ _ (n+1), pow_succ _ (n+1)], exact le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) } /-- If `α` is a seminormed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/ lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n | 0 := by simp | (n+1) := norm_pow_le' a n.zero_lt_succ lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n := eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩ /-- In a seminormed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ := norm_mul_le x /-- In a seminormed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ := λ y, by {rw mul_comm, convert norm_mul_le y x} /-- Seminormed ring structure on the product of two seminormed rings, using the sup norm. -/ instance prod.semi_normed_ring [semi_normed_ring β] : semi_normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp [max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.semi_normed_group } end semi_normed_ring section normed_ring variables [normed_ring α] lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ := norm_pos_iff.mpr (units.ne_zero x) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring β] : normed_ring (α × β) := { norm_mul := norm_mul_le, ..prod.semi_normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring_top_monoid [semi_normed_ring α] : has_continuous_mul α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ begin have : ∀ e : α × α, ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥, { intro e, calc ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2∥ : by rw [mul_sub, sub_mul, sub_add_sub_cancel] ... ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥ : norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) }, refine squeeze_zero (λ e, norm_nonneg _) this _, convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub tendsto_const_nhds).norm).add (((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _), show tendsto _ _ _, from tendsto_const_nhds, simp end ⟩ /-- A seminormed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance semi_normed_top_ring [semi_normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply tendsto_norm_sub_self ⟩ /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) namespace normed_field section normed_field variables [normed_field α] @[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[priority 100] -- see Note [lower instance priority] instance to_normed_comm_ring : normed_comm_ring α := { norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› } @[priority 900] instance to_norm_one_class : norm_one_class α := ⟨mul_left_cancel' (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $ by rw [← norm_mul, mul_one, mul_one]⟩ @[simp] lemma nnnorm_mul (a b : α) : nnnorm (a * b) = nnnorm a * nnnorm b := nnreal.eq $ norm_mul a b /-- `norm` as a `monoid_hom`. -/ @[simps] def norm_hom : monoid_with_zero_hom α ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩ /-- `nnnorm` as a `monoid_hom`. -/ @[simps] def nnnorm_hom : monoid_with_zero_hom α ℝ≥0 := ⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩ @[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n := (norm_hom.to_monoid_hom : α →* ℝ).map_pow a @[simp] lemma nnnorm_pow (a : α) (n : ℕ) : nnnorm (a ^ n) = nnnorm a ^ n := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_pow a n @[simp] lemma norm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := (norm_hom.to_monoid_hom : α →* ℝ).map_prod f s @[simp] lemma nnnorm_prod (s : finset β) (f : β → α) : nnnorm (∏ b in s, f b) = ∏ b in s, nnnorm (f b) := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s @[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ := (norm_hom : monoid_with_zero_hom α ℝ).map_div a b @[simp] lemma nnnorm_div (a b : α) : nnnorm (a / b) = nnnorm a / nnnorm b := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_div a b @[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := (norm_hom : monoid_with_zero_hom α ℝ).map_inv' a @[simp] lemma nnnorm_inv (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n := (norm_hom : monoid_with_zero_hom α ℝ).map_fpow @[simp] lemma nnnorm_fpow : ∀ (a : α) (n : ℤ), nnnorm (a^n) = (nnnorm a)^n := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_fpow @[priority 100] -- see Note [lower instance priority] instance : has_continuous_inv' α := begin refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩, have r0' : 0 < ∥r∥ := norm_pos_iff.2 r0, rcases exists_between r0' with ⟨ε, ε0, εr⟩, have : ∀ᶠ e in 𝓝 r, ∥e⁻¹ - r⁻¹∥ ≤ ∥r - e∥ / ∥r∥ / ε, { filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr], intros e he, have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he), calc ∥e⁻¹ - r⁻¹∥ = ∥r - e∥ / ∥r∥ / ∥e∥ : by field_simp [mul_comm] ... ≤ ∥r - e∥ / ∥r∥ / ε : div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le }, refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _, refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _, simp end end normed_field variables (α) [nondiscrete_normed_field α] lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], rintro rfl, rw norm_zero at hy, exact lt_asymm zero_lt_one hy }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ variable {α} @[instance] lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[{x}ᶜ] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) end normed_field instance : normed_field ℝ := { norm_mul' := abs_mul, .. real.normed_group } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } namespace real lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x := abs_of_nonneg hx @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _) @[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : nnnorm x = ⟨x, hx⟩ := nnreal.eq $ norm_of_nonneg hx lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (nnnorm x : ℝ≥0∞) = ennreal.of_real x := by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] } end real namespace nnreal open_locale nnreal @[simp] lemma norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x := by rw [real.norm_eq_abs, x.abs_eq] @[simp] lemma nnnorm_eq (x : ℝ≥0) : nnnorm (x : ℝ) = x := nnreal.eq $ real.norm_of_nonneg x.2 end nnreal @[simp] lemma norm_norm [semi_normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := real.norm_of_nonneg (norm_nonneg _) @[simp] lemma nnnorm_norm [semi_normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] /-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/ lemma normed_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ∥f n - b∥ < ε := (at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) /-- A variant of `normed_group.tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ lemma normed_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_top_order α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ∥f n - b∥ < ε := (at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) instance : normed_comm_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub], mul_comm := mul_comm } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : norm_one_class ℤ := ⟨by simp [← int.norm_cast_real]⟩ instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section semi_normed_space section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[semi_normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A seminormed space over a normed field is a vector space endowed with a seminorm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class semi_normed_space (α : Type*) (β : Type*) [normed_field α] [semi_normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) /-- A normed space is a seminormed space. -/ @[priority 100] -- see Note [lower instance priority] instance normed_space.to_semi_normed_space [normed_field α] [normed_group β] [γ : normed_space α β] : semi_normed_space α β := { ..γ } end prio variables [normed_field α] [semi_normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [semi_normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (semi_normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : mul_le_mul_of_nonneg_left (semi_normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end @[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma dist_smul [semi_normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [semi_normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [semi_normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y lemma norm_smul_of_nonneg [semi_normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [semi_normed_group E] [semi_normed_space α E] variables {F : Type*} [semi_normed_group F] [semi_normed_space α F] @[priority 100] -- see Note [lower instance priority] instance semi_normed_space.has_continuous_smul : has_continuous_smul α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from (continuous_const.smul (continuous_id.sub continuous_const)).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) theorem closure_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] variables (α) lemma ne_neg_of_mem_sphere [char_zero α] {r : ℝ} (hr : 0 < r) (x : sphere (0:E) r) : x ≠ - x := λ h, nonzero_of_mem_sphere hr x (eq_zero_of_eq_neg α (by { conv_lhs {rw h}, simp })) lemma ne_neg_of_mem_unit_sphere [char_zero α] (x : sphere (0:E) 1) : x ≠ - x := ne_neg_of_mem_sphere α (by norm_num) x variables {α} open normed_field /-- The product of two seminormed spaces is a seminormed space, with the sup norm. -/ instance prod.semi_normed_space : semi_normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.semi_norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_group, ..prod.module } /-- The product of finitely many seminormed spaces is a seminormed space, with the sup norm. -/ instance pi.semi_normed_space {E : ι → Type*} [fintype ι] [∀i, semi_normed_group (E i)] [∀i, semi_normed_space α (E i)] : semi_normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a seminormed space is also a normed space, with the restriction of the norm. -/ instance submodule.semi_normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [semi_normed_group E] [semi_normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : semi_normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element of with norm different from `0` can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ∥x∥ ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end semi_normed_space section normed_space variables [normed_field α] variables {E : Type*} [normed_group E] [normed_space α E] variables {F : Type*} [normed_group F] [normed_space α F] open normed_field theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases exists_ne (0 : E) with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { ..prod.semi_normed_space } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { ..pi.semi_normed_space } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [normed_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { ..submodule.semi_normed_space s } end normed_space section normed_algebra /-- A seminormed algebra `𝕜'` over `𝕜` is an algebra endowed with a seminorm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra is a seminormed algebra. -/ @[priority 100] -- see Note [lower instance priority] instance normed_algebra.to_semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : semi_normed_algebra 𝕜 𝕜' := { norm_algebra_map_eq := normed_algebra.norm_algebra_map_eq } @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [h : semi_normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := semi_normed_algebra.norm_algebra_map_eq _ variables (𝕜 : Type*) [normed_field 𝕜] variables (𝕜' : Type*) [semi_normed_ring 𝕜'] @[priority 100] instance semi_normed_algebra.to_semi_normed_space [h : semi_normed_algebra 𝕜 𝕜'] : semi_normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : semi_normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } @[priority 100] instance normed_algebra.to_normed_space (𝕜 : Type*) [normed_field 𝕜] (𝕜' : Type*) [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := semi_normed_space.norm_smul_le, ..h } instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} variables (𝕜') [semi_normed_algebra 𝕜 𝕜'] include 𝕜 lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 := by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜)) lemma normed_algebra.norm_one_class : norm_one_class 𝕜' := ⟨normed_algebra.norm_one 𝕜 𝕜'⟩ lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 := begin refine (ne_zero_of_norm_pos _).symm, rw normed_algebra.norm_one 𝕜 𝕜', norm_num, end lemma normed_algebra.nontrivial : nontrivial 𝕜' := ⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜 𝕜'⟩⟩ end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [normed_group E] [normed_space 𝕜' E] (F : Type*) [semi_normed_group F] [semi_normed_space 𝕜' F] /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-seminormed space structure induced by a `𝕜'`-seminormed space structure when `𝕜'` is a seminormed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def semi_normed_space.restrict_scalars : semi_normed_space 𝕜 F := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' F } /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' E } instance {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [I : semi_normed_group F] : semi_normed_group (restrict_scalars 𝕜 𝕜' F) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I instance module.restrict_scalars.semi_normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [normed_field 𝕜'] [semi_normed_group F] [I : semi_normed_space 𝕜' F] : semi_normed_space 𝕜' (restrict_scalars 𝕜 𝕜' F) := I instance module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I instance : semi_normed_space 𝕜 (restrict_scalars 𝕜 𝕜' F) := (semi_normed_space.restrict_scalars 𝕜 𝕜' F : semi_normed_space 𝕜 F) instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := (normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E) end restrict_scalars section summable open_locale classical open finset filter variables [semi_normed_group α] [semi_normed_group β] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff], { simp only [ball_0_eq, set.mem_set_of_eq] }, { rintros s t hst ⟨s', hs'⟩, exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ } end lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : γ → finset ι} {p : filter γ} [ne_bot p] (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma has_sum.norm_le_of_bounded {f : ι → α} {g : ι → ℝ} {a : α} {b : ℝ} (hf : has_sum f a) (hg : has_sum g b) (h : ∀ i, ∥f i∥ ≤ g i) : ∥a∥ ≤ b := le_of_tendsto_of_tendsto' hf.norm hg $ λ s, norm_sum_le_of_le _ $ λ i hi, h i /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀ i, ∥f i∥ ≤ g i) : ∥∑' i : ι, f i∥ ≤ a := begin by_cases hf : summable f, { exact hf.has_sum.norm_le_of_bounded hg h }, { rw [tsum_eq_zero_of_not_summable hf, norm_zero], exact ge_of_tendsto' hg (λ s, sum_nonneg $ λ i hi, (norm_nonneg _).trans (h i)) } end /-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥∑'i, f i∥ ≤ ∑' i, ∥f i∥ := tsum_of_norm_bounded hf.has_sum $ λ i, le_rfl variable [complete_space α] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := begin replace h := mem_cofinite.1 h, refine h.summable_compl_iff.mp _, refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _, rintros ⟨a, h'⟩, simpa using h' end lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → ℝ≥0) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
784de03687229b34f58ab6efea9e11ff83be71f6
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nat_bug2.lean
2edc8f77b20ed0ea93442e252fb3aabd2d750b55
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
716
lean
import logic open eq.ops namespace experiment inductive nat : Type := | zero : nat | succ : nat → nat namespace nat definition plus (x y : nat) : nat := nat.rec x (λn r, succ r) y definition to_nat [coercion] (n : num) : nat := num.rec zero (λn, pos_num.rec (succ zero) (λn r, plus r (plus r (succ zero))) (λn r, plus r r) n) n definition add (x y : nat) : nat := plus x y constant le : nat → nat → Prop infixl `+` := add infix `≤` := le axiom add_one (n:nat) : n + (succ zero) = succ n axiom add_le_right {n m : nat} (H : n ≤ m) (k : nat) : n + k ≤ m + k theorem succ_le {n m : nat} (H : n ≤ m) : succ n ≤ succ m := add_one m ▸ add_one n ▸ add_le_right H (1:num) end nat end experiment
c8b7276116dbe28f7c8526076bb56231c06eed38
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/alias_map.lean
d6b8651106be32adca77df89de73c8581f0553b7
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
8,087
lean
import data.list import data.rbmap import tactic.linarith import .ast import .sized lemma rbmap_insert_lookup_eq {α:Type} {β:Type} {lt:α → α → Prop} [Hdec:decidable_rel lt] (m:rbmap α β lt) (k:α) (x:β) : forall a, cmp_using lt a k = ordering.eq → rbmap.find (rbmap.insert m k x) a = some x := sorry lemma rbmap_insert_lookup_neq {α:Type} {β:Type} {lt:α → α → Prop} [Hdec:decidable_rel lt] (m:rbmap α β lt) (k:α) (x:β) : forall a, cmp_using lt a k ≠ ordering.eq → rbmap.find (rbmap.insert m k x) a = rbmap.find m a := sorry namespace llvm. meta def llvm_type_tac := `[unfold has_well_founded.r measure inv_image sizeof has_sizeof.sizeof llvm_type.sizeof at *, try { linarith } ]. @[simp] def mentions : llvm_type → list ident | (llvm_type.prim_type _) := [] | (llvm_type.alias i) := [i] | (llvm_type.array _n tp) := mentions tp | (llvm_type.fun_ty ret args _va) := mentions ret ++ (list.join (sized.map_over args (λ x H, mentions x))) | (llvm_type.ptr_to _) := [] -- NB pointer types are explicitly excluded | (llvm_type.struct fs) := list.join (sized.map_over fs (λ x H, mentions x)) | (llvm_type.packed_struct fs) := list.join (sized.map_over fs (λ x H, mentions x)) | (llvm_type.vector _n tp) := mentions tp | (llvm_type.opaque) := [] using_well_founded ⟨λ _ _, `[exact ⟨measure sizeof, measure_wf _⟩] , llvm_type_tac⟩ . @[reducible,simp] def alias_rel (am:strmap llvm_type) (x y:ident) : Prop := ∃tp, am.find y.ident = some tp /\ x ∈ mentions tp. instance ident_eq_dec : decidable_rel (@eq ident) := begin unfold decidable_rel, intros a b, cases a, cases b, simp, apply_instance end @[reducible] def alias_map := { am:strmap llvm_type // (forall a, acc (alias_rel am) a) }. namespace alias_map. def all_mem_dec {α:Type} (p:α → Prop) (l:list α) : (∀x, x ∈ l → decidable (p x)) → decidable (∀x, x ∈ l → p x) := begin induction l, case list.nil { intros, unfold has_mem.mem list.mem, right; intros, trivial, }, case list.cons { intros, unfold has_mem.mem list.mem, intros, cases (a l_hd (or.inl rfl)), { left, intro, apply h, apply a_1, simp, }, { have Hsub : (Π (x : α), x ∈ l_tl → decidable (p x)), { intros; apply a, apply or.inr, assumption }, cases (l_ih Hsub), { left, intro, apply h_1, intros, apply a_1, apply or.inr, assumption }, { right, intros, cases a_1, { subst x; assumption }, { apply h_1; assumption } } } } end def ex_mem_dec {α:Type} (p:α → Prop) (l:list α) : (∀x, x ∈ l → decidable (p x)) → decidable (∃x, x ∈ l ∧ p x) := begin induction l, case list.nil { intros, unfold has_mem.mem list.mem, left, intro H, cases H, cases H_h, trivial }, case list.cons { intros, unfold has_mem.mem list.mem, intros, cases (a l_hd (or.inl rfl)), { have Hsub : (Π (x : α), x ∈ l_tl → decidable (p x)), { intros; apply a, apply or.inr, assumption }, cases (l_ih Hsub), { left, intro H, cases H, cases H_h, cases H_h_left, { apply h; cc }, { apply h_1, existsi H_w, cc } }, { right, cases h_1, existsi h_1_w, cases h_1_h, split, apply or.inr, assumption, assumption, } }, { right, existsi l_hd, split; try {assumption}, left, refl, } } end. def reachable_dec (am:strmap llvm_type) : forall x y (Hacc : acc (alias_rel am) y), decidable (tc (alias_rel am) x y) := begin intros x y Hacc, apply Hacc.rec_on, clear Hacc y, intros y _ IH, destruct (am.find y.ident), { intros Hy, left, intro Htc, revert Hy, clear IH, induction Htc, { intros, cases Htc_a_1, cc, }, { intros, cc } }, intros tp Htp, have H : decidable (∃i, i ∈ mentions tp ∧ (i = x ∨ tc (alias_rel am) x i)), { apply ex_mem_dec, intros i Hi, cases (llvm.ident_eq_dec i x), { have Hi : alias_rel am i y, { existsi tp, split; assumption }, cases (IH i Hi), { left, intro H, cases H; cc }, { right, right, assumption } }, { right, left, assumption }, }, cases H, { left, intro, clear h IH, apply H, clear H, induction a; intros, unfold alias_rel at a_a_1, cases a_a_1 with tp' Ha, cases Ha with Ha1 Ha2, have Heq : tp = tp', { cc }, subst tp', existsi a_a, split, apply Ha2, simp, cases (a_ih_a_1 Htp), cases h, cases h_right, subst a_b, existsi w, split, assumption, right, assumption, existsi w, split, assumption, right, apply tc.trans _ a_b _; assumption, }, { right, cases H with i H, cases H with H1 H2, cases H2 with H2 H2, subst i, apply tc.base, existsi tp, split; assumption, apply tc.trans _ i _, assumption, apply tc.base, existsi tp, split; assumption } end. lemma string_cmp_using_eq (x y : string) : cmp_using string.has_lt'.lt x y = ordering.eq → x = y := begin unfold cmp_using ite, cases (string.decidable_lt y x); simp, cases (string.decidable_lt x y); simp, apply le_antisymm; assumption, cases (string.decidable_lt x y); simp, end. lemma insert_alias_map_wf_aux (am:strmap llvm_type) (x z:ident) (tp:llvm_type) (Hacc: acc (alias_rel am) z) : forall (Hxy : z ≠ x) (Hntc: ¬(tc (alias_rel am) x z)), acc (alias_rel (rbmap.insert am x.ident tp)) z := begin apply Hacc.rec_on, clear Hacc z, intros z h IH Hx Htc, apply acc.intro, intros q Hq, cases Hq with tp Htp, cases Htp with Htp1 Htp2, rewrite (rbmap_insert_lookup_neq am) at Htp1, { apply IH, { existsi tp, cc }, { intro Hqx, apply Htc, apply tc.base, subst q, existsi tp, cc }, { intro Hxq, apply Htc, apply tc.trans _ q _, assumption, apply tc.base, existsi tp, cc, } }, { intro, apply Hx, cases z, cases x, unfold ident.ident at a, have Hzx : z = x, { apply string_cmp_using_eq, assumption }, cc } end lemma insert_alias_map_wf (am:strmap llvm_type) (x:ident) (tp:llvm_type) (Hacc: forall a, acc (alias_rel am) a) (Hnacc : ¬∃y, y ∈ mentions tp ∧ (y = x ∨ tc (alias_rel am) x y)) : forall a, acc (alias_rel (rbmap.insert am x.ident tp)) a := begin intro a, apply (Hacc a).rec_on, clear a, intros a h IH, clear h, apply acc.intro, intros q Hq, cases Hq with tp' Htp, cases Htp with Htp1 Htp2, apply (@decidable.by_cases (cmp_using string.has_lt'.lt a.ident x.ident = ordering.eq)); intro Heq, { rewrite (rbmap_insert_lookup_eq am x.ident tp) at Htp1; try {assumption}, injection Htp1, subst tp', clear Htp1, apply (insert_alias_map_wf_aux am x q tp (Hacc q)), { intro; subst q, apply Hnacc, existsi x, cc, }, { intro, apply Hnacc, existsi q, cc, } }, { rewrite (rbmap_insert_lookup_neq am x.ident tp) at Htp1; try {assumption}, apply (IH q), existsi tp', split; assumption } end. def empty : alias_map := subtype.mk (strmap_empty _) begin intro a, apply acc.intro, intros b H, destruct H, simp, unfold strmap_empty, unfold rbmap.find rbmap.find_entry rbmap.from_list, unfold mk_rbmap mk_rbtree, simp, unfold rbmap.find_entry._match_1 rbmap.to_value, intros, cc, end . def insert_check_dec (am:alias_map) (x:ident) (tp:llvm_type) : decidable (∃y, y ∈ mentions tp ∧ (y = x ∨ tc (alias_rel am.val) x y)) := begin apply ex_mem_dec, intros q Hq, cases (llvm.ident_eq_dec q x), { cases (reachable_dec am.val x q (am.property q)), { left, intro H; cases H; cc }, { right, right, assumption } }, { right, left, assumption } end. def insert (am:alias_map) (k:ident) (tp:llvm_type) : option alias_map := match insert_check_dec am k tp with | decidable.is_true _ := none | decidable.is_false H := some ⟨rbmap.insert am.val k.ident tp, insert_alias_map_wf am.val k tp am.property H⟩ end def build : list type_decl → alias_map → sum type_decl alias_map | [] am := sum.inr am | (td::tds) am := match insert am td.name td.value with | none := sum.inl td | some am' := build tds am' end. end alias_map. end llvm.
5f37dc695df2ebd50b7dc6205c592a59d4cd3f22
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/omega/int/preterm.lean
1f86ddf74e3f81ed375a589c8d3f86964b18f34c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,799
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Linear integer arithmetic terms in pre-normalized form. -/ import tactic.omega.term namespace omega namespace int /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `-5` is reified to `cst -5`) and all other atomic terms are reified to `exp` (e.g., `-5 * (gcd 14 -7)` is reified to `exp -5 \`(gcd 14 -7)`). `exp` accepts a coefficient of type `int` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : int → exprterm | exp : int → expr → exprterm | add : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive inhabited] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm localized "notation `&` k := omega.int.preterm.cst k" in omega.int localized "infix ` ** ` : 300 := omega.int.preterm.var" in omega.int localized "notation t `+*` s := omega.int.preterm.add t s" in omega.int namespace preterm /-- Preterm evaluation -/ @[simp] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index @[simp] def add_one (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& i) := ⟨i, []⟩ | (i ** n) := ⟨0, [] {n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[simp] lemma val_canonize {v : nat → int} : ∀ {t : preterm}, (canonize t).val v = t.val v | (& i) := by simp only [preterm.val, add_zero, term.val, canonize, coeffs.val_nil] | (i ** n) := begin simp only [coeffs.val_set, canonize, preterm.val, zero_add, term.val], split_ifs with h1 h2, { simp only [one_mul, h1] }, { simp only [neg_mul, one_mul, h2] }, { rw mul_comm } end | (t +* s) := by simp only [canonize, val_canonize, term.val_add, preterm.val] end int end omega
1d2f15f26e8dbc08e0fdfa98a0410ad49d823641
750acab0c635b67751bcfec43c5411aa3941c441
/em.lean
c8b6082c51f9c79fb4e6996318da4c17539d7c04
[]
no_license
nthomas103/lean_work
912f8e662cdd73ba97f5d3655ddb8a5d2cd204c9
7e9785cae2b60a77b41922fd5d5b159a1fae415c
refs/heads/master
1,586,739,169,355
1,455,759,226,000
1,455,759,226,000
50,978,095
0
0
null
null
null
null
UTF-8
Lean
false
false
5,501
lean
import standard data.matrix theories.group_theory.perm import theories.group_theory.hom algebra.module open nat fin real matrix matrix.ops list group_theory finset int open algebra section fn_module variables {R S : Type} variable [field R] definition fn_add (f g : S → R) (x : S) := f x + g x definition fn_mul (a : R) (f : S → R) (x : S) := a * f x definition fn_zero (x : S) : R := 0 definition fn_neg (f : S → R) (x : S) := - f x proposition fn_add_assoc (f g h : S → R) : (fn_add (fn_add f g) h) = (fn_add f (fn_add g h)) := sorry proposition fn_zero_add (f : S → R) : fn_add fn_zero f = f := sorry proposition fn_add_zero (f : S → R) : fn_add f fn_zero = f := sorry proposition fn_add_left_inv (f : S → R) : fn_add (fn_neg f) f = fn_zero := sorry proposition fn_add_comm (f g : S → R) : fn_add f g = fn_add g f := sorry proposition fn_smul_left_distrib : ∀ (a : R) (f g : S → R), fn_mul a (fn_add f g) = (fn_add (fn_mul a f) (fn_mul a g)) := sorry proposition fn_smul_right_distrib : ∀ (a b : R) (f : S → R), fn_mul (a + b) f = fn_add (fn_mul a f) (fn_mul b f) := sorry proposition fn_smul_mul : ∀ (a b : R) (f : S → R), fn_mul (a * b) f = fn_mul a (fn_mul b f) := sorry proposition fn_one_smul : ∀ (f : S → R), fn_mul 1 f = f := sorry definition fn_module [instance] : vector_space R (S → R) := ⦃ vector_space, smul := fn_mul, add := fn_add, add_assoc := fn_add_assoc, zero := fn_zero, zero_add := fn_zero_add, add_zero := fn_add_zero, neg := fn_neg, add_left_inv := fn_add_left_inv, add_comm := fn_add_comm, smul_left_distrib := fn_smul_left_distrib, smul_right_distrib := fn_smul_right_distrib, mul_smul := fn_smul_mul, one_smul := fn_one_smul ⦄ end fn_module definition vector [reducible] (T : Type) (n : ℕ) := fin n → T definition vc [reducible] (n : ℕ) := vector ℝ n definition mx [reducible] (m n : ℕ) := matrix ℝ m n definition tn [reducible] (T : Type) (n m : ℕ) := (vector (fin n) m) → T postfix `ᵀ`:1500 := transpose definition skew_symm {n} {T : Type} [comm_ring T] (A : matrix T n n) := λ i j, A[i, j] = -A[j, i] constant A' : vector (vc 4 → ℝ) 4 constant partial_derivative {n} : vector ((vc n → ℝ) → (vc n → ℝ)) n notation `∂` := partial_derivative definition F' : matrix (vc 4 → ℝ) 4 4 := λ μ ν x, ∂ μ (A' ν) x - ∂ ν (A' μ) x constant j' : vector (vc 4 → ℝ) 4 constant π : ℝ constant homogeneous_maxwell' : ∀ μ ρ σ x, ∂ μ (F' ρ σ) x + ∂ ρ (F' σ μ) x + ∂ σ (F' μ ρ) x = 0 constant heterogeneous_maxwell' : ∀ ν x, (∑ μ ← upto 4, ∂ μ (F' μ ν) x) = - 4 * π * (j' ν) x lemma charge_conservation : ∀ x, (∑ μ ← upto 4, ∂ μ (j' μ) x) = 0 := sorry /-lemma deriv_comm : ∀ T μ ν x, (D μ) ((D ν) T) x = (D ν) ((D μ) T) x := sorry-/ --lemma F_skew : skew_symm F := sorry constant sgn {A : Type} [h : fintype A] (p : perm A) : ℤ constant sgn_range {A : Type} [h : fintype A] (p : perm A) : sgn p = 1 ∨ sgn p = -1 --constant sgn_hom {A : Type} [h : fintype A] : is_hom_class sgn definition vec_is_fintype [instance] {A : Type} {n} : fintype (vector A n) := sorry noncomputable definition symmetrize {n m : ℕ} (T : tn (vc n → ℝ) n m) : tn (vc n → ℝ) n m := λ v, (fact m)⁻¹ • ∑ σ ← all_perms, T (move_by v σ) noncomputable definition anti_symmetrize {n m : ℕ} (T : tn (vc n → ℝ) n m) : tn (vc n → ℝ) n m := λ v, (fact m)⁻¹ • ∑ σ ← all_perms, sgn σ • (T (move_by v σ)) definition vhead {A : Type} {n} (v : vector A (n+1)) : A := v (mk 0 !zero_lt_succ) definition vtail {A : Type} {n} (v : vector A (n+1)) : vector A n := λ i, v (mk (val i + 1) (add_lt_add_right (is_lt i) 1)) noncomputable definition d {n m : ℕ} (T : tn (vc n → ℝ) n m) : tn (vc n → ℝ) n (m+1) := anti_symmetrize (λ v, ∂ (vhead v) (T (vtail v))) theorem d2_0 [simp] {n m} {T : tn _ n m} {μ x} : d (d T) μ x = 0 := sorry constant A : tn (vc 4 → ℝ) 4 1 noncomputable definition F := d A attribute [reducible] F definition vc_add [instance] {n m} : has_add (tn (vc n → ℝ) n m) := sorry lemma d_additive [simp] {n m} (B C : tn (vc n → ℝ) n m) {μ x} : d (B + C) μ x = (d B) μ x + (d C) μ x := sorry /-lemma d_homog {n m} (a : ℝ) (B : tn (vc n → ℝ) n m) : d (a * B) = a * (d B) := sorry-/ lemma gauge_transform {m} (A : tn (vc 4 → ℝ) 4 (m+1)) (f : tn (vc 4 → ℝ) 4 m) {μ x} : d (A + d f) μ x = d A μ x := calc d (A + d f) μ x = d A μ x + d (d f) μ x : d_additive ... = d A μ x + 0 : {d2_0} ... = d A μ x : by simp theorem homogeneous_maxwell {μ x} : (d F) μ x = 0 := by inst_simp --constant ε {n} {μ : vector (fin n) n} : ℤ definition hodge (T : tn (vc 4 → ℝ) 4 2) : tn (vc 4 → ℝ) 4 2 := sorry prefix `⋆`:2000 := hodge constant J : tn (vc 4 → ℝ) 4 3 constant heterogeneous_maxwell : J = d ⋆ F theorem continuity_equation {μ x} : (d J) μ x = 0 := calc (d J) μ x = d (d ⋆ F) μ x : {heterogeneous_maxwell} ... = 0 : d2_0
1b9530d7e6b16954b03f5cd07526409fb21110cb
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Data/Json/FromToJson.lean
2461a3852672b395229ba660ec36bf121d29ea10
[ "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
2,058
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic namespace Lean universes u class FromJson (α : Type u) where fromJson? : Json → Option α export FromJson (fromJson?) class ToJson (α : Type u) where toJson : α → Json export ToJson (toJson) instance : FromJson Json := ⟨some⟩ instance : ToJson Json := ⟨id⟩ instance : FromJson JsonNumber := ⟨Json.getNum?⟩ instance : ToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance : FromJson Bool := ⟨Json.getBool?⟩ instance : ToJson Bool := ⟨fun b => b⟩ instance : FromJson Nat := ⟨Json.getNat?⟩ instance : ToJson Nat := ⟨fun n => n⟩ instance : FromJson Int := ⟨Json.getInt?⟩ instance : ToJson Int := ⟨fun n => Json.num n⟩ instance : FromJson String := ⟨Json.getStr?⟩ instance : ToJson String := ⟨fun s => s⟩ instance [FromJson α] : FromJson (Array α) where fromJson? | Json.arr a => OptionM.run <| a.mapM fromJson? | _ => none instance [ToJson α] : ToJson (Array α) := ⟨fun a => Json.arr (a.map toJson)⟩ instance [FromJson α] : FromJson (Option α) where fromJson? | Json.null => some none | j => some <$> fromJson? j instance [ToJson α] : ToJson (Option α) := ⟨fun | none => Json.null | some a => toJson a⟩ namespace Json instance : FromJson Structured := ⟨fun | arr a => Structured.arr a | obj o => Structured.obj o | _ => none⟩ instance : ToJson Structured := ⟨fun | Structured.arr a => arr a | Structured.obj o => obj o⟩ def toStructured? [ToJson α] (v : α) : Option Structured := fromJson? (toJson v) def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Option α := fromJson? <| j.getObjValD k def opt [ToJson α] (k : String) : Option α → List (String × Json) | none => [] | some o => [⟨k, toJson o⟩] end Json end Lean
224272ef8ab6b3d0e909f2c084d142b2bcd2b51e
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/special_functions/integrals.lean
1da7cd5e134e04fd20bb1561f685504f10e2ea2e
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,053
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import measure_theory.integral.interval_integral /-! # Integration of specific interval integrals This file contains proofs of the integrals of various specific functions. This includes: * Integrals of simple functions, such as `id`, `pow`, `inv`, `exp`, `log` * Integrals of some trigonometric functions, such as `sin`, `cos`, `1 / (1 + x^2)` * The integral of `cos x ^ 2 - sin x ^ 2` * Reduction formulae for the integrals of `sin x ^ n` and `cos x ^ n` for `n ≥ 2` * The computation of `∫ x in 0..π, sin x ^ n` as a product for even and odd `n` (used in proving the Wallis product for pi) * Integrals of the form `sin x ^ m * cos x ^ n` With these lemmas, many simple integrals can be computed by `simp` or `norm_num`. See `test/integration.lean` for specific examples. This file also contains some facts about the interval integrability of specific functions. This file is still being developed. ## Tags integrate, integration, integrable, integrability -/ open real nat set finset open_locale real big_operators variables {a b : ℝ} (n : ℕ) namespace interval_integral open measure_theory variables {f : ℝ → ℝ} {μ ν : measure ℝ} [is_locally_finite_measure μ] (c d : ℝ) /-! ### Interval integrability -/ @[simp] lemma interval_integrable_pow : interval_integrable (λ x, x^n) μ a b := (continuous_pow n).interval_integrable a b @[simp] lemma interval_integrable_id : interval_integrable (λ x, x) μ a b := continuous_id.interval_integrable a b @[simp] lemma interval_integrable_const : interval_integrable (λ x, c) μ a b := continuous_const.interval_integrable a b @[simp] lemma interval_integrable.const_mul (h : interval_integrable f ν a b) : interval_integrable (λ x, c * f x) ν a b := by convert h.smul c @[simp] lemma interval_integrable.mul_const (h : interval_integrable f ν a b) : interval_integrable (λ x, f x * c) ν a b := by simp only [mul_comm, interval_integrable.const_mul c h] @[simp] lemma interval_integrable.div (h : interval_integrable f ν a b) : interval_integrable (λ x, f x / c) ν a b := interval_integrable.mul_const c⁻¹ h lemma interval_integrable_one_div (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) (hf : continuous_on f (interval a b)) : interval_integrable (λ x, 1 / f x) μ a b := (continuous_on_const.div hf h).interval_integrable @[simp] lemma interval_integrable_inv (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) (hf : continuous_on f (interval a b)) : interval_integrable (λ x, (f x)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div h hf @[simp] lemma interval_integrable_exp : interval_integrable exp μ a b := continuous_exp.interval_integrable a b @[simp] lemma interval_integrable.log (hf : continuous_on f (interval a b)) (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) : interval_integrable (λ x, log (f x)) μ a b := (continuous_on.log hf h).interval_integrable @[simp] lemma interval_integrable_log (h : (0:ℝ) ∉ interval a b) : interval_integrable log μ a b := interval_integrable.log continuous_on_id $ λ x hx, ne_of_mem_of_not_mem hx h @[simp] lemma interval_integrable_sin : interval_integrable sin μ a b := continuous_sin.interval_integrable a b @[simp] lemma interval_integrable_cos : interval_integrable cos μ a b := continuous_cos.interval_integrable a b lemma interval_integrable_one_div_one_add_sq : interval_integrable (λ x : ℝ, 1 / (1 + x^2)) μ a b := begin refine (continuous_const.div _ (λ x, _)).interval_integrable a b, { continuity }, { nlinarith }, end @[simp] lemma interval_integrable_inv_one_add_sq : interval_integrable (λ x : ℝ, (1 + x^2)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div_one_add_sq /-! ### Integral of a function scaled by a constant -/ @[simp] lemma integral_const_mul : ∫ x in a..b, c * f x = c * ∫ x in a..b, f x := integral_smul c @[simp] lemma integral_mul_const : ∫ x in a..b, f x * c = (∫ x in a..b, f x) * c := by simp only [mul_comm, integral_const_mul] @[simp] lemma integral_div : ∫ x in a..b, f x / c = (∫ x in a..b, f x) / c := integral_mul_const c⁻¹ /-! ### Integrals of the form `c * ∫ x in a..b, f (c * x + d)` -/ @[simp] lemma mul_integral_comp_mul_right : c * ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := smul_integral_comp_mul_right f c @[simp] lemma mul_integral_comp_mul_left : c * ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := smul_integral_comp_mul_left f c @[simp] lemma inv_mul_integral_comp_div : c⁻¹ * ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := inv_smul_integral_comp_div f c @[simp] lemma mul_integral_comp_mul_add : c * ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := smul_integral_comp_mul_add f c d @[simp] lemma mul_integral_comp_add_mul : c * ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := smul_integral_comp_add_mul f c d @[simp] lemma inv_mul_integral_comp_div_add : c⁻¹ * ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := inv_smul_integral_comp_div_add f c d @[simp] lemma inv_mul_integral_comp_add_div : c⁻¹ * ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := inv_smul_integral_comp_add_div f c d @[simp] lemma mul_integral_comp_mul_sub : c * ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := smul_integral_comp_mul_sub f c d @[simp] lemma mul_integral_comp_sub_mul : c * ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := smul_integral_comp_sub_mul f c d @[simp] lemma inv_mul_integral_comp_div_sub : c⁻¹ * ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := inv_smul_integral_comp_div_sub f c d @[simp] lemma inv_mul_integral_comp_sub_div : c⁻¹ * ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := inv_smul_integral_comp_sub_div f c d end interval_integral open interval_integral /-! ### Integrals of simple functions -/ @[simp] lemma integral_pow : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) := begin have hderiv : deriv (λ x : ℝ, x ^ (n + 1) / (n + 1)) = λ x, x ^ n, { ext, have hne : (n + 1 : ℝ) ≠ 0 := by exact_mod_cast succ_ne_zero n, simp [mul_div_assoc, mul_div_cancel' _ hne] }, rw integral_deriv_eq_sub' _ hderiv; norm_num [div_sub_div_same, continuous_on_pow], end @[simp] lemma integral_id : ∫ x in a..b, x = (b ^ 2 - a ^ 2) / 2 := by simpa using integral_pow 1 @[simp] lemma integral_one : ∫ x in a..b, (1 : ℝ) = b - a := by simp only [mul_one, smul_eq_mul, integral_const] @[simp] lemma integral_inv (h : (0:ℝ) ∉ interval a b) : ∫ x in a..b, x⁻¹ = log (b / a) := begin have h' := λ x hx, ne_of_mem_of_not_mem hx h, rw [integral_deriv_eq_sub' _ deriv_log' (λ x hx, differentiable_at_log (h' x hx)) (continuous_on_inv'.mono $ subset_compl_singleton_iff.mpr h), log_div (h' b right_mem_interval) (h' a left_mem_interval)], end @[simp] lemma integral_inv_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_lt ha hb @[simp] lemma integral_inv_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_gt ha hb lemma integral_one_div (h : (0:ℝ) ∉ interval a b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv h] lemma integral_one_div_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_pos ha hb] lemma integral_one_div_of_neg (ha : a < 0) (hb : b < 0) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_neg ha hb] @[simp] lemma integral_exp : ∫ x in a..b, exp x = exp b - exp a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_exp] @[simp] lemma integral_log (h : (0:ℝ) ∉ interval a b) : ∫ x in a..b, log x = b * log b - a * log a - b + a := begin obtain ⟨h', heq⟩ := ⟨λ x hx, ne_of_mem_of_not_mem hx h, λ x hx, mul_inv_cancel (h' x hx)⟩, convert integral_mul_deriv_eq_deriv_mul (λ x hx, has_deriv_at_log (h' x hx)) (λ x hx, has_deriv_at_id x) (continuous_on_inv'.mono $ subset_compl_singleton_iff.mpr h).interval_integrable continuous_on_const.interval_integrable using 1; simp [integral_congr heq, mul_comm, ← sub_add], end @[simp] lemma integral_log_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_lt ha hb @[simp] lemma integral_log_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_gt ha hb @[simp] lemma integral_sin : ∫ x in a..b, sin x = cos a - cos b := by rw integral_deriv_eq_sub' (λ x, -cos x); norm_num [continuous_on_sin] @[simp] lemma integral_cos : ∫ x in a..b, cos x = sin b - sin a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_cos] lemma integral_cos_sq_sub_sin_sq : ∫ x in a..b, cos x ^ 2 - sin x ^ 2 = sin b * cos b - sin a * cos a := by simpa only [sq, sub_eq_add_neg, neg_mul_eq_mul_neg] using integral_deriv_mul_eq_sub (λ x hx, has_deriv_at_sin x) (λ x hx, has_deriv_at_cos x) continuous_on_cos.interval_integrable continuous_on_sin.neg.interval_integrable @[simp] lemma integral_inv_one_add_sq : ∫ x : ℝ in a..b, (1 + x^2)⁻¹ = arctan b - arctan a := begin simp only [← one_div], refine integral_deriv_eq_sub' _ _ _ (continuous_const.div _ (λ x, _)).continuous_on, { norm_num }, { norm_num }, { continuity }, { nlinarith }, end lemma integral_one_div_one_add_sq : ∫ x : ℝ in a..b, 1 / (1 + x^2) = arctan b - arctan a := by simp only [one_div, integral_inv_one_add_sq] /-! ### Integral of `sin x ^ n` -/ lemma integral_sin_pow_aux : ∫ x in a..b, sin x ^ (n + 2) = sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) := begin let C := sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, sin y ^ (n + 1)) ((n + 1) * cos x * sin x ^ n) x := λ x hx, by simpa [mul_right_comm] using (has_deriv_at_sin x).pow, have hv : ∀ x ∈ interval a b, has_deriv_at (-cos) (sin x) x := λ x hx, by simpa only [neg_neg] using (has_deriv_at_cos x).neg, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, sin x ^ (n + 2) = ∫ x in a..b, sin x ^ (n + 1) * sin x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, cos x ^ 2 * sin x ^ n : by simp [H, h, sq] ... = C + (n + 1) * ∫ x in a..b, sin x ^ n - sin x ^ (n + 2) : by simp [cos_sq', sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `sin x ^ n` for any natural `n ≥ 2`. -/ lemma integral_sin_pow : ∫ x in a..b, sin x ^ (n + 2) = (sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, sin x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_sin_pow_aux n), ring, end @[simp] lemma integral_sin_sq : ∫ x in a..b, sin x ^ 2 = (sin a * cos a - sin b * cos b + b - a) / 2 := by field_simp [integral_sin_pow, add_sub_assoc] theorem integral_sin_pow_odd : ∫ x in 0..π, sin x ^ (2 * n + 1) = 2 * ∏ i in range n, (2 * i + 2) / (2 * i + 3) := begin induction n with k ih, { norm_num }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end theorem integral_sin_pow_even : ∫ x in 0..π, sin x ^ (2 * n) = π * ∏ i in range n, (2 * i + 1) / (2 * i + 2) := begin induction n with k ih, { simp }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end lemma integral_sin_pow_pos : 0 < ∫ x in 0..π, sin x ^ n := begin rcases even_or_odd' n with ⟨k, (rfl | rfl)⟩; simp only [integral_sin_pow_even, integral_sin_pow_odd]; refine mul_pos (by norm_num [pi_pos]) (prod_pos (λ n hn, div_pos _ _)); norm_cast; linarith, end lemma integral_sin_pow_antimono : ∫ x in 0..π, sin x ^ (n + 1) ≤ ∫ x in 0..π, sin x ^ n := let H := λ x h, pow_le_pow_of_le_one (sin_nonneg_of_mem_Icc h) (sin_le_one x) (n.le_add_right 1) in by refine integral_mono_on pi_pos.le _ _ H; exact (continuous_sin.pow _).interval_integrable 0 π /-! ### Integral of `cos x ^ n` -/ lemma integral_cos_pow_aux : ∫ x in a..b, cos x ^ (n + 2) = cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) := begin let C := cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, cos y ^ (n + 1)) (-(n + 1) * sin x * cos x ^ n) x := λ x hx, by simpa [mul_right_comm, -neg_add_rev] using (has_deriv_at_cos x).pow, have hv : ∀ x ∈ interval a b, has_deriv_at sin (cos x) x := λ x hx, has_deriv_at_sin x, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, cos x ^ (n + 2) = ∫ x in a..b, cos x ^ (n + 1) * cos x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, sin x ^ 2 * cos x ^ n : by simp [H, h, sq, -neg_add_rev] ... = C + (n + 1) * ∫ x in a..b, cos x ^ n - cos x ^ (n + 2) : by simp [sin_sq, sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `cos x ^ n` for any natural `n ≥ 2`. -/ lemma integral_cos_pow : ∫ x in a..b, cos x ^ (n + 2) = (cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, cos x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_cos_pow_aux n), ring, end @[simp] lemma integral_cos_sq : ∫ x in a..b, cos x ^ 2 = (cos b * sin b - cos a * sin a + b - a) / 2 := by field_simp [integral_cos_pow, add_sub_assoc] /-! ### Integral of `sin x ^ m * cos x ^ n` -/ /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `n` is odd. -/ lemma integral_sin_pow_mul_cos_pow_odd (m n : ℕ) : ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n := have hc : continuous (λ u : ℝ, u ^ m * (1 - u ^ 2) ^ n), by continuity, calc ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ x in a..b, sin x ^ m * (1 - sin x ^ 2) ^ n * cos x : by simp only [pow_succ', ← mul_assoc, pow_mul, cos_sq'] ... = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n : integral_comp_mul_deriv (λ x hx, has_deriv_at_sin x) continuous_on_cos hc /-- The integral of `sin x * cos x`, given in terms of sin². See `integral_sin_mul_cos₂` below for the integral given in terms of cos². -/ @[simp] lemma integral_sin_mul_cos₁ : ∫ x in a..b, sin x * cos x = (sin b ^ 2 - sin a ^ 2) / 2 := by simpa using integral_sin_pow_mul_cos_pow_odd 1 0 @[simp] lemma integral_sin_sq_mul_cos : ∫ x in a..b, sin x ^ 2 * cos x = (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 2 0 @[simp] lemma integral_cos_pow_three : ∫ x in a..b, cos x ^ 3 = sin b - sin a - (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 0 1 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` is odd. -/ lemma integral_sin_pow_odd_mul_cos_pow (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m := have hc : continuous (λ u : ℝ, u ^ n * (1 - u ^ 2) ^ m), by continuity, calc ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = -∫ x in b..a, sin x ^ (2 * m + 1) * cos x ^ n : by rw integral_symm ... = ∫ x in b..a, (1 - cos x ^ 2) ^ m * -sin x * cos x ^ n : by simp [pow_succ', pow_mul, sin_sq] ... = ∫ x in b..a, cos x ^ n * (1 - cos x ^ 2) ^ m * -sin x : by { congr, ext, ring } ... = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m : integral_comp_mul_deriv (λ x hx, has_deriv_at_cos x) continuous_on_sin.neg hc /-- The integral of `sin x * cos x`, given in terms of cos². See `integral_sin_mul_cos₁` above for the integral given in terms of sin². -/ lemma integral_sin_mul_cos₂ : ∫ x in a..b, sin x * cos x = (cos a ^ 2 - cos b ^ 2) / 2 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 1 @[simp] lemma integral_sin_mul_cos_sq : ∫ x in a..b, sin x * cos x ^ 2 = (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 2 @[simp] lemma integral_sin_pow_three : ∫ x in a..b, sin x ^ 3 = cos a - cos b - (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 1 0 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` and `n` are both even. -/ lemma integral_sin_pow_even_mul_cos_pow_even (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m) * cos x ^ (2 * n) = ∫ x in a..b, ((1 - cos (2 * x)) / 2) ^ m * ((1 + cos (2 * x)) / 2) ^ n := by field_simp [pow_mul, sin_sq, cos_sq, ← sub_sub, (by ring : (2:ℝ) - 1 = 1)] @[simp] lemma integral_sin_sq_mul_cos_sq : ∫ x in a..b, sin x ^ 2 * cos x ^ 2 = (b - a) / 8 - (sin (4 * b) - sin (4 * a)) / 32 := begin convert integral_sin_pow_even_mul_cos_pow_even 1 1 using 1, have h1 : ∀ c : ℝ, (1 - c) / 2 * ((1 + c) / 2) = (1 - c ^ 2) / 4 := λ c, by ring, have h2 : continuous (λ x, cos (2 * x) ^ 2) := by continuity, have h3 : ∀ x, cos x * sin x = sin (2 * x) / 2, { intro, rw sin_two_mul, ring }, have h4 : ∀ d : ℝ, 2 * (2 * d) = 4 * d := λ d, by ring, simp [h1, h2.interval_integrable, integral_comp_mul_left (λ x, cos x ^ 2), h3, h4], ring, end
a223d53deb65f19d4c522a4d29ac7db7038f0c6f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/lex.lean
6b8d9eb1439d75d151555f6f2cf6eedf9a4a8305
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,807
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import order.rel_classes /-! # Lexicographic ordering of lists. The lexicographic order on `list α` is defined by `L < M` iff * `[] < (a :: L)` for any `a` and `L`, * `(a :: L) < (b :: M)` where `a < b`, or * `(a :: L) < (a :: M)` where `L < M`. ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.psigma.order`: Lexicographic order on `Σ' i, α i`. * `data.pi.lex`: Lexicographic order on `Πₗ i, α i`. * `data.sigma.order`: Lexicographic order on `Σ i, α i`. * `data.prod.lex`: Lexicographic order on `α × β`. -/ namespace list open nat universes u variables {α : Type u} /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order α r] : is_strict_total_order (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem _root_.decidable.list.lex.ne_iff [decidable_eq α] {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { by_cases ab : a = b, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := by classical; exact decidable.list.lex.ne_iff H end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ end list
143de0d40de13a63898b2c7a8d18ae132bcc75cf
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/rewrite12.lean
043bf30d450d8a5eedc306aefc22ad233e65a6ad
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
313
lean
import data.nat open nat variables (f : nat → nat → nat → nat) (a b c : nat) example (H₁ : a = b) (H₂ : f b a b = 0) : f a a a = 0 := by rewrite ⟨H₁ at -{2}, H₂⟩ example (H₁ : a = b) (H₂ : f b a b = 0) (H₃ : c = f a a a) : c = 0 := by rewrite ⟨H₁ at H₃ -{2}, H₂ at H₃, H₃⟩
0bf17ca8788c08a59738cffe3bee346e5f24d3c8
a8c03ed21a1bd6fc45901943b79dd6574ea3f0c2
/inhabited.lean
11a01929c7525546bbd3ef43f33fdedd998eeb6b
[]
no_license
gebner/resolution.lean
716c355fbb5204e5c4d0c5a7f3f3cc825892a2bf
c6fafe06fba1cfad73db68f2aa474b29fe892a2b
refs/heads/master
1,601,111,444,528
1,475,256,701,000
1,475,256,701,000
67,711,151
0
0
null
null
null
null
UTF-8
Lean
false
false
2,075
lean
import clause_ops prover_state open expr tactic monad meta def nonempty_lookup_left (c : clause) : tactic (list clause) := collect_successes $ do l ← c↣get_lits, guard l↣is_neg, return $ do type ← return l↣formula, guard ¬type↣has_var, univ ← infer_univ type, inst ← mk_instance (app (const ``nonempty [univ]) type), clause.of_proof inst meta def try_nonempty_left (c : clause) : tactic (list clause) := on_first_left c $ λprop, match prop with | (app (const ``nonempty [u]) type) := do x ← mk_local_def `x type, return [([x], app_of_list (const ``nonempty.intro [u]) [type, x])] | _ := failed end meta def try_nonempty_right (c : clause) : tactic (list clause) := on_first_right c $ λhnonempty, match hnonempty↣local_type with | (app (const ``nonempty [u]) type) := do hnx ← mk_local_def `nx (imp type false_), return [([hnx], app_of_list (const ``nonempty.elim [u]) [type, false_, hnonempty, hnx])] | _ := failed end meta def try_inhabited_left (c : clause) : tactic (list clause) := on_first_left c $ λprop, match prop with | (app (const ``inhabited [u]) type) := do x ← mk_local_def `x type, return [([x], app_of_list (const ``inhabited.mk [u]) [type, x])] | _ := failed end meta def try_inhabited_right (c : clause) : tactic (list clause) := on_first_right' c $ λhinh, match hinh↣local_type with | (app (const ``inhabited [u]) type) := return [([], app_of_list (const ``inhabited.default [u]) [type, hinh])] | _ := failed end meta def simp_if_successful (parent : active_cls) (tac : tactic (list clause)) : resolution_prover unit := (do inferred ← ↑tac, forM' inferred $ λc, add_inferred c [parent], remove_redundant parent↣id []) <|> return () meta def inhabited_infs : inference := take given, do insts ← ↑(nonempty_lookup_left given↣c), forM' insts (λc, add_inferred c []), forM' [try_nonempty_left, try_nonempty_right, try_inhabited_left, try_inhabited_right] $ λr, simp_if_successful given (r given↣c)
18b51d446a02090b4c6bab9b2045fe3e0c84b228
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/using_smt1.lean
d66cfce35b10ae9712af2f026eedc5259f8041cf
[ "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
1,285
lean
open smt_tactic tactic lemma ex1 (a b c : nat) : a = c → a = b → b = c := by using_smt intros set_option pp.all true lemma ex2 (a b c : nat) : a > nat.zero → a = c → a = b → b = c := by using_smt intros lemma ex3 (p q r : Prop) : p → q → ¬p → r := by using_smt intros lemma ex4 (a b c : nat) : a > nat.zero → 0 < a := by simp [(>)]; using_smt intros lemma ex5 (a b c d : nat) : a ≠ d → a = b ∧ b = c → a = c := by using_smt intros set_option pp.all false lemma ex6 (f : nat → nat) (a b c : nat) : f a = 0 → f b = 1 → f a = f b ∨ f a = c → c = 0 := by using_smt intros lemma ex7 (f : nat → nat) (a b c d e: nat) : f a = 0 → f a = d → f b = e → f b = 1 → d = e ∨ f a = c → c = 0 := by using_smt intros lemma ex8 (f : bool → bool) (a b c : bool) : f a = ff → f b = tt → f a = f b ∨ f a = c → c = ff := by using_smt intros lemma ex9 (f : list nat → list nat) (a b c : list nat) : f a = [] → f b = [0, 1] → f a = f b ∨ f a = c → c = [] := by using_smt intros lemma ex10 (a b c d e : int) : a = b → b ≠ c → (a = c ∨ d = e) → d = e := by using_smt intros
74aea4f8ac83929bc188658c847faa399989efd7
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/InverseSig.lean
210ed63c81604f9bf0ed92b4834bdc4e4daf6bb9
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,373
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section InverseSig structure InverseSig (A : Type) : Type := (inv : (A → A)) (e : A) (op : (A → (A → A))) open InverseSig structure Sig (AS : Type) : Type := (invS : (AS → AS)) (eS : AS) (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (invP : ((Prod A A) → (Prod A A))) (eP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) structure Hom {A1 : Type} {A2 : Type} (In1 : (InverseSig A1)) (In2 : (InverseSig A2)) : Type := (hom : (A1 → A2)) (pres_inv : (∀ {x1 : A1} , (hom ((inv In1) x1)) = ((inv In2) (hom x1)))) (pres_e : (hom (e In1)) = (e In2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op In1) x1 x2)) = ((op In2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (In1 : (InverseSig A1)) (In2 : (InverseSig A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_inv : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((inv In1) x1) ((inv In2) y1))))) (interp_e : (interp (e In1) (e In2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op In1) x1 x2) ((op In2) y1 y2)))))) inductive InverseSigTerm : Type | invL : (InverseSigTerm → InverseSigTerm) | eL : InverseSigTerm | opL : (InverseSigTerm → (InverseSigTerm → InverseSigTerm)) open InverseSigTerm inductive ClInverseSigTerm (A : Type) : Type | sing : (A → ClInverseSigTerm) | invCl : (ClInverseSigTerm → ClInverseSigTerm) | eCl : ClInverseSigTerm | opCl : (ClInverseSigTerm → (ClInverseSigTerm → ClInverseSigTerm)) open ClInverseSigTerm inductive OpInverseSigTerm (n : ℕ) : Type | v : ((fin n) → OpInverseSigTerm) | invOL : (OpInverseSigTerm → OpInverseSigTerm) | eOL : OpInverseSigTerm | opOL : (OpInverseSigTerm → (OpInverseSigTerm → OpInverseSigTerm)) open OpInverseSigTerm inductive OpInverseSigTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpInverseSigTerm2) | sing2 : (A → OpInverseSigTerm2) | invOL2 : (OpInverseSigTerm2 → OpInverseSigTerm2) | eOL2 : OpInverseSigTerm2 | opOL2 : (OpInverseSigTerm2 → (OpInverseSigTerm2 → OpInverseSigTerm2)) open OpInverseSigTerm2 def simplifyCl {A : Type} : ((ClInverseSigTerm A) → (ClInverseSigTerm A)) | (invCl x1) := (invCl (simplifyCl x1)) | eCl := eCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpInverseSigTerm n) → (OpInverseSigTerm n)) | (invOL x1) := (invOL (simplifyOpB x1)) | eOL := eOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpInverseSigTerm2 n A) → (OpInverseSigTerm2 n A)) | (invOL2 x1) := (invOL2 (simplifyOp x1)) | eOL2 := eOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((InverseSig A) → (InverseSigTerm → A)) | In (invL x1) := ((inv In) (evalB In x1)) | In eL := (e In) | In (opL x1 x2) := ((op In) (evalB In x1) (evalB In x2)) def evalCl {A : Type} : ((InverseSig A) → ((ClInverseSigTerm A) → A)) | In (sing x1) := x1 | In (invCl x1) := ((inv In) (evalCl In x1)) | In eCl := (e In) | In (opCl x1 x2) := ((op In) (evalCl In x1) (evalCl In x2)) def evalOpB {A : Type} {n : ℕ} : ((InverseSig A) → ((vector A n) → ((OpInverseSigTerm n) → A))) | In vars (v x1) := (nth vars x1) | In vars (invOL x1) := ((inv In) (evalOpB In vars x1)) | In vars eOL := (e In) | In vars (opOL x1 x2) := ((op In) (evalOpB In vars x1) (evalOpB In vars x2)) def evalOp {A : Type} {n : ℕ} : ((InverseSig A) → ((vector A n) → ((OpInverseSigTerm2 n A) → A))) | In vars (v2 x1) := (nth vars x1) | In vars (sing2 x1) := x1 | In vars (invOL2 x1) := ((inv In) (evalOp In vars x1)) | In vars eOL2 := (e In) | In vars (opOL2 x1 x2) := ((op In) (evalOp In vars x1) (evalOp In vars x2)) def inductionB {P : (InverseSigTerm → Type)} : ((∀ (x1 : InverseSigTerm) , ((P x1) → (P (invL x1)))) → ((P eL) → ((∀ (x1 x2 : InverseSigTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : InverseSigTerm) , (P x))))) | pinvl pel popl (invL x1) := (pinvl _ (inductionB pinvl pel popl x1)) | pinvl pel popl eL := pel | pinvl pel popl (opL x1 x2) := (popl _ _ (inductionB pinvl pel popl x1) (inductionB pinvl pel popl x2)) def inductionCl {A : Type} {P : ((ClInverseSigTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 : (ClInverseSigTerm A)) , ((P x1) → (P (invCl x1)))) → ((P eCl) → ((∀ (x1 x2 : (ClInverseSigTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClInverseSigTerm A)) , (P x)))))) | psing pinvcl pecl popcl (sing x1) := (psing x1) | psing pinvcl pecl popcl (invCl x1) := (pinvcl _ (inductionCl psing pinvcl pecl popcl x1)) | psing pinvcl pecl popcl eCl := pecl | psing pinvcl pecl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pinvcl pecl popcl x1) (inductionCl psing pinvcl pecl popcl x2)) def inductionOpB {n : ℕ} {P : ((OpInverseSigTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 : (OpInverseSigTerm n)) , ((P x1) → (P (invOL x1)))) → ((P eOL) → ((∀ (x1 x2 : (OpInverseSigTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpInverseSigTerm n)) , (P x)))))) | pv pinvol peol popol (v x1) := (pv x1) | pv pinvol peol popol (invOL x1) := (pinvol _ (inductionOpB pv pinvol peol popol x1)) | pv pinvol peol popol eOL := peol | pv pinvol peol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv pinvol peol popol x1) (inductionOpB pv pinvol peol popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpInverseSigTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 : (OpInverseSigTerm2 n A)) , ((P x1) → (P (invOL2 x1)))) → ((P eOL2) → ((∀ (x1 x2 : (OpInverseSigTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpInverseSigTerm2 n A)) , (P x))))))) | pv2 psing2 pinvol2 peol2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 pinvol2 peol2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pinvol2 peol2 popol2 (invOL2 x1) := (pinvol2 _ (inductionOp pv2 psing2 pinvol2 peol2 popol2 x1)) | pv2 psing2 pinvol2 peol2 popol2 eOL2 := peol2 | pv2 psing2 pinvol2 peol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 pinvol2 peol2 popol2 x1) (inductionOp pv2 psing2 pinvol2 peol2 popol2 x2)) def stageB : (InverseSigTerm → (Staged InverseSigTerm)) | (invL x1) := (stage1 invL (codeLift1 invL) (stageB x1)) | eL := (Now eL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClInverseSigTerm A) → (Staged (ClInverseSigTerm A))) | (sing x1) := (Now (sing x1)) | (invCl x1) := (stage1 invCl (codeLift1 invCl) (stageCl x1)) | eCl := (Now eCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpInverseSigTerm n) → (Staged (OpInverseSigTerm n))) | (v x1) := (const (code (v x1))) | (invOL x1) := (stage1 invOL (codeLift1 invOL) (stageOpB x1)) | eOL := (Now eOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpInverseSigTerm2 n A) → (Staged (OpInverseSigTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (invOL2 x1) := (stage1 invOL2 (codeLift1 invOL2) (stageOp x1)) | eOL2 := (Now eOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (invT : ((Repr A) → (Repr A))) (eT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) end InverseSig
9d040de3b4993e4bc1870df679937e02547bfe7d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/mut_ind_wf.lean
fb01c71a8fa228a49825c9544043baad4d3b3de3
[ "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,974
lean
namespace Mutual mutual inductive Tree (α : Type u) where | node : TreeList α → Tree α | leaf : α → Tree α inductive TreeList (α : Type u) where | nil : TreeList α | cons : Tree α → TreeList α → TreeList α end mutual def Tree.size : Tree α → Nat | Tree.node l => -- see "TODO: linarith" in Init.WFTactics have : sizeOf l < 1 + sizeOf l := by rw [Nat.add_comm] apply Nat.lt_succ_self sizeList l | Tree.leaf _ => 1 def Tree.sizeList : TreeList α → Nat | TreeList.nil => 0 | TreeList.cons t l => have : sizeOf t < 1 + sizeOf t + sizeOf l := by rw [Nat.add_comm 1, Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] apply Nat.lt_succ_of_le apply Nat.le_add_right have : sizeOf l < 1 + sizeOf t + sizeOf l := by rw [Nat.add_comm 1, Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] apply Nat.lt_succ_of_le apply Nat.le_add_left t.size + sizeList l end -- use automatically synthesized size function, which is not quite the number of leaves termination_by size t => sizeOf t sizeList l => sizeOf l end Mutual namespace Nested inductive Tree (α : Type u) where | node : List (Tree α) → Tree α | leaf : α → Tree α mutual def Tree.size : Tree α → Nat | Tree.node l => have : sizeOf l < 1 + sizeOf l := by rw [Nat.add_comm] apply Nat.lt_succ_self sizeList l | Tree.leaf _ => 1 def Tree.sizeList : List (Tree α) → Nat | [] => 0 | t :: l => have : sizeOf t < 1 + sizeOf t + sizeOf l := by rw [Nat.add_comm 1, Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] apply Nat.lt_succ_of_le apply Nat.le_add_right have : sizeOf l < 1 + sizeOf t + sizeOf l := by rw [Nat.add_comm 1, Nat.add_assoc, Nat.add_comm 1, ← Nat.add_assoc] apply Nat.lt_succ_of_le apply Nat.le_add_left t.size + sizeList l end termination_by size t => sizeOf t sizeList l => sizeOf l end Nested
b120d3215d804e17ec931d5a6ebbebb9a9e96b0f
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/measure_theory/constructions/prod.lean
18bcd3e810e5a6ca1cc2d7aea0f35c38a701d986
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,763
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.giry_monad import dynamics.ergodic.measure_preserving import measure_theory.integral.set_integral /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s.prod t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem and Fubini's theorem. ## Main definition * `measure_theory.measure.prod`: The product of two measures. ## Main results * `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version. * `measure_theory.measure.prod_prod` states `μ.prod ν (s.prod t) = μ s * ν t` for measurable sets `s` and `t`. * `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. * `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. * `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable theory open_locale classical topological_space ennreal measure_theory open set function real ennreal open measure_theory measurable_space measure_theory.measure open topological_space (hiding generate_from) open filter (hiding prod_eq map) variables {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C) (hD : is_pi_system D) : is_pi_system (image2 set.prod C D) := begin rintro _ _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst, rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst, exact mem_image2_of_mem (hC _ _ hs₁ hs₂ hst.1) (hD _ _ ht₁ ht₂ hst.2) end /-- Rectangles of countably spanning sets are countably spanning. -/ lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : is_countably_spanning (image2 set.prod C D) := begin rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩, refine ⟨λ n, (s n.unpair.1).prod (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩, rw [Union_unpair_prod, h2s, h2t, univ_prod_univ] end variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β'] variables [measurable_space γ] variables {μ : measure α} {ν : measure β} {τ : measure γ} variables [normed_group E] [measurable_space E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : @prod.measurable_space _ _ (generate_from C) (generate_from D) = generate_from (image2 set.prod C D) := begin apply le_antisymm, { refine sup_le _ _; rw [comap_generate_from]; apply generate_from_le; rintro _ ⟨s, hs, rfl⟩, { rcases hD with ⟨t, h1t, h2t⟩, rw [← prod_univ, ← h2t, prod_Union], apply measurable_set.Union, intro n, apply measurable_set_generate_from, exact ⟨s, t n, hs, h1t n, rfl⟩ }, { rcases hC with ⟨t, h1t, h2t⟩, rw [← univ_prod, ← h2t, Union_prod_const], apply measurable_set.Union, rintro n, apply measurable_set_generate_from, exact mem_image2_of_mem (h1t n) hs } }, { apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq], apply (measurable_fst _).inter (measurable_snd _), { exact measurable_set_generate_from hs }, { exact measurable_set_generate_from ht } } end /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) : generate_from (image2 set.prod C D) = prod.measurable_space := by rw [← hC, ← hD, generate_from_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s.prod t` for sets `s : set α` and `t : set β`. -/ lemma generate_from_prod : generate_from (image2 set.prod {s : set α | measurable_set s} {t : set β | measurable_set t}) = prod.measurable_space := generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set is_countably_spanning_measurable_set is_countably_spanning_measurable_set /-- Rectangles form a π-system. -/ lemma is_pi_system_prod : is_pi_system (image2 set.prod {s : set α | measurable_set s} {t : set β | measurable_set t}) := is_pi_system_measurable_set.prod is_pi_system_measurable_set /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ lemma measurable_measure_prod_mk_left_finite [is_finite_measure ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs, { simp [measurable_zero, const_def] }, { rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if], exact measurable_const.indicator hs }, { intros t ht h2t, simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)], exact h2t.const_sub _ }, { intros f h1f h2f h3f, simp_rw [preimage_Union], have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) := λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f i j hij)) (λ i, measurable_prod_mk_left (h2f i)), simp_rw [this], apply measurable.ennreal_tsum h3f }, end /-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs, simp only [← @supr_restrict_spanning_sets _ _ ν, this], apply measurable_supr, intro i, haveI := fact.mk (measure_spanning_sets_lt_top ν i), exact measurable_measure_prod_mk_left_finite hs end /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)} (hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) := measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs) lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_left hs], exact measurable_measure_prod_mk_left hs end lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] : measurable (λ y : β, map (λ x : α, (x, y)) μ) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_right hs], exact measurable_measure_prod_mk_right hs end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_right' [sigma_finite ν] : ∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)), { simpa [lintegral_indicator _ (m hs)] }, exact (measurable_measure_prod_mk_left hs).const_mul _ }, { rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add (hf.comp m) (hg.comp m)], exact h2f.add h2g }, { intros f hf h2f h3f, have := measurable_supr h3f, have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), simpa [lintegral_supr (λ n, (hf n).comp m), this] } end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞} (hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) := hf.lintegral_prod_left' lemma measurable_set_integrable [sigma_finite ν] [opens_measurable_space E] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable_set { x | integrable (f x) ν } := begin simp_rw [integrable, hf.of_uncurry_left.ae_measurable, true_and], exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const end section variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ x, ∫ y, f x y ∂ν) := begin let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf univ _ (mem_univ 0), let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left, let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator (λ x, (s' n x).integral ν), have hf' : ∀ n, measurable (f' n), { intro n, refine measurable.indicator _ (measurable_set_integrable hf), have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range, { intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y, simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ }, simp only [simple_func.integral_eq_sum_of_subset (this _)], refine finset.measurable_sum _ (λ x _, _), refine (measurable.ennreal_to_real _).smul_const _, simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt}, apply measurable_measure_prod_mk_left, exact (s n).measurable_set_fiber x }, have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)), { rw [tendsto_pi], intro x, by_cases hfx : integrable (f x) ν, { have : ∀ n, integrable (s' n x) ν, { intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).measurable.ae_measurable, apply eventually_of_forall, intro y, simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n }, simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem, mem_set_of_eq], refine tendsto_integral_of_dominated_convergence (λ y, ∥f x y∥ + ∥f x y∥) (λ n, (s' n x).ae_measurable) (hfx.norm.add hfx.norm) _ _, { exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) }, { exact eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ (by simp)) } }, { simpa [f', hfx, integral_undef] using @tendsto_const_nhds _ _ _ (0 : E) _, } }, exact measurable_of_tendsto_metric hf' h2f' end /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ lemma measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ x, ∫ y, f (x, y) ∂ν) := by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right } /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ y, ∫ x, f x y ∂μ) := (hf.comp measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ lemma measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ y, ∫ x, f (x, y) ∂μ) := (hf.comp measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace measure_theory namespace measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is σ-finite. -/ @[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) := bind μ $ λ x : α, map (prod.mk x) ν instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) := { volume := volume.prod volume } variables {μ ν} [sigma_finite ν] lemma volume_eq_prod (α β) [measure_space α] [measure_space β] : (volume : measure (α × β)) = (volume : measure α).prod (volume : measure β) := rfl lemma prod_apply {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ := by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left, map_apply measurable_prod_mk_left hs] @[simp] lemma prod_prod {s : set α} {t : set β} (hs : measurable_set s) (ht : measurable_set t) : μ.prod ν (s.prod t) = μ s * ν t := by simp_rw [prod_apply (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ hs, lintegral_const, restrict_apply measurable_set.univ, univ_inter, mul_comm] /-- If we don't assume measurability of `s` and `t`, we can bound the measure of their product. -/ lemma prod_prod_le (s : set α) (t : set β) : μ.prod ν (s.prod t) ≤ μ s * ν t := calc μ.prod ν (s.prod t) ≤ μ.prod ν ((to_measurable μ s).prod (to_measurable ν t)) : measure_mono $ set.prod_mono (subset_to_measurable _ _) (subset_to_measurable _ _) ... = μ (to_measurable μ s) * ν (to_measurable ν t) : prod_prod (measurable_set_to_measurable _ _) (measurable_set_to_measurable _ _) ... = μ s * ν t : by rw [measure_to_measurable, measure_to_measurable] lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ := by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s } lemma integrable_measure_prod_mk_left {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ := begin refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable, _⟩, simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg], convert h2s.lt_top using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae, refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx, rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx], end /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_prod_null {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_ae_null_of_prod_null {s : set (α × β)} (h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := begin obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h, simp_rw [measure_prod_null mt] at ht, rw [eventually_le_antisymm_iff], exact ⟨eventually_le.trans_eq (eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall $ λ x, zero_le _⟩ end /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) := measure_ae_null_of_prod_null h /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)} (hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) (hC : ∀ s ∈ C, measurable_set s) (hD : ∀ t ∈ D, measurable_set t) : (μ.prod ν).finite_spanning_sets_in (image2 set.prod C D) := begin haveI := hν.sigma_finite, refine ⟨λ n, (hμ.set n.unpair.1).prod (hν.set n.unpair.2), λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩, { simp_rw [prod_prod (hC _ (hμ.set_mem _)) (hD _ (hν.set_mem _))], exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne }, { simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] } end lemma prod_fst_absolutely_continuous : map prod.fst (μ.prod ν) ≪ μ := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply measurable_fst hs, ← prod_univ, prod_prod hs measurable_set.univ], rw [h2s, zero_mul] -- for some reason `simp_rw [h2s]` doesn't work end lemma prod_snd_absolutely_continuous : map prod.snd (μ.prod ν) ≪ ν := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply measurable_snd hs, ← univ_prod, prod_prod measurable_set.univ hs], rw [h2s, mul_zero] -- for some reason `simp_rw [h2s]` doesn't work end variables [sigma_finite μ] instance prod.sigma_finite : sigma_finite (μ.prod ν) := (μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in (λ _, id) (λ _, id)).sigma_finite /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D) (h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D) {μν : measure (α × β)} (h₁ : ∀ (s ∈ C) (t ∈ D), μν (set.prod s t) = μ s * ν t) : μ.prod ν = μν := begin have h4C : ∀ (s : set α), s ∈ C → measurable_set s, { intros s hs, rw [← hC], exact measurable_set_generate_from hs }, have h4D : ∀ (t : set β), t ∈ D → measurable_set t, { intros t ht, rw [← hD], exact measurable_set_generate_from ht }, refine (h3C.prod h3D h4C h4D).ext (generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm (h2C.prod h2D) _, { rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite, simp_rw [h₁ s hs t ht, prod_prod (h4C s hs) (h4D t ht)] } end /-- A measure on a product space equals the product measure if they are equal on rectangles. -/ lemma prod_eq {μν : measure (α × β)} (h : ∀ s t, measurable_set s → measurable_set t → μν (s.prod t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set is_pi_system_measurable_set is_pi_system_measurable_set μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht) lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod ht hs, mul_comm] end lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν := by { rw [← prod_swap, map_apply measurable_swap hs], simp only [prod_apply (measurable_swap hs)], refl } lemma prod_assoc_prod [sigma_finite τ] : map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := begin refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in (ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in (λ _, id) (λ _, id)) _).symm, rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu, simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)), prod_prod ht hu, measurable_equiv.prod_assoc, measurable_equiv.coe_mk, equiv.prod_assoc_preimage, prod_prod (hs.prod ht) hu, prod_prod hs ht, mul_assoc] end /-! ### The product of specific measures -/ lemma prod_restrict {s : set α} {t : set β} (hs : measurable_set s) (ht : measurable_set t) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s.prod t) := begin refine prod_eq (λ s' t' hs' ht', _), simp_rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod (hs'.inter hs) (ht'.inter ht), restrict_apply hs', restrict_apply ht'] end lemma restrict_prod_eq_prod_univ {s : set α} (hs : measurable_set s) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s.prod univ) := begin have : ν = ν.restrict set.univ := measure.restrict_univ.symm, rwa [this, measure.prod_restrict, ← this], exact measurable_set.univ, end lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one] end lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul] end lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] lemma prod_sum {ι : Type*} [fintype ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] : μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod hs ht, tsum_fintype, finset.mul_sum] end lemma sum_prod {ι : Type*} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : (sum μ).prod ν = sum (λ i, (μ i).prod ν) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod hs ht, tsum_fintype, finset.sum_mul] end lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod hs ht, left_distrib] } lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod hs ht, right_distrib] } @[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 := by { rw measure.prod, exact bind_zero_left _ } @[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 := by simp [measure.prod] lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ} {μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa)) (hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) : (map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) := begin haveI := hgc.of_map μc hg, refine prod_eq (λ s t hs ht, _), rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht], exact prod_prod (hf hs) (hg ht) end end measure namespace measure_preserving open measure variables {δ : Type*} [measurable_space δ] {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ} lemma skew_product [sigma_finite μb] [sigma_finite μd] {f : α → β} (hf : measure_preserving f μa μb) {g : α → γ → δ} (hgm : measurable (uncurry g)) (hg : ∀ᵐ x ∂μa, map (g x) μc = μd) : measure_preserving (λ p : α × γ, (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := begin classical, have : measurable (λ p : α × γ, (f p.1, g p.1 p.2)) := (hf.1.comp measurable_fst).prod_mk hgm, /- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg` to deduce `sigma_finite μc`. -/ rcases eq_or_ne μa 0 with (rfl|ha), { rw [← hf.map_eq, zero_prod, (map f).map_zero, zero_prod], exact ⟨this, (map _).map_zero⟩ }, haveI : sigma_finite μc, { rcases (ae_ne_bot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩, exact sigma_finite.of_map _ hgm.of_uncurry_left (by rwa hx) }, -- Thus we can apply `measure.prod_eq` to prove equality of measures. refine ⟨this, (prod_eq $ λ s t hs ht, _).symm⟩, rw [map_apply this (hs.prod ht)], refine (prod_apply (this $ hs.prod ht)).trans _, have : ∀ᵐ x ∂μa, μc ((λ y, (f x, g x y)) ⁻¹' s.prod t) = indicator (f ⁻¹' s) (λ y, μd t) x, { refine hg.mono (λ x hx, _), unfreezingI { subst hx }, simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage], split_ifs, exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] }, simp only [preimage_preimage], rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] end /-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`, then `prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/ protected lemma prod [sigma_finite μb] [sigma_finite μd] {f : α → β} {g : γ → δ} (hf : measure_preserving f μa μb) (hg : measure_preserving g μc μd) : measure_preserving (prod.map f g) (μa.prod μc) (μb.prod μd) := have measurable (uncurry $ λ _ : α, g), from (hg.1.comp measurable_snd), hf.skew_product this $ filter.eventually_of_forall $ λ _, hg.map_eq end measure_preserving end measure_theory open measure_theory.measure section lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma ae_measurable.fst [sigma_finite ν] {f : α → γ} (hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_measurable' measurable_fst prod_fst_absolutely_continuous lemma ae_measurable.snd [sigma_finite ν] {f : β → γ} (hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_measurable' measurable_snd prod_snd_absolutely_continuous /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ lemma ae_measurable.integral_prod_right' [sigma_finite ν] [second_countable_topology E] [normed_space ℝ E] [borel_space E] [complete_space E] ⦃f : α × β → E⦄ (hf : ae_measurable f (μ.prod ν)) : ae_measurable (λ x, ∫ y, f (x, y) ∂ν) μ := ⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.measurable_mk.integral_prod_right', begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], assume x hx, exact integral_congr_ae hx end⟩ lemma ae_measurable.prod_mk_left [sigma_finite ν] {f : α × β → γ} (hf : ae_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_measurable (λ y, f (x, y)) ν := begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], intros x hx, exact ⟨λ y, hf.mk f (x, y), hf.measurable_mk.comp measurable_prod_mk_left, hx⟩ end end namespace measure_theory /-! ### The Lebesgue integral on a product -/ variables [sigma_finite ν] lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) := by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap, prod_swap] } /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs, prod_apply] }, { rintro f g - hf hg h2f h2g, simp [lintegral_add, measurable.lintegral_prod_right', hf.comp m, hg.comp m, hf, hg, h2f, h2g] }, { intros f hf h2f h3f, have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m, have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right', have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij), simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] }, end /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ, { apply lintegral_congr_ae, filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk], assume a ha, exact lintegral_congr_ae ha }, rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk], apply_instance end /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap } /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : measurable f) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm f hf.ae_measurable /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Integrability on a product -/ section variables [opens_measurable_space E] lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) := ⟨hf.ae_measurable.prod_swap, (lintegral_prod_swap _ hf.ae_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩ lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ : integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) := ⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩ lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : measurable f) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm], have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ∥f (x, y)∥ := λ x, eventually_of_forall (λ y, norm_nonneg _), simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp measurable_prod_mk_left).ae_measurable, ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm], -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) := λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1], rw [this], { intro h2f, rw lintegral_congr_ae, refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only, rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx }, { intro h2f, refine ae_lt_top _ h2f.ne, exact h1f.ennnorm.lintegral_prod_right' }, end lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin rw [has_finite_integral_congr h1f.ae_eq_mk, has_finite_integral_prod_iff h1f.measurable_mk], apply and_congr, { apply eventually_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact has_finite_integral_congr hx }, { apply has_finite_integral_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact integral_congr_ae (eventually_eq.fun_comp hx _) }, { apply_instance } end /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. -/ lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ∥f (x, y)∥ dx` is integrable. -/ lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] } lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ := ((integrable_prod_iff' hf.ae_measurable).mp hf).1 lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν := hf.swap.prod_left_ae lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := ((integrable_prod_iff hf.ae_measurable).mp hf).2 lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := hf.swap.integral_norm_prod_left end variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] lemma integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ := integrable.mono hf.integral_norm_prod_left hf.ae_measurable.integral_prod_right' $ eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $ (norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $ λ y, (norm_nonneg (f (x, y)) : _)).symm lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variables [sigma_finite μ] lemma integral_prod_swap (f : α × β → E) (hf : ae_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) := begin rw ← prod_swap at hf, rw [← integral_map measurable_swap hf, prod_swap] end variables {E' : Type*} [measurable_space E'] [normed_group E'] [borel_space E'] [complete_space E'] [normed_space ℝ E'] [second_countable_topology E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_add h2f h2g], end /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_sub h2f h2g] end /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine lintegral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae], intros x h2f h2g, simp [integral_sub h2f h2g] end /-- Double integrals commute with addition. -/ lemma integral_integral_add ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans $ integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ lemma integral_integral_add' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ lemma integral_integral_sub ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans $ integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ lemma integral_integral_sub' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ lemma continuous_integral_integral : continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) := begin rw [continuous_iff_continuous_at], intro g, refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left (eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _, simp_rw [← lintegral_fn_integral_sub (λ x, (nnnorm x : ℝ≥0∞)) (L1.integrable_coe_fn _) (L1.integrable_coe_fn g)], refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _, { exact λ i, ∫⁻ x, ∫⁻ y, nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ }, swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) }, show tendsto (λ (i : α × β →₁[μ.prod ν] E), ∫⁻ x, ∫⁻ (y : β), nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ) (𝓝 g) (𝓝 0), have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (nnnorm (i z - g z) : ℝ≥0∞)) := λ i, ((Lp.measurable i).sub (Lp.measurable g)).ennnorm, simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral, ← of_real_zero], refine (continuous_of_real.tendsto 0).comp _, rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id end /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `measure_theory.integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)), ∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := begin apply integrable.induction, { intros c s hs h2s, simp_rw [integral_indicator hs, ← indicator_comp_right, function.comp, integral_indicator (measurable_prod_mk_left hs), set_integral_const, integral_smul_const, integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable (ae_measure_lt_top hs h2s.ne), prod_apply hs] }, { intros f g hfg i_f i_g hf hg, simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] }, { exact is_closed_eq continuous_integral continuous_integral_integral }, { intros f g hfg i_f hf, convert hf using 1, { exact integral_congr_ae hfg.symm }, { refine integral_congr_ae _, refine (ae_ae_of_ae_prod hfg).mp _, apply eventually_of_forall, intros x hfgx, exact integral_congr_ae (ae_eq_symm hfgx) } } end /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) : ∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by { simp_rw [← integral_prod_swap f hf.ae_measurable], exact integral_prod _ hf.swap } /-- Reversed version of **Fubini's Theorem**. -/ lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) end measure_theory
0e1c2857b2babe472c44021f00bdd191e7d7efb7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/inner_product_space/dual.lean
fbb0a733d61347a98e79520ccdcd7d30ce2e8229
[ "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
6,585
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.inner_product_space.projection import analysis.normed_space.dual import analysis.normed_space.star.basic /-! # The Fréchet-Riesz representation theorem We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define `to_dual_map`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `to_dual`, a conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the surjectivity of `to_dual_map`. This is the Fréchet-Riesz representation theorem: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. For a bounded sesquilinear form `B : E →L⋆[𝕜] E →L[𝕜] 𝕜`, we define a map `inner_product_space.continuous_linear_map_of_bilin B : E →L[𝕜] E`, given by substituting `E →L[𝕜] 𝕜` with `E` using `to_dual`. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ noncomputable theory open_locale classical complex_conjugate universes u v namespace inner_product_space open is_R_or_C continuous_linear_map variables (𝕜 : Type*) variables (E : Type*) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local postfix `†`:90 := star_ring_end _ /-- An element `x` of an inner product space `E` induces an element of the dual space `dual 𝕜 E`, the map `λ y, ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric embedding of `E` into `dual 𝕜 E`. If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence; see `to_dual`. -/ def to_dual_map : E →ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := { norm_map' := λ _, innerSL_apply_norm, ..innerSL } variables {E} @[simp] lemma to_dual_map_apply {x y : E} : to_dual_map 𝕜 E x y = ⟪x, y⟫ := rfl lemma innerSL_norm [nontrivial E] : ∥(innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜)∥ = 1 := show ∥(to_dual_map 𝕜 E).to_continuous_linear_map∥ = 1, from linear_isometry.norm_to_continuous_linear_map _ variable {𝕜} lemma ext_inner_left_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪b i, x⟫ = ⟪b i, y⟫) : x = y := begin apply (to_dual_map 𝕜 E).map_eq_iff.mp, refine (function.injective.eq_iff continuous_linear_map.coe_injective).mp (basis.ext b _), intro i, simp only [to_dual_map_apply, continuous_linear_map.coe_coe], rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end lemma ext_inner_right_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪x, b i⟫ = ⟪y, b i⟫) : x = y := begin refine ext_inner_left_basis b (λ i, _), rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end variables (𝕜) (E) [complete_space E] /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual_map` is surjective. -/ def to_dual : E ≃ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := linear_isometry_equiv.of_surjective (to_dual_map 𝕜 E) begin intros ℓ, set Y := ker ℓ with hY, by_cases htriv : Y = ⊤, { have hℓ : ℓ = 0, { have h' := linear_map.ker_eq_top.mp htriv, rw [←coe_zero] at h', apply coe_injective, exact h' }, exact ⟨0, by simp [hℓ]⟩ }, { rw [← submodule.orthogonal_eq_bot_iff] at htriv, change Yᗮ ≠ ⊥ at htriv, rw [submodule.ne_bot_iff] at htriv, obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv, refine ⟨((ℓ z)† / ⟪z, z⟫) • z, _⟩, ext x, have h₁ : (ℓ z) • x - (ℓ x) • z ∈ Y, { rw [mem_ker, map_sub, continuous_linear_map.map_smul, continuous_linear_map.map_smul, algebra.id.smul_eq_mul, algebra.id.smul_eq_mul, mul_comm], exact sub_self (ℓ x * ℓ z) }, have h₂ : (ℓ z) * ⟪z, x⟫ = (ℓ x) * ⟪z, z⟫, { have h₃ := calc 0 = ⟪z, (ℓ z) • x - (ℓ x) • z⟫ : by { rw [(Y.mem_orthogonal' z).mp hz], exact h₁ } ... = ⟪z, (ℓ z) • x⟫ - ⟪z, (ℓ x) • z⟫ : by rw [inner_sub_right] ... = (ℓ z) * ⟪z, x⟫ - (ℓ x) * ⟪z, z⟫ : by simp [inner_smul_right], exact sub_eq_zero.mp (eq.symm h₃) }, have h₄ := calc ⟪((ℓ z)† / ⟪z, z⟫) • z, x⟫ = (ℓ z) / ⟪z, z⟫ * ⟪z, x⟫ : by simp [inner_smul_left, conj_conj] ... = (ℓ z) * ⟪z, x⟫ / ⟪z, z⟫ : by rw [←div_mul_eq_mul_div] ... = (ℓ x) * ⟪z, z⟫ / ⟪z, z⟫ : by rw [h₂] ... = ℓ x : begin have : ⟪z, z⟫ ≠ 0, { change z = 0 → false at z_ne_0, rwa ←inner_self_eq_zero at z_ne_0 }, field_simp [this] end, exact h₄ } end variables {𝕜} {E} @[simp] lemma to_dual_apply {x y : E} : to_dual 𝕜 E x y = ⟪x, y⟫ := rfl @[simp] lemma to_dual_symm_apply {x : E} {y : normed_space.dual 𝕜 E} : ⟪(to_dual 𝕜 E).symm y, x⟫ = y x := begin rw ← to_dual_apply, simp only [linear_isometry_equiv.apply_symm_apply], end variables {E 𝕜} /-- Maps a bounded sesquilinear form to its continuous linear map, given by interpreting the form as a map `B : E →L⋆[𝕜] normed_space.dual 𝕜 E` and dualizing the result using `to_dual`. -/ def continuous_linear_map_of_bilin (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) : E →L[𝕜] E := comp (to_dual 𝕜 E).symm.to_continuous_linear_equiv.to_continuous_linear_map B local postfix `♯`:1025 := continuous_linear_map_of_bilin variables (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) @[simp] lemma continuous_linear_map_of_bilin_apply (v w : E) : ⟪(B♯ v), w⟫ = B v w := by simp [continuous_linear_map_of_bilin] lemma unique_continuous_linear_map_of_bilin {v f : E} (is_lax_milgram : (∀ w, ⟪f, w⟫ = B v w)) : f = B♯ v := begin refine ext_inner_right 𝕜 _, intro w, rw continuous_linear_map_of_bilin_apply, exact is_lax_milgram w, end end inner_product_space
2b9d6b4d2edce88a3664fef97fde41b8705c4e3a
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/facts/normed_group.lean
47ecfeb4d4a5858274b84d7b14b3c112a1cab91b
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
198
lean
import analysis.normed_space.basic variables {V : Type*} [normed_group V] -- move this instance fact_nnnorm_add_le (v w : V) : fact (nnnorm (v + w) ≤ nnnorm v + nnnorm w) := nnnorm_add_le _ _
b1afd495cdeec0efa5c159ad3a94b1603aae8093
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/iso.hlean
338a787e7690d997a9598dc5f33c56eb27ef0d72
[ "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
15,735
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, Jakob von Raumer -/ import .precategory types.sigma arity open eq category prod equiv is_equiv sigma sigma.ops is_trunc namespace iso structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {retraction_of : b ⟶ a} (retraction_comp : retraction_of ∘ f = id) structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {section_of : b ⟶ a} (comp_section : f ∘ section_of = id) structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := (inverse : b ⟶ a) (left_inverse : inverse ∘ f = id) (right_inverse : f ∘ inverse = id) attribute is_iso.inverse [reducible] open split_mono split_epi is_iso abbreviation retraction_of [unfold 6] := @split_mono.retraction_of abbreviation retraction_comp [unfold 6] := @split_mono.retraction_comp abbreviation section_of [unfold 6] := @split_epi.section_of abbreviation comp_section [unfold 6] := @split_epi.comp_section abbreviation inverse [unfold 6] := @is_iso.inverse abbreviation left_inverse [unfold 6] := @is_iso.left_inverse abbreviation right_inverse [unfold 6] := @is_iso.right_inverse postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C definition split_mono_of_is_iso [constructor] [instance] [priority 300] (f : a ⟶ b) [H : is_iso f] : split_mono f := split_mono.mk !left_inverse definition split_epi_of_is_iso [constructor] [instance] [priority 300] (f : a ⟶ b) [H : is_iso f] : split_epi f := split_epi.mk !right_inverse definition is_iso_id [constructor] [instance] [priority 500] (a : ob) : is_iso (ID a) := is_iso.mk _ !id_id !id_id definition is_iso_inverse [constructor] [instance] [priority 200] (f : a ⟶ b) {H : is_iso f} : is_iso f⁻¹ := is_iso.mk _ !right_inverse !left_inverse theorem left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := by rewrite [-(id_right g), -Hr, assoc, Hl, id_left] theorem retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_comp H2 theorem section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h := (left_inverse_eq_right_inverse H2 !comp_section)⁻¹ theorem inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !left_inverse H2 theorem inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := (left_inverse_eq_right_inverse H2 !right_inverse)⁻¹ theorem retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : retraction_of f = section_of f := retraction_eq !comp_section definition is_iso_of_split_epi_of_split_mono [constructor] (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : is_iso f := is_iso.mk _ ((retraction_eq_section f) ▸ (retraction_comp f)) (comp_section f) theorem inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := @inverse_eq_left _ _ _ _ _ _ H !left_inverse theorem inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)] : (f⁻¹)⁻¹ = f := inverse_eq_right !left_inverse theorem inverse_eq_inverse {f g : a ⟶ b} [H : is_iso f] [H : is_iso g] (p : f = g) : f⁻¹ = g⁻¹ := by cases p;apply inverse_unique theorem retraction_id (a : ob) : retraction_of (ID a) = id := retraction_eq !id_id theorem section_id (a : ob) : section_of (ID a) = id := section_eq !id_id theorem id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id := inverse_eq_left !id_id definition split_mono_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) := split_mono.mk (show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id, by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp]) definition split_epi_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) := split_epi.mk (show (g ∘ f) ∘ section_of f ∘ section_of g = id, by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section]) definition is_iso_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) := !is_iso_of_split_epi_of_split_mono theorem is_prop_is_iso [instance] (f : hom a b) : is_prop (is_iso f) := begin apply is_prop.mk, intro H H', cases H with g li ri, cases H' with g' li' ri', fapply (apd0111 (@is_iso.mk ob C a b f)), apply left_inverse_eq_right_inverse, apply li, apply ri', apply is_prop.elim, apply is_prop.elim, end end iso open iso /- isomorphic objects -/ structure iso {ob : Type} [C : precategory ob] (a b : ob) := (to_hom : hom a b) (struct : is_iso to_hom) infix ` ≅ `:50 := iso notation c ` ≅[`:50 C:0 `] `:0 c':50 := @iso C _ c c' attribute iso.struct [instance] [priority 2000] namespace iso variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C attribute to_hom [coercion] protected definition MK [constructor] (f : a ⟶ b) (g : b ⟶ a) (H1 : g ∘ f = id) (H2 : f ∘ g = id) := @(mk f) (is_iso.mk _ H1 H2) variable {C} definition to_inv [reducible] [unfold 5] (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹ definition to_left_inverse [unfold 5] (f : a ≅ b) : (to_hom f)⁻¹ ∘ (to_hom f) = id := left_inverse (to_hom f) definition to_right_inverse [unfold 5] (f : a ≅ b) : (to_hom f) ∘ (to_hom f)⁻¹ = id := right_inverse (to_hom f) variable [C] protected definition refl [constructor] (a : ob) : a ≅ a := mk (ID a) _ protected definition symm [constructor] ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (to_hom H)⁻¹ _ protected definition trans [constructor] ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (to_hom H2 ∘ to_hom H1) _ infixl ` ⬝i `:75 := iso.trans postfix [parsing_only] `⁻¹ⁱ`:(max + 1) := iso.symm definition change_hom [constructor] (H : a ≅ b) (f : a ⟶ b) (p : to_hom H = f) : a ≅ b := iso.MK f (to_inv H) (p ▸ to_left_inverse H) (p ▸ to_right_inverse H) definition change_inv [constructor] (H : a ≅ b) (g : b ⟶ a) (p : to_inv H = g) : a ≅ b := iso.MK (to_hom H) g (p ▸ to_left_inverse H) (p ▸ to_right_inverse H) definition iso_mk_eq {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f') : iso.mk f _ = iso.mk f' _ := apd011 iso.mk p !is_prop.elim variable {C} definition iso_eq {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' := by (cases f; cases f'; apply (iso_mk_eq p)) variable [C] -- The structure for isomorphism can be characterized up to equivalence by a sigma type. protected definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) := begin fapply (equiv.mk), {intro S, apply iso.mk, apply (S.2)}, {fapply adjointify, {intro p, cases p with f H, exact sigma.mk f H}, {intro p, cases p, apply idp}, {intro S, cases S, apply idp}}, end -- The type of isomorphisms between two objects is a set definition is_set_iso [instance] : is_set (a ≅ b) := begin apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv (!iso.sigma_char), end definition iso_of_eq [unfold 5] (p : a = b) : a ≅ b := eq.rec_on p (iso.refl a) definition hom_of_eq [reducible] [unfold 5] (p : a = b) : a ⟶ b := iso.to_hom (iso_of_eq p) definition inv_of_eq [reducible] [unfold 5] (p : a = b) : b ⟶ a := iso.to_inv (iso_of_eq p) definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) := eq.rec_on p idp theorem hom_of_eq_inv (p : a = b) : hom_of_eq p⁻¹ = inv_of_eq p := eq.rec_on p idp theorem inv_of_eq_inv (p : a = b) : inv_of_eq p⁻¹ = hom_of_eq p := eq.rec_on p idp definition iso_of_eq_con (p : a = b) (q : b = c) : iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) := eq.rec_on q (eq.rec_on p (iso_eq !id_id⁻¹)) section open funext variables {X : Type} {x y : X} {F G : X → ob} definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y)) : p ▸ f = hom_of_eq (apd10 p y) ∘ f ∘ inv_of_eq (apd10 p x) := by induction p; exact !id_leftright⁻¹ definition transport_hom_of_eq_right (p : x = y) (f : hom c (F x)) : p ▸ f = hom_of_eq (ap F p) ∘ f := by induction p; exact !id_left⁻¹ definition transport_hom_of_eq_left (p : x = y) (f : hom (F x) c) : p ▸ f = f ∘ inv_of_eq (ap F p) := by induction p; exact !id_right⁻¹ definition transport_hom (p : F ~ G) (f : hom (F x) (F y)) : eq_of_homotopy p ▸ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) := calc eq_of_homotopy p ▸ f = hom_of_eq (apd10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apd10 (eq_of_homotopy p) x) : transport_hom_of_eq ... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {right_inv apd10 p} end structure mono [class] (f : a ⟶ b) := (elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) structure epi [class] (f : a ⟶ b) := (elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f := mono.mk (λ c g h H, calc g = id ∘ g : by rewrite id_left ... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp ... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc] ... = id ∘ h : by rewrite retraction_comp ... = h : by rewrite id_left) definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f := epi.mk (λ c g h H, calc g = g ∘ id : by rewrite id_right ... = g ∘ f ∘ section_of f : by rewrite -(comp_section f) ... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc] ... = h ∘ id : by rewrite comp_section ... = h : by rewrite id_right) definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g] : mono (g ∘ f) := mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), begin rewrite *assoc, exact H end, !mono.elim (!mono.elim H2)) definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g] : epi (g ∘ f) := epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, begin rewrite -*assoc, exact H end, !epi.elim (!epi.elim H2)) end iso attribute iso.refl [refl] attribute iso.symm [symm] attribute iso.trans [trans] namespace iso /- rewrite lemmas for inverses, modified from https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v -/ section variables {ob : Type} [C : precategory ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq theorem comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse theorem comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse theorem inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p := by rewrite [assoc, left_inverse, id_left] theorem comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g := by rewrite [assoc, right_inverse, id_left] theorem comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r := by rewrite [-assoc, right_inverse, id_right] theorem inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f := by rewrite [-assoc, left_inverse, id_right] theorem comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ := inverse_eq_left (show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from by rewrite [-assoc, inverse_comp_cancel_left, left_inverse]) theorem inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▸ comp_inverse q⁻¹ g theorem inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▸ comp_inverse q f⁻¹ theorem inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▸ inverse_comp_inverse_left q r⁻¹ end section variables {ob : Type} {C : precategory ob} include C variables {d c b a : ob} {r' : c ⟶ d} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {p' : a ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq theorem comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▸ comp_inverse_cancel_left q g theorem comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▸ inverse_comp_cancel_right f q theorem eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y := (comp_eq_of_eq_inverse_comp H⁻¹)⁻¹ theorem eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q := (comp_eq_of_eq_comp_inverse H⁻¹)⁻¹ variable {Hq} theorem inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▸ inverse_comp_cancel_left q p theorem comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▸ comp_inverse_cancel_right r q theorem eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z := (inverse_comp_eq_of_eq_comp H⁻¹)⁻¹ theorem eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ := (comp_inverse_eq_of_eq_comp H⁻¹)⁻¹ theorem eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹ theorem eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹ theorem inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h := (eq_inverse_of_comp_eq_id' H⁻¹)⁻¹ theorem inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h := (eq_inverse_of_comp_eq_id H⁻¹)⁻¹ variable [Hq] theorem eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q := eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q theorem eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q := eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q theorem eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹ theorem eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹ variables (q) theorem comp.cancel_left (H : q ∘ p = q ∘ p') : p = p' := by rewrite [-inverse_comp_cancel_left q, H, inverse_comp_cancel_left q] theorem comp.cancel_right (H : r ∘ q = r' ∘ q) : r = r' := by rewrite [-comp_inverse_cancel_right _ q, H, comp_inverse_cancel_right _ q] end end iso
42f18bae44e53cfb5afbf195f1d81e109e574537
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Elab/Term.lean
a9e952bf66e1da08cc8ef83fc8005396946afeb8
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,920
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.ExprDefEq import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Meta.Tactic.Util import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term /- Set isDefEq configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT δ (StateT σ Id) σ := monadLift (get : StateT σ Id σ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α ``` It produces the following unification problem when we process the expected type: ``` ?n ?α =?= StateT δ (StateT σ id) σ ==> (approximate using first-order unification) ?n := StateT δ (StateT σ id) ?α := σ ``` Then, we need to solve: ``` ?m ?α =?= StateT σ id σ ==> instantiate metavars ?m σ =?= StateT σ id σ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun σ => StateT σ id σ ``` Note that the constraint is not a Milner pattern because σ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun σ' => StateT σ id σ ?m := fun σ' => StateT σ' id σ ?m := fun σ' => StateT σ id σ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT σ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : List MVarErrorInfo := [] messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad TermElabM := { inferInstanceAs (Monad TermElabM) with } open Meta instance : Inhabited (TermElabM α) where default := throw arbitrary structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The info trees are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally modify ({ s with infoState := ·.infoState }) set sMeta unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal → Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal → Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos } def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg : MessageData := "don't know how to synthesize placeholder" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : NameSet := {} for mvarErrorInfo in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId let foundError ← withMVarContext mvarId do /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do mvarErrorInfo.logError extraMsg? pure true else pure false if foundError then hasNewErrors := true return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? β α a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope α fun _ α => do if (← isMonadApp α) then pure none else if !α.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. It only works if `n` implements `Pure` If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, β) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n β eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel α let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel α let v ← getLevel β let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | none => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } | some mvarId => return Sum.inr mvarId def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' (mkInfo := mkTermInfo elabFn.decl (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex) catch ex => match ex with | Exception.internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(noImplicitLambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then pure none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then pure none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType | _ => pure none | _ => pure none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew) => withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do let β ← mkFreshTypeMVar let u ← getLevel α let v ← getLevel β let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar] else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := let x : TermElabM α := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst α name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
64293f88b850a2c7eabf262fb232e02ee34ea1a3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/vector/zip.lean
e47bc9ee582ad8e52263235ea8a178619ccc03e1
[ "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
1,457
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.vector.basic import data.list.zip /-! # The `zip_with` operation on vectors. -/ namespace vector section zip_with variables {α β γ : Type*} {n : ℕ} (f : α → β → γ) /-- Apply the function `f : α → β → γ` to each corresponding pair of elements from two vectors. -/ def zip_with : vector α n → vector β n → vector γ n := λ x y, ⟨list.zip_with f x.1 y.1, by simp⟩ @[simp] lemma zip_with_to_list (x : vector α n) (y : vector β n) : (vector.zip_with f x y).to_list = list.zip_with f x.to_list y.to_list := rfl @[simp] lemma zip_with_nth (x : vector α n) (y : vector β n) (i) : (vector.zip_with f x y).nth i = f (x.nth i) (y.nth i) := begin dsimp only [vector.zip_with, vector.nth], cases x, cases y, simp only [list.nth_le_zip_with, subtype.coe_mk], congr, end @[simp] lemma zip_with_tail (x : vector α n) (y : vector β n) : (vector.zip_with f x y).tail = vector.zip_with f x.tail y.tail := by { ext, simp [nth_tail], } @[to_additive] lemma prod_mul_prod_eq_prod_zip_with [comm_monoid α] (x y : vector α n) : x.to_list.prod * y.to_list.prod = (vector.zip_with (*) x y).to_list.prod := list.prod_mul_prod_eq_prod_zip_with_of_length_eq x.to_list y.to_list ((to_list_length x).trans (to_list_length y).symm) end zip_with end vector
c29eb66693743328859a4a5263e6754b06baa0ff
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/order/locally_finite.lean
2a71fef888958d9665a82909ff3ccd1116148a23
[ "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
18,543
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.preimage /-! # Locally finite orders This file defines locally finite orders. A locally finite order is an order for which all bounded intervals are finite. This allows to make sense of `Icc`/`Ico`/`Ioc`/`Ioo` as lists, multisets, or finsets. Further, if the order is bounded above (resp. below), then we can also make sense of the "unbounded" intervals `Ici`/`Ioi` (resp. `Iic`/`Iio`). ## Examples Naturally occurring locally finite orders are `ℕ`, `ℤ`, `ℕ+`, `fin n`, `α × β` the product of two locally finite orders, `α →₀ β` the finitely supported functions to a locally finite order `β`... ## Main declarations In a `locally_finite_order`, * `finset.Icc`: Closed-closed interval as a finset. * `finset.Ico`: Closed-open interval as a finset. Currently only for `ℕ`. * `finset.Ioc`: Open-closed interval as a finset. * `finset.Ioo`: Open-open interval as a finset. * `multiset.Icc`: Closed-closed interval as a multiset. * `multiset.Ico`: Closed-open interval as a multiset. Currently only for `ℕ`. * `multiset.Ioc`: Open-closed interval as a multiset. * `multiset.Ioo`: Open-open interval as a finset. When it's also an `order_top`, * `finset.Ici`: Closed-infinite interval as a finset. * `finset.Ioi`: Open-infinite interval as a finset. * `multiset.Ici`: Closed-infinite interval as a multiset. * `multiset.Ioi`: Open-infinite interval as a multiset. When it's also an `order_bot`, * `finset.Iic`: Infinite-open interval as a finset. * `finset.Iio`: Infinite-closed interval as a finset. * `multiset.Iic`: Infinite-open interval as a multiset. * `multiset.Iio`: Infinite-closed interval as a multiset. ## Instances A `locally_finite_order` instance can be built * for a subtype of a locally finite order. See `subtype.locally_finite_order`. * for the product of two locally finite orders. See `prod.locally_finite_order`. * for any fintype (but it is noncomputable). See `fintype.to_locally_finite_order`. * from a definition of `finset.Icc` alone. See `locally_finite_order.of_Icc`. * by pulling back `locally_finite_order β` through an order embedding `f : α →o β`. See `order_embedding.locally_finite_order`. ## TODO `finset.Ico` and `multiset.Ico` haven't been generalized yet. All of `data.finset.intervals` and `data.multiset.intervals` should be generalized. Provide the `locally_finite_order` instance for `lex α β` where `locally_finite_order α` and `fintype β`. Provide the `locally_finite_order` instance for `α →₀ β` where `β` is locally finite. Provide the `locally_finite_order` instance for `Π₀ i, β i` where all the `β i` are locally finite. From `linear_order α`, `no_top_order α`, `locally_finite_order α`, we can also define an order isomorphism `α ≃ ℕ` or `α ≃ ℤ`, depending on whether we have `order_bot α` or `no_bot_order α` and `nonempty α`. When `order_bot α`, we can match `a : α` to `(Iio a).card`. Once we have the `succ_order` typeclass (any non-top element has a least greater element), we can provide `succ_order α` from `linear_order α` and `locally_finite_order α` using ```lean lemma exists_min_greater [linear_order α] [locally_finite_order α] {x ub : α} (hx : x < ub) : ∃ lub, x < lub ∧ ∀ y, x < y → lub ≤ y := begin -- very non golfed have h : (finset.Ioc x ub).nonempty := ⟨ub, finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩⟩, use finset.min' (finset.Ioc x ub) h, split, { have := finset.min'_mem _ h, simp * at * }, rintro y hxy, obtain hy | hy := le_total y ub, apply finset.min'_le, simp * at *, exact (finset.min'_le _ _ (finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩)).trans hy, end ``` Note that the converse is not true. Consider `{-2^z | z : ℤ} ∪ {2^z | z : ℤ}`. Any element has a successor (and actually a predecessor as well), so it is a `succ_order`, but it's not locally finite as `Icc (-1) 1` is infinite. -/ open finset /-- A locally finite order is an order where bounded intervals are finite. When you don't care too much about definitional equality, you can use `locally_finite_order.of_Icc` or `locally_finite_order.of_finite_Icc` to build a locally finite order from just `finset.Icc`. -/ class locally_finite_order (α : Type*) [preorder α] := (finset_Icc : α → α → finset α) (finset_Ico : α → α → finset α) (finset_Ioc : α → α → finset α) (finset_Ioo : α → α → finset α) (finset_mem_Icc : ∀ a b x : α, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) (finset_mem_Ico : ∀ a b x : α, x ∈ finset_Ico a b ↔ a ≤ x ∧ x < b) (finset_mem_Ioc : ∀ a b x : α, x ∈ finset_Ioc a b ↔ a < x ∧ x ≤ b) (finset_mem_Ioo : ∀ a b x : α, x ∈ finset_Ioo a b ↔ a < x ∧ x < b) /-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `decidable_rel (≤)` but only `preorder`. -/ def locally_finite_order.of_Icc' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)] (finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) : locally_finite_order α := { finset_Icc := finset_Icc, finset_Ico := λ a b, (finset_Icc a b).filter (λ x, ¬b ≤ x), finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a), finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a ∧ ¬b ≤ x), finset_mem_Icc := mem_Icc, finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_not_le], finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_not_le], finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_not_le, lt_iff_le_not_le] } /-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `partial_order` but only `decidable_eq`. -/ def locally_finite_order.of_Icc (α : Type*) [partial_order α] [decidable_eq α] (finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) : locally_finite_order α := { finset_Icc := finset_Icc, finset_Ico := λ a b, (finset_Icc a b).filter (λ x, x ≠ b), finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, a ≠ x), finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, a ≠ x ∧ x ≠ b), finset_mem_Icc := mem_Icc, finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_and_ne], finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_and_ne], finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_and_ne, lt_iff_le_and_ne] } variables {α β : Type*} /-! ### Intervals as finsets -/ namespace finset section preorder variables [preorder α] [locally_finite_order α] /-- The finset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a finset. -/ def Icc (a b : α) : finset α := locally_finite_order.finset_Icc a b -- TODO@Yaël: Nuke `data.finset.intervals` and redefine `finset.Ico` here /-- The finset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a finset. -/ def Ioc (a b : α) : finset α := locally_finite_order.finset_Ioc a b /-- The finset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a finset. -/ def Ioo (a b : α) : finset α := locally_finite_order.finset_Ioo a b @[simp] lemma mem_Icc {a b x : α} : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := locally_finite_order.finset_mem_Icc a b x @[simp] lemma mem_Ioc {a b x : α} : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := locally_finite_order.finset_mem_Ioc a b x @[simp] lemma mem_Ioo {a b x : α} : x ∈ Ioo a b ↔ a < x ∧ x < b := locally_finite_order.finset_mem_Ioo a b x @[simp, norm_cast] lemma coe_Icc (a b : α) : (Icc a b : set α) = set.Icc a b := by { ext, rw [mem_coe, mem_Icc, set.mem_Icc] } @[simp, norm_cast] lemma coe_Ioc (a b : α) : (Ioc a b : set α) = set.Ioc a b := by { ext, rw [mem_coe, mem_Ioc, set.mem_Ioc] } @[simp, norm_cast] lemma coe_Ioo (a b : α) : (Ioo a b : set α) = set.Ioo a b := by { ext, rw [mem_coe, mem_Ioo, set.mem_Ioo] } end preorder section order_top variables [order_top α] [locally_finite_order α] /-- The finset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a finset. -/ def Ici (a : α) : finset α := Icc a ⊤ /-- The finset of elements `x` such that `a < x`. Basically `set.Ioi a` as a finset. -/ def Ioi (a : α) : finset α := Ioc a ⊤ lemma Ici_eq_Icc (a : α) : Ici a = Icc a ⊤ := rfl lemma Ioi_eq_Ioc (a : α) : Ioi a = Ioc a ⊤ := rfl @[simp, norm_cast] lemma coe_Ici (a : α) : (Ici a : set α) = set.Ici a := by rw [Ici, coe_Icc, set.Icc_top] @[simp, norm_cast] lemma coe_Ioi (a : α) : (Ioi a : set α) = set.Ioi a := by rw [Ioi, coe_Ioc, set.Ioc_top] @[simp] lemma mem_Ici {a x : α} : x ∈ Ici a ↔ a ≤ x := by rw [←set.mem_Ici, ←coe_Ici, mem_coe] @[simp] lemma mem_Ioi {a x : α} : x ∈ Ioi a ↔ a < x := by rw [←set.mem_Ioi, ←coe_Ioi, mem_coe] end order_top section order_bot variables [order_bot α] [locally_finite_order α] /-- The finset of elements `x` such that `x ≤ b`. Basically `set.Iic b` as a finset. -/ def Iic (b : α) : finset α := Icc ⊥ b -- TODO@Yaël: Define `finset.Iio` here lemma Iic_eq_Icc : Iic = Icc (⊥ : α) := rfl @[simp, norm_cast] lemma coe_Iic (b : α) : (Iic b : set α) = set.Iic b := by rw [Iic, coe_Icc, set.Icc_bot] @[simp] lemma mem_Iic {b x : α} : x ∈ Iic b ↔ x ≤ b := by rw [←set.mem_Iic, ←coe_Iic, mem_coe] end order_bot end finset /-! ### Intervals as multisets -/ namespace multiset section preorder variables [preorder α] [locally_finite_order α] /-- The multiset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a multiset. -/ def Icc (a b : α) : multiset α := (finset.Icc a b).val -- TODO@Yaël: Nuke `data.multiset.intervals` and redefine `multiset.Ico` here /-- The multiset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a multiset. -/ def Ioc (a b : α) : multiset α := (finset.Ioc a b).val /-- The multiset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a multiset. -/ def Ioo (a b : α) : multiset α := (finset.Ioo a b).val @[simp] lemma mem_Icc {a b x : α} : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := by rw [Icc, ←finset.mem_def, finset.mem_Icc] @[simp] lemma mem_Ioc {a b x : α} : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := by rw [Ioc, ←finset.mem_def, finset.mem_Ioc] @[simp] lemma mem_Ioo {a b x : α} : x ∈ Ioo a b ↔ a < x ∧ x < b := by rw [Ioo, ←finset.mem_def, finset.mem_Ioo] end preorder section order_top variables [order_top α] [locally_finite_order α] /-- The multiset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a multiset. -/ def Ici (a : α) : multiset α := (finset.Ici a).val /-- The multiset of elements `x` such that `a < x`. Basically `set.Ioi a` as a multiset. -/ def Ioi (a : α) : multiset α := (finset.Ioi a).val @[simp] lemma mem_Ici {a x : α} : x ∈ Ici a ↔ a ≤ x := by rw [Ici, ←finset.mem_def, finset.mem_Ici] @[simp] lemma mem_Ioi {a x : α} : x ∈ Ioi a ↔ a < x := by rw [Ioi, ←finset.mem_def, finset.mem_Ioi] end order_top section order_bot variables [order_bot α] [locally_finite_order α] /-- The multiset of elements `x` such that `x ≤ b`. Basically `set.Iic b` as a multiset. -/ def Iic (b : α) : multiset α := (finset.Iic b).val -- TODO@Yaël: Define `multiset.Iio` here @[simp] lemma mem_Iic {b x : α} : x ∈ Iic b ↔ x ≤ b := by rw [Iic, ←finset.mem_def, finset.mem_Iic] end order_bot end multiset /-! ### Finiteness of `set` intervals -/ namespace set section preorder variables [preorder α] [locally_finite_order α] (a b : α) instance fintype_Icc : fintype (Icc a b) := fintype.of_finset (finset.Icc a b) (λ x, by rw [finset.mem_Icc, mem_Icc]) instance fintype_Ioc : fintype (Ioc a b) := fintype.of_finset (finset.Ioc a b) (λ x, by rw [finset.mem_Ioc, mem_Ioc]) instance fintype_Ioo : fintype (Ioo a b) := fintype.of_finset (finset.Ioo a b) (λ x, by rw [finset.mem_Ioo, mem_Ioo]) lemma finite_Icc : (Icc a b).finite := ⟨set.fintype_Icc a b⟩ lemma finite_Ioc : (Ioc a b).finite := ⟨set.fintype_Ioc a b⟩ lemma finite_Ioo : (Ioo a b).finite := ⟨set.fintype_Ioo a b⟩ end preorder section order_top variables [order_top α] [locally_finite_order α] (a : α) instance fintype_Ici : fintype (Ici a) := fintype.of_finset (finset.Ici a) (λ x, by rw [finset.mem_Ici, mem_Ici]) instance fintype_Ioi : fintype (Ioi a) := fintype.of_finset (finset.Ioi a) (λ x, by rw [finset.mem_Ioi, mem_Ioi]) lemma finite_Ici : (Ici a).finite := ⟨set.fintype_Ici a⟩ lemma finite_Ioi : (Ioi a).finite := ⟨set.fintype_Ioi a⟩ end order_top section order_bot variables [order_bot α] [locally_finite_order α] (b : α) instance fintype_Iic : fintype (Iic b) := fintype.of_finset (finset.Iic b) (λ x, by rw [finset.mem_Iic, mem_Iic]) lemma finite_Iic : (Iic b).finite := ⟨set.fintype_Iic b⟩ end order_bot end set /-! ### Instances -/ open finset section preorder variables [preorder α] /-- A noncomputable constructor from the finiteness of all closed intervals. -/ noncomputable def locally_finite_order.of_finite_Icc (h : ∀ a b : α, (set.Icc a b).finite) : locally_finite_order α := @locally_finite_order.of_Icc' α _ (classical.dec_rel _) (λ a b, (h a b).to_finset) (λ a b x, by rw [set.finite.mem_to_finset, set.mem_Icc]) /-- A fintype is noncomputably a locally finite order. -/ noncomputable def fintype.to_locally_finite_order [fintype α] : locally_finite_order α := { finset_Icc := λ a b, (set.finite.of_fintype (set.Icc a b)).to_finset, finset_Ico := λ a b, (set.finite.of_fintype (set.Ico a b)).to_finset, finset_Ioc := λ a b, (set.finite.of_fintype (set.Ioc a b)).to_finset, finset_Ioo := λ a b, (set.finite.of_fintype (set.Ioo a b)).to_finset, finset_mem_Icc := λ a b x, by rw [set.finite.mem_to_finset, set.mem_Icc], finset_mem_Ico := λ a b x, by rw [set.finite.mem_to_finset, set.mem_Ico], finset_mem_Ioc := λ a b x, by rw [set.finite.mem_to_finset, set.mem_Ioc], finset_mem_Ioo := λ a b x, by rw [set.finite.mem_to_finset, set.mem_Ioo] } instance : subsingleton (locally_finite_order α) := subsingleton.intro (λ h₀ h₁, begin cases h₀, cases h₁, have hIcc : h₀_finset_Icc = h₁_finset_Icc, { ext a b x, rw [h₀_finset_mem_Icc, h₁_finset_mem_Icc] }, have hIco : h₀_finset_Ico = h₁_finset_Ico, { ext a b x, rw [h₀_finset_mem_Ico, h₁_finset_mem_Ico] }, have hIoc : h₀_finset_Ioc = h₁_finset_Ioc, { ext a b x, rw [h₀_finset_mem_Ioc, h₁_finset_mem_Ioc] }, have hIoo : h₀_finset_Ioo = h₁_finset_Ioo, { ext a b x, rw [h₀_finset_mem_Ioo, h₁_finset_mem_Ioo] }, simp_rw [hIcc, hIco, hIoc, hIoo], end) variables [preorder β] [locally_finite_order β] -- Should this be called `locally_finite_order.lift`? /-- Given an order embedding `α ↪o β`, pulls back the `locally_finite_order` on `β` to `α`. -/ noncomputable def order_embedding.locally_finite_order (f : α ↪o β) : locally_finite_order α := { finset_Icc := λ a b, (Icc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ico := λ a b, (locally_finite_order.finset_Ico (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ioc := λ a b, (Ioc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_Ioo := λ a b, (Ioo (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _), finset_mem_Icc := λ a b x, by rw [mem_preimage, mem_Icc, f.le_iff_le, f.le_iff_le], finset_mem_Ico := λ a b x, by rw [mem_preimage,locally_finite_order.finset_mem_Ico, f.le_iff_le, f.lt_iff_lt], finset_mem_Ioc := λ a b x, by rw [mem_preimage, mem_Ioc, f.lt_iff_lt, f.le_iff_le], finset_mem_Ioo := λ a b x, by rw [mem_preimage, mem_Ioo, f.lt_iff_lt, f.lt_iff_lt] } variables [locally_finite_order α] instance [decidable_rel ((≤) : α × β → α × β → Prop)] : locally_finite_order (α × β) := locally_finite_order.of_Icc' (α × β) (λ a b, (Icc a.fst b.fst).product (Icc a.snd b.snd)) (λ a b x, by { rw [mem_product, mem_Icc, mem_Icc, and_and_and_comm], refl }) end preorder /-! #### Subtype of a locally finite order -/ variables [preorder α] [locally_finite_order α] (p : α → Prop) [decidable_pred p] instance : locally_finite_order (subtype p) := { finset_Icc := λ a b, (Icc (a : α) b).subtype p, finset_Ico := λ a b, (locally_finite_order.finset_Ico (a : α) b).subtype p, finset_Ioc := λ a b, (Ioc (a : α) b).subtype p, finset_Ioo := λ a b, (Ioo (a : α) b).subtype p, finset_mem_Icc := λ a b x, by simp_rw [finset.mem_subtype, mem_Icc, subtype.coe_le_coe], finset_mem_Ico := λ a b x, by simp_rw [finset.mem_subtype, locally_finite_order.finset_mem_Ico, subtype.coe_le_coe, subtype.coe_lt_coe], finset_mem_Ioc := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioc, subtype.coe_le_coe, subtype.coe_lt_coe], finset_mem_Ioo := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioo, subtype.coe_lt_coe] } variables (a b : subtype p) namespace finset lemma subtype_Icc_eq : Icc a b = (Icc (a : α) b).subtype p := rfl lemma subtype_Ioc_eq : Ioc a b = (Ioc (a : α) b).subtype p := rfl lemma subtype_Ioo_eq : Ioo a b = (Ioo (a : α) b).subtype p := rfl variables (hp : ∀ ⦃a b x⦄, a ≤ x → x ≤ b → p a → p b → p x) include hp lemma map_subtype_embedding_Icc : (Icc a b).map (function.embedding.subtype p) = Icc (a : α) b := begin rw subtype_Icc_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Icc at hx, exact hp hx.1 hx.2 a.prop b.prop, end lemma map_subtype_embedding_Ioc : (Ioc a b).map (function.embedding.subtype p) = Ioc (a : α) b := begin rw subtype_Ioc_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Ioc at hx, exact hp hx.1.le hx.2 a.prop b.prop, end lemma map_subtype_embedding_Ioo : (Ioo a b).map (function.embedding.subtype p) = Ioo (a : α) b := begin rw subtype_Ioo_eq, refine finset.subtype_map_of_mem (λ x hx, _), rw mem_Ioo at hx, exact hp hx.1.le hx.2.le a.prop b.prop, end end finset
d3ee94782243be0f302e19198575c5f4663800b5
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/decl_olean.lean
b26c2c3b1861e47a9c958b301d402e32aa19cb37
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
524
lean
open tactic def g : nat → nat := λ n, 0 meta def show_pos (n : name) : command := do env ← get_env, pos ← returnopt (env^.decl_pos n), olean ← returnopt (env^.decl_olean n) <|> return "current file", trace $ to_string n ++ " was defined at " ++ olean ++ " : " ++ to_string pos.1 ++ ":" ++ to_string pos.2 run_cmd show_pos `add run_cmd show_pos `nat.succ run_cmd show_pos `subsingleton.intro run_cmd show_pos `subsingleton.rec run_cmd show_pos `nat.add run_cmd show_pos `quotient run_cmd show_pos `g
6ebf061dfcb9d9d3e4dff99cb28bd24f29ce5191
d534932ed7c1eba03b537c377a4f8961acd41e99
/lake/lakefile.lean
65dab2277e56e0919c4b9a3b108a8a365dde9224
[ "Apache-2.0" ]
permissive
Adminixtrator/lean4-socket
d7e321d547df6545d0c085d310be8f2c41c44ddb
b313041f2e75f4ad8320ab66d7e2afafd2202318
refs/heads/main
1,692,582,696,753
1,633,439,398,000
1,633,439,523,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
469
lean
import Lake open System Lake DSL def nativeOTarget (pkgDir : FilePath) : FileTarget := oFileTarget (pkgDir / "../build/native/native.o") (pkgDir / "../native/native.c" : FilePath) #[] "gcc" def cLibTarget (pkgDir : FilePath) : FileTarget := staticLibTarget (pkgDir / "../build/native/native.a") #[nativeOTarget pkgDir] package socket (pkgDir) (args) { srcDir := "../" buildDir := "../build" libRoots := #[`Socket] moreLibTargets := #[cLibTarget pkgDir] }