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
122bf84c288aff8ed0b107c2c1e6fe43a2f77446
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/metric_space/completion.lean
8b493174fb7ed4d7d71f8397a8e67502809a3987
[ "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
8,572
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel 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 -/ import topology.uniform_space.completion topology.metric_space.isometry open lattice set filter uniform_space uniform_space.completion noncomputable theory universes u variables {α : Type u} [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 : _) }, { 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 (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}, principal {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} }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, principal {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a 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
cc4f41d5eef0442fac141aa9be18d7aa785bdee5
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/full_subcategory.lean
b6c3038a5e08db9593145c9f42c2b7f2d748eef5
[ "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
3,247
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.fully_faithful namespace category_theory universes v u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section induced /- Induced categories. Given a category D and a function F : C → D from a type C to the objects of D, there is an essentially unique way to give C a category structure such that F becomes a fully faithful functor, namely by taking Hom_C(X, Y) = Hom_D(FX, FY). We call this the category induced from D along F. As a special case, if C is a subtype of D, this produces the full subcategory of D on the objects belonging to C. In general the induced category is equivalent to the full subcategory of D on the image of F. -/ /- It looks odd to make D an explicit argument of `induced_category`, when it is determined by the argument F anyways. The reason to make D explicit is in order to control its syntactic form, so that instances like `induced_category.has_forget₂` (elsewhere) refer to the correct form of D. This is used to set up several algebraic categories like def CommMon : Type (u+1) := induced_category Mon (bundled.map @comm_monoid.to_monoid) -- not `induced_category (bundled monoid) (bundled.map @comm_monoid.to_monoid)`, -- even though `Mon = bundled monoid`! -/ variables {C : Type u₁} (D : Type u₂) [𝒟 : category.{v} D] include 𝒟 variables (F : C → D) include F def induced_category : Type u₁ := C variables {D} instance induced_category.has_coe_to_sort [has_coe_to_sort D] : has_coe_to_sort (induced_category D F) := ⟨_, λ c, ↥(F c)⟩ instance induced_category.category : category.{v} (induced_category D F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } def induced_functor : induced_category D F ⥤ D := { obj := F, map := λ x y f, f } @[simp] lemma induced_functor.obj {X} : (induced_functor F).obj X = F X := rfl @[simp] lemma induced_functor.hom {X Y} {f : X ⟶ Y} : (induced_functor F).map f = f := rfl instance induced_category.full : full (induced_functor F) := { preimage := λ x y f, f } instance induced_category.faithful : faithful (induced_functor F) := {} end induced section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Type u₂} [𝒞 : category.{v} C] include 𝒞 variables (Z : C → Prop) instance full_subcategory : category.{v} {X : C // Z X} := induced_category.category subtype.val def full_subcategory_inclusion : {X : C // Z X} ⥤ C := induced_functor subtype.val @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.val := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.ful : full (full_subcategory_inclusion Z) := induced_category.full subtype.val instance full_subcategory.faithful : faithful (full_subcategory_inclusion Z) := induced_category.faithful subtype.val end full_subcategory end category_theory
5cc49bf3069ec2d02fc7c141e71e48ba7f0b188f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Conv/Congr.lean
2fd218952e2d9c36a7acbb634fdb63a3edfb81c4
[ "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
8,092
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Congr import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta private def congrImplies (mvarId : MVarId) : MetaM (List MVarId) := do let [mvarId₁, mvarId₂, _, _] ← mvarId.apply (← mkConstWithFreshMVarLevels ``implies_congr) | throwError "'apply implies_congr' unexpected result" let mvarId₁ ← markAsConvGoal mvarId₁ let mvarId₂ ← markAsConvGoal mvarId₂ return [mvarId₁, mvarId₂] private def isImplies (e : Expr) : MetaM Bool := if e.isArrow then isProp e.bindingDomain! <&&> isProp e.bindingBody! else return false def congr (mvarId : MVarId) (addImplicitArgs := false) (nameSubgoals := true) : MetaM (List (Option MVarId)) := mvarId.withContext do let origTag ← mvarId.getTag let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if (← isImplies lhs) then return (← congrImplies mvarId).map Option.some else if lhs.isApp then let funInfo ← getFunInfo lhs.getAppFn let args := lhs.getAppArgs let some congrThm ← mkCongrSimp? lhs.getAppFn (subsingletonInstImplicitRhs := false) | throwError "'congr' conv tactic failed to create congruence theorem" unless args.size == congrThm.argKinds.size do throwError "'congr' conv tactic failed, unexpected number of arguments in congruence theorem" let mut proof := congrThm.proof let mut mvarIdsNew := #[] let mut mvarIdsNewInsts := #[] for i in [:args.size] do let arg := args[i]! let argInfo := funInfo.paramInfo[i]! match congrThm.argKinds[i]! with | .fixed | .cast => proof := mkApp proof arg; if addImplicitArgs || argInfo.isExplicit then mvarIdsNew := mvarIdsNew.push none | .eq => if addImplicitArgs || argInfo.isExplicit then let tag ← if nameSubgoals then pure (appendTag origTag (← whnf (← inferType proof)).bindingName!) else pure origTag let (rhs, mvarNew) ← mkConvGoalFor arg tag proof := mkApp3 proof arg rhs mvarNew mvarIdsNew := mvarIdsNew.push (some mvarNew.mvarId!) else proof := mkApp3 proof arg arg (← mkEqRefl arg) | .subsingletonInst => proof := mkApp proof arg let rhs ← mkFreshExprMVar (← whnf (← inferType proof)).bindingDomain! proof := mkApp proof rhs mvarIdsNewInsts := mvarIdsNewInsts.push (some rhs.mvarId!) | .heq | .fixedNoParam => unreachable! let some (_, _, rhs') := (← whnf (← inferType proof)).eq? | throwError "'congr' conv tactic failed, equality expected" unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'congr' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" mvarId.assign proof return mvarIdsNew.toList ++ mvarIdsNewInsts.toList else throwError "invalid 'congr' conv tactic, application or implication expected{indentExpr lhs}" @[builtin_tactic Lean.Parser.Tactic.Conv.congr] def evalCongr : Tactic := fun _ => do replaceMainGoal <| List.filterMap id (← congr (← getMainGoal)) private def selectIdx (tacticName : String) (mvarIds : List (Option MVarId)) (i : Int) : TacticM Unit := do if i >= 0 then let i := i.toNat if h : i < mvarIds.length then for mvarId? in mvarIds, j in [:mvarIds.length] do match mvarId? with | none => pure () | some mvarId => if i != j then mvarId.refl match mvarIds[i] with | none => throwError "cannot select argument" | some mvarId => replaceMainGoal [mvarId] return () throwError "invalid '{tacticName}' conv tactic, application has only {mvarIds.length} (nondependent) argument(s)" @[builtin_tactic Lean.Parser.Tactic.Conv.skip] def evalSkip : Tactic := fun _ => pure () @[builtin_tactic Lean.Parser.Tactic.Conv.lhs] def evalLhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) (nameSubgoals := false) selectIdx "lhs" mvarIds ((mvarIds.length : Int) - 2) @[builtin_tactic Lean.Parser.Tactic.Conv.rhs] def evalRhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) (nameSubgoals := false) selectIdx "rhs" mvarIds ((mvarIds.length : Int) - 1) @[builtin_tactic Lean.Parser.Tactic.Conv.arg] def evalArg : Tactic := fun stx => do match stx with | `(conv| arg $[@%$tk?]? $i:num) => let i := i.getNat if i == 0 then throwError "invalid 'arg' conv tactic, index must be greater than 0" let i := i - 1 let mvarIds ← congr (← getMainGoal) (addImplicitArgs := tk?.isSome) (nameSubgoals := false) selectIdx "arg" mvarIds i | _ => throwUnsupportedSyntax def extLetBodyCongr? (mvarId : MVarId) (lhs rhs : Expr) : MetaM (Option MVarId) := do match lhs with | .letE n t v b _ => let u₁ ← getLevel t let f := mkLambda n .default t b unless (← isTypeCorrect f) do throwError "failed to abstract let-expression, result is not type correct" let (β, u₂, f') ← withLocalDeclD n t fun a => do let type ← inferType (mkApp f a) let β ← mkLambdaFVars #[a] type let u₂ ← getLevel type let rhsBody ← mkFreshExprMVar type let f' ← mkLambdaFVars #[a] rhsBody let rhs' := mkLet n t v f'.bindingBody! unless (← isDefEq rhs rhs') do throwError "failed to go inside let-declaration, type error" return (β, u₂, f') let (arg, mvarId') ← withLocalDeclD n t fun x => do let eqLhs := f.beta #[x] let eqRhs := f'.beta #[x] let mvarNew ← mkFreshExprSyntheticOpaqueMVar (← mkEq eqLhs eqRhs) let arg ← mkLambdaFVars #[x] mvarNew return (arg, mvarNew.mvarId!) let val := mkApp6 (mkConst ``let_body_congr [u₁, u₂]) t β f f' v arg mvarId.assign val return some (← markAsConvGoal mvarId') | _ => return none private def extCore (mvarId : MVarId) (userName? : Option Name) : MetaM MVarId := mvarId.withContext do let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if let .forallE n d b bi := lhs then let u ← getLevel d let p : Expr := .lam n d b bi let userName ← if let some userName := userName? then pure userName else mkFreshBinderNameForTactic n let (q, h, mvarNew) ← withLocalDecl userName bi d fun a => do let pa := b.instantiate1 a let (qa, mvarNew) ← mkConvGoalFor pa let q ← mkLambdaFVars #[a] qa let h ← mkLambdaFVars #[a] mvarNew let rhs' ← mkForallFVars #[a] qa unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'ext' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" return (q, h, mvarNew) let proof := mkApp4 (mkConst ``forall_congr [u]) d p q h mvarId.assign proof return mvarNew.mvarId! else if let some mvarId ← extLetBodyCongr? mvarId lhs rhs then return mvarId else let lhsType ← whnfD (← inferType lhs) unless lhsType.isForall do throwError "invalid 'ext' conv tactic, function or arrow expected{indentD m!"{lhs} : {lhsType}"}" let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``funext) | throwError "'apply funext' unexpected result" let userNames := if let some userName := userName? then [userName] else [] let (_, mvarId) ← mvarId.introN 1 userNames markAsConvGoal mvarId private def ext (userName? : Option Name) : TacticM Unit := do replaceMainGoal [← extCore (← getMainGoal) userName?] @[builtin_tactic Lean.Parser.Tactic.Conv.ext] def evalExt : Tactic := fun stx => do let ids := stx[1].getArgs if ids.isEmpty then ext none else for id in ids do withRef id <| ext id.getId end Lean.Elab.Tactic.Conv
01b2abf954d09ad074ec0db447a6b54ec1a0cce8
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/ordered_group.hlean
7d81fe1d04870e204bd993bda712c843838cea20
[ "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
21,538
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Partially ordered additive groups, modeled on Isabelle's library. We could refine the structures, but we would have to declare more inheritance paths. Ported from the standard library -/ import .order .group open core namespace algebra variable {A : Type} /- partially ordered monoids, such as the natural numbers -/ structure ordered_cancel_comm_monoid [class] (A : Type) extends add_comm_monoid A, add_left_cancel_semigroup A, add_right_cancel_semigroup A, order_pair A := (add_le_add_left : Πa b, le a b → Πc, le (add c a) (add c b)) (le_of_add_le_add_left : Πa b c, le (add a b) (add a c) → le b c) section variables [s : ordered_cancel_comm_monoid A] variables {a b c d e : A} include s definition add_le_add_left (H : a ≤ b) (c : A) : c + a ≤ c + b := !ordered_cancel_comm_monoid.add_le_add_left H c definition add_le_add_right (H : a ≤ b) (c : A) : a + c ≤ b + c := (add.comm c a) ▸ (add.comm c b) ▸ (add_le_add_left H c) definition add_le_add (Hab : a ≤ b) (Hcd : c ≤ d) : a + c ≤ b + d := le.trans (add_le_add_right Hab c) (add_le_add_left Hcd b) definition add_lt_add_left (H : a < b) (c : A) : c + a < c + b := have H1 : c + a ≤ c + b, from add_le_add_left (le_of_lt H) c, have H2 : c + a ≠ c + b, from take H3 : c + a = c + b, have H4 : a = b, from add.left_cancel H3, ne_of_lt H H4, lt_of_le_of_ne H1 H2 definition add_lt_add_right (H : a < b) (c : A) : a + c < b + c := begin rewrite [add.comm, {b + _}add.comm], exact (add_lt_add_left H c) end definition le_add_of_nonneg_right (H : b ≥ 0) : a ≤ a + b := begin have H1 : a + b ≥ a + 0, from add_le_add_left H a, rewrite add_zero at H1, exact H1 end definition le_add_of_nonneg_left (H : b ≥ 0) : a ≤ b + a := begin have H1 : 0 + a ≤ b + a, from add_le_add_right H a, rewrite zero_add at H1, exact H1 end definition add_lt_add (Hab : a < b) (Hcd : c < d) : a + c < b + d := lt.trans (add_lt_add_right Hab c) (add_lt_add_left Hcd b) definition add_lt_add_of_le_of_lt (Hab : a ≤ b) (Hcd : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right Hab c) (add_lt_add_left Hcd b) definition add_lt_add_of_lt_of_le (Hab : a < b) (Hcd : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right Hab c) (add_le_add_left Hcd b) definition lt_add_of_pos_right (H : b > 0) : a < a + b := !add_zero ▸ add_lt_add_left H a definition lt_add_of_pos_left (H : b > 0) : a < b + a := !zero_add ▸ add_lt_add_right H a -- here we start using le_of_add_le_add_left. definition le_of_add_le_add_left (H : a + b ≤ a + c) : b ≤ c := !ordered_cancel_comm_monoid.le_of_add_le_add_left H definition le_of_add_le_add_right (H : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rewrite [add.comm, {b + _}add.comm], exact H end) definition lt_of_add_lt_add_left (H : a + b < a + c) : b < c := have H1 : b ≤ c, from le_of_add_le_add_left (le_of_lt H), have H2 : b ≠ c, from assume H3 : b = c, lt.irrefl _ (H3 ▸ H), lt_of_le_of_ne H1 H2 definition lt_of_add_lt_add_right (H : a + b < c + b) : a < c := lt_of_add_lt_add_left ((add.comm a b) ▸ (add.comm c b) ▸ H) definition add_le_add_left_iff (a b c : A) : a + b ≤ a + c ↔ b ≤ c := iff.intro le_of_add_le_add_left (assume H, add_le_add_left H _) definition add_le_add_right_iff (a b c : A) : a + b ≤ c + b ↔ a ≤ c := iff.intro le_of_add_le_add_right (assume H, add_le_add_right H _) definition add_lt_add_left_iff (a b c : A) : a + b < a + c ↔ b < c := iff.intro lt_of_add_lt_add_left (assume H, add_lt_add_left H _) definition add_lt_add_right_iff (a b c : A) : a + b < c + b ↔ a < c := iff.intro lt_of_add_lt_add_right (assume H, add_lt_add_right H _) -- here we start using properties of zero. definition add_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a + b := !zero_add ▸ (add_le_add Ha Hb) definition add_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add Ha Hb) definition add_pos_of_pos_of_nonneg (Ha : 0 < a) (Hb : 0 ≤ b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) definition add_pos_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) definition add_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : a + b ≤ 0 := !zero_add ▸ (add_le_add Ha Hb) definition add_neg (Ha : a < 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add Ha Hb) definition add_neg_of_neg_of_nonpos (Ha : a < 0) (Hb : b ≤ 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) definition add_neg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) -- TODO: add nonpos version (will be easier with simplifier) definition add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : a + b = 0 ↔ a = 0 × b = 0 := iff.intro (assume Hab : a + b = 0, have Ha' : a ≤ 0, from calc a = a + 0 : by rewrite add_zero ... ≤ a + b : add_le_add_left Hb ... = 0 : Hab, have Haz : a = 0, from le.antisymm Ha' Ha, have Hb' : b ≤ 0, from calc b = 0 + b : by rewrite zero_add ... ≤ a + b : add_le_add_right Ha ... = 0 : Hab, have Hbz : b = 0, from le.antisymm Hb' Hb, pair Haz Hbz) (assume Hab : a = 0 × b = 0, match Hab with | pair Ha' Hb' := by rewrite [Ha', Hb', add_zero] end) definition le_add_of_nonneg_of_le (Ha : 0 ≤ a) (Hbc : b ≤ c) : b ≤ a + c := !zero_add ▸ add_le_add Ha Hbc definition le_add_of_le_of_nonneg (Hbc : b ≤ c) (Ha : 0 ≤ a) : b ≤ c + a := !add_zero ▸ add_le_add Hbc Ha definition lt_add_of_pos_of_le (Ha : 0 < a) (Hbc : b ≤ c) : b < a + c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc definition lt_add_of_le_of_pos (Hbc : b ≤ c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha definition add_le_of_nonpos_of_le (Ha : a ≤ 0) (Hbc : b ≤ c) : a + b ≤ c := !zero_add ▸ add_le_add Ha Hbc definition add_le_of_le_of_nonpos (Hbc : b ≤ c) (Ha : a ≤ 0) : b + a ≤ c := !add_zero ▸ add_le_add Hbc Ha definition add_lt_of_neg_of_le (Ha : a < 0) (Hbc : b ≤ c) : a + b < c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc definition add_lt_of_le_of_neg (Hbc : b ≤ c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha definition lt_add_of_nonneg_of_lt (Ha : 0 ≤ a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc definition lt_add_of_lt_of_nonneg (Hbc : b < c) (Ha : 0 ≤ a) : b < c + a := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha definition lt_add_of_pos_of_lt (Ha : 0 < a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add Ha Hbc definition lt_add_of_lt_of_pos (Hbc : b < c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add Hbc Ha definition add_lt_of_nonpos_of_lt (Ha : a ≤ 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc definition add_lt_of_lt_of_nonpos (Hbc : b < c) (Ha : a ≤ 0) : b + a < c := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha definition add_lt_of_neg_of_lt (Ha : a < 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add Ha Hbc definition add_lt_of_lt_of_neg (Hbc : b < c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add Hbc Ha end -- TODO: add properties of max and min /- partially ordered groups -/ structure ordered_comm_group [class] (A : Type) extends add_comm_group A, order_pair A := (add_le_add_left : Πa b, le a b → Πc, le (add c a) (add c b)) definition ordered_comm_group.le_of_add_le_add_left [s : ordered_comm_group A] {a b c : A} (H : a + b ≤ a + c) : b ≤ c := assert H' : -a + (a + b) ≤ -a + (a + c), from ordered_comm_group.add_le_add_left _ _ H _, by rewrite *neg_add_cancel_left at H'; exact H' definition ordered_comm_group.to_ordered_cancel_comm_monoid [instance] [reducible] [s : ordered_comm_group A] : ordered_cancel_comm_monoid A := ⦃ ordered_cancel_comm_monoid, s, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @ordered_comm_group.le_of_add_le_add_left A _ ⦄ section variables [s : ordered_comm_group A] (a b c d e : A) include s definition neg_le_neg {a b : A} (H : a ≤ b) : -b ≤ -a := have H1 : 0 ≤ -a + b, from !add.left_inv ▸ !(add_le_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_le_add_right H1 (-b) definition le_of_neg_le_neg {a b : A} (H : -b ≤ -a) : a ≤ b := neg_neg a ▸ neg_neg b ▸ neg_le_neg H definition neg_le_neg_iff_le : -a ≤ -b ↔ b ≤ a := iff.intro le_of_neg_le_neg neg_le_neg definition nonneg_of_neg_nonpos {a : A} (H : -a ≤ 0) : 0 ≤ a := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) definition neg_nonpos_of_nonneg {a : A} (H : 0 ≤ a) : -a ≤ 0 := neg_zero ▸ neg_le_neg H definition neg_nonpos_iff_nonneg : -a ≤ 0 ↔ 0 ≤ a := iff.intro nonneg_of_neg_nonpos neg_nonpos_of_nonneg definition nonpos_of_neg_nonneg {a : A} (H : 0 ≤ -a) : a ≤ 0 := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) definition neg_nonneg_of_nonpos {a : A} (H : a ≤ 0) : 0 ≤ -a := neg_zero ▸ neg_le_neg H definition neg_nonneg_iff_nonpos : 0 ≤ -a ↔ a ≤ 0 := iff.intro nonpos_of_neg_nonneg neg_nonneg_of_nonpos definition neg_lt_neg {a b : A} (H : a < b) : -b < -a := have H1 : 0 < -a + b, from !add.left_inv ▸ !(add_lt_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_lt_add_right H1 (-b) definition lt_of_neg_lt_neg {a b : A} (H : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg H definition neg_lt_neg_iff_lt : -a < -b ↔ b < a := iff.intro lt_of_neg_lt_neg neg_lt_neg definition pos_of_neg_neg {a : A} (H : -a < 0) : 0 < a := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) definition neg_neg_of_pos {a : A} (H : 0 < a) : -a < 0 := neg_zero ▸ neg_lt_neg H definition neg_neg_iff_pos : -a < 0 ↔ 0 < a := iff.intro pos_of_neg_neg neg_neg_of_pos definition neg_of_neg_pos {a : A} (H : 0 < -a) : a < 0 := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) definition neg_pos_of_neg {a : A} (H : a < 0) : 0 < -a := neg_zero ▸ neg_lt_neg H definition neg_pos_iff_neg : 0 < -a ↔ a < 0 := iff.intro neg_of_neg_pos neg_pos_of_neg definition le_neg_iff_le_neg : a ≤ -b ↔ b ≤ -a := !neg_neg ▸ !neg_le_neg_iff_le definition neg_le_iff_neg_le : -a ≤ b ↔ -b ≤ a := !neg_neg ▸ !neg_le_neg_iff_le definition lt_neg_iff_lt_neg : a < -b ↔ b < -a := !neg_neg ▸ !neg_lt_neg_iff_lt definition neg_lt_iff_neg_lt : -a < b ↔ -b < a := !neg_neg ▸ !neg_lt_neg_iff_lt definition sub_nonneg_iff_le : 0 ≤ a - b ↔ b ≤ a := !sub_self ▸ !add_le_add_right_iff definition sub_nonpos_iff_le : a - b ≤ 0 ↔ a ≤ b := !sub_self ▸ !add_le_add_right_iff definition sub_pos_iff_lt : 0 < a - b ↔ b < a := !sub_self ▸ !add_lt_add_right_iff definition sub_neg_iff_lt : a - b < 0 ↔ a < b := !sub_self ▸ !add_lt_add_right_iff definition add_le_iff_le_neg_add : a + b ≤ c ↔ b ≤ -a + c := have H: a + b ≤ c ↔ -a + (a + b) ≤ -a + c, from iff.symm (!add_le_add_left_iff), !neg_add_cancel_left ▸ H definition add_le_iff_le_sub_left : a + b ≤ c ↔ b ≤ c - a := by rewrite [sub_eq_add_neg, {c+_}add.comm]; apply add_le_iff_le_neg_add definition add_le_iff_le_sub_right : a + b ≤ c ↔ a ≤ c - b := have H: a + b ≤ c ↔ a + b - b ≤ c - b, from iff.symm (!add_le_add_right_iff), !add_neg_cancel_right ▸ H definition le_add_iff_neg_add_le : a ≤ b + c ↔ -b + a ≤ c := assert H: a ≤ b + c ↔ -b + a ≤ -b + (b + c), from iff.symm (!add_le_add_left_iff), by rewrite neg_add_cancel_left at H; exact H definition le_add_iff_sub_left_le : a ≤ b + c ↔ a - b ≤ c := by rewrite [sub_eq_add_neg, {a+_}add.comm]; apply le_add_iff_neg_add_le definition le_add_iff_sub_right_le : a ≤ b + c ↔ a - c ≤ b := assert H: a ≤ b + c ↔ a - c ≤ b + c - c, from iff.symm (!add_le_add_right_iff), by rewrite add_neg_cancel_right at H; exact H definition add_lt_iff_lt_neg_add_left : a + b < c ↔ b < -a + c := assert H: a + b < c ↔ -a + (a + b) < -a + c, from iff.symm (!add_lt_add_left_iff), begin rewrite neg_add_cancel_left at H, exact H end definition add_lt_iff_lt_neg_add_right : a + b < c ↔ a < -b + c := by rewrite add.comm; apply add_lt_iff_lt_neg_add_left definition add_lt_iff_lt_sub_left : a + b < c ↔ b < c - a := begin rewrite [sub_eq_add_neg, {c+_}add.comm], apply add_lt_iff_lt_neg_add_left end definition add_lt_add_iff_lt_sub_right : a + b < c ↔ a < c - b := assert H: a + b < c ↔ a + b - b < c - b, from iff.symm (!add_lt_add_right_iff), by rewrite add_neg_cancel_right at H; exact H definition lt_add_iff_neg_add_lt_left : a < b + c ↔ -b + a < c := assert H: a < b + c ↔ -b + a < -b + (b + c), from iff.symm (!add_lt_add_left_iff), by rewrite neg_add_cancel_left at H; exact H definition lt_add_iff_neg_add_lt_right : a < b + c ↔ -c + a < b := by rewrite add.comm; apply lt_add_iff_neg_add_lt_left definition lt_add_iff_sub_lt_left : a < b + c ↔ a - b < c := by rewrite [sub_eq_add_neg, {a + _}add.comm]; apply lt_add_iff_neg_add_lt_left definition lt_add_iff_sub_lt_right : a < b + c ↔ a - c < b := by rewrite add.comm; apply lt_add_iff_sub_lt_left -- TODO: the Isabelle library has varations on a + b ≤ b ↔ a ≤ 0 definition le_iff_le_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a ≤ b ↔ c ≤ d := calc a ≤ b ↔ a - b ≤ 0 : iff.symm (sub_nonpos_iff_le a b) ... = (c - d ≤ 0) : by rewrite H ... ↔ c ≤ d : sub_nonpos_iff_le c d definition lt_iff_lt_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a < b ↔ c < d := calc a < b ↔ a - b < 0 : iff.symm (sub_neg_iff_lt a b) ... = (c - d < 0) : by rewrite H ... ↔ c < d : sub_neg_iff_lt c d definition sub_le_sub_left {a b : A} (H : a ≤ b) (c : A) : c - b ≤ c - a := add_le_add_left (neg_le_neg H) c definition sub_le_sub_right {a b : A} (H : a ≤ b) (c : A) : a - c ≤ b - c := add_le_add_right H (-c) definition sub_le_sub {a b c d : A} (Hab : a ≤ b) (Hcd : c ≤ d) : a - d ≤ b - c := add_le_add Hab (neg_le_neg Hcd) definition sub_lt_sub_left {a b : A} (H : a < b) (c : A) : c - b < c - a := add_lt_add_left (neg_lt_neg H) c definition sub_lt_sub_right {a b : A} (H : a < b) (c : A) : a - c < b - c := add_lt_add_right H (-c) definition sub_lt_sub {a b c d : A} (Hab : a < b) (Hcd : c < d) : a - d < b - c := add_lt_add Hab (neg_lt_neg Hcd) definition sub_lt_sub_of_le_of_lt {a b c d : A} (Hab : a ≤ b) (Hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt Hab (neg_lt_neg Hcd) definition sub_lt_sub_of_lt_of_le {a b c d : A} (Hab : a < b) (Hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le Hab (neg_le_neg Hcd) definition sub_le_self (a : A) {b : A} (H : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg H) ... = a : by rewrite add_zero definition sub_lt_self (a : A) {b : A} (H : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos H) ... = a : by rewrite add_zero end structure decidable_linear_ordered_comm_group [class] (A : Type) extends ordered_comm_group A, decidable_linear_order A section variables [s : decidable_linear_ordered_comm_group A] variables {a b c d e : A} include s definition eq_zero_of_neg_eq (H : -a = a) : a = 0 := lt.by_cases (assume H1 : a < 0, have H2: a > 0, from H ▸ neg_pos_of_neg H1, absurd H1 (lt.asymm H2)) (assume H1 : a = 0, H1) (assume H1 : a > 0, have H2: a < 0, from H ▸ neg_neg_of_pos H1, absurd H1 (lt.asymm H2)) definition abs (a : A) : A := if 0 ≤ a then a else -a definition abs_of_nonneg (H : a ≥ 0) : abs a = a := if_pos H definition abs_of_pos (H : a > 0) : abs a = a := if_pos (le_of_lt H) definition abs_of_neg (H : a < 0) : abs a = -a := if_neg (not_le_of_lt H) definition abs_zero : abs 0 = (0:A) := abs_of_nonneg (le.refl _) definition abs_of_nonpos (H : a ≤ 0) : abs a = -a := decidable.by_cases (assume H1 : a = 0, by rewrite [H1, abs_zero, neg_zero]) (assume H1 : a ≠ 0, have H2 : a < 0, from lt_of_le_of_ne H H1, abs_of_neg H2) definition abs_neg (a : A) : abs (-a) = abs a := sum.rec_on (le.total 0 a) (assume H1 : 0 ≤ a, by rewrite [abs_of_nonpos (neg_nonpos_of_nonneg H1), neg_neg, abs_of_nonneg H1]) (assume H1 : a ≤ 0, by rewrite [abs_of_nonneg (neg_nonneg_of_nonpos H1), abs_of_nonpos H1]) definition abs_nonneg (a : A) : abs a ≥ 0 := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, by rewrite (abs_of_nonneg H); exact H) (assume H : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos H ... = abs a : abs_of_nonpos H) definition abs_abs (a : A) : abs (abs a) = abs a := abs_of_nonneg !abs_nonneg definition le_abs_self (a : A) : a ≤ abs a := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, abs_of_nonneg H ▸ !le.refl) (assume H : a ≤ 0, le.trans H !abs_nonneg) definition neg_le_abs_self (a : A) : -a ≤ abs a := !abs_neg ▸ !le_abs_self definition eq_zero_of_abs_eq_zero (H : abs a = 0) : a = 0 := have H1 : a ≤ 0, from H ▸ le_abs_self a, have H2 : -a ≤ 0, from H ▸ abs_neg a ▸ le_abs_self (-a), le.antisymm H1 (nonneg_of_neg_nonpos H2) definition abs_eq_zero_iff_eq_zero (a : A) : abs a = 0 ↔ a = 0 := iff.intro eq_zero_of_abs_eq_zero (assume H, ap abs H ⬝ !abs_zero) definition abs_pos_of_pos (H : a > 0) : abs a > 0 := by rewrite (abs_of_pos H); exact H definition abs_pos_of_neg (H : a < 0) : abs a > 0 := !abs_neg ▸ abs_pos_of_pos (neg_pos_of_neg H) definition abs_pos_of_ne_zero (H : a ≠ 0) : abs a > 0 := sum.rec_on (lt_or_gt_of_ne H) abs_pos_of_neg abs_pos_of_pos definition abs_sub (a b : A) : abs (a - b) = abs (b - a) := by rewrite [-neg_sub, abs_neg] definition abs.by_cases {P : A → Type} {a : A} (H1 : P a) (H2 : P (-a)) : P (abs a) := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, (abs_of_nonneg H)⁻¹ ▸ H1) (assume H : a ≤ 0, (abs_of_nonpos H)⁻¹ ▸ H2) definition abs_le_of_le_of_neg_le (H1 : a ≤ b) (H2 : -a ≤ b) : abs a ≤ b := abs.by_cases H1 H2 definition abs_lt_of_lt_of_neg_lt (H1 : a < b) (H2 : -a < b) : abs a < b := abs.by_cases H1 H2 -- the triangle inequality section private lemma aux1 {a b : A} (H1 : a + b ≥ 0) (H2 : a ≥ 0) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume H3 : b ≥ 0, calc abs (a + b) ≤ abs (a + b) : le.refl ... = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... = abs a + abs b : by rewrite (abs_of_nonneg H3)) (assume H3 : ¬ b ≥ 0, assert H4 : b ≤ 0, from le_of_lt (lt_of_not_le H3), calc abs (a + b) = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... ≤ abs a + 0 : add_le_add_left H4 ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos H4) ... = abs a + abs b : by rewrite (abs_of_nonpos H4)) private lemma aux2 {a b : A} (H1 : a + b ≥ 0) : abs (a + b) ≤ abs a + abs b := sum.rec_on (le.total b 0) (assume H2 : b ≤ 0, have H3 : ¬ a < 0, from assume H4 : a < 0, have H5 : a + b < 0, from !add_zero ▸ add_lt_add_of_lt_of_le H4 H2, not_lt_of_le H1 H5, aux1 H1 (le_of_not_lt H3)) (assume H2 : 0 ≤ b, begin have H3 : abs (b + a) ≤ abs b + abs a, begin rewrite add.comm at H1, exact aux1 H1 H2 end, rewrite [add.comm, {abs a + _}add.comm], exact H3 end) definition abs_add_le_abs_add_abs (a b : A) : abs (a + b) ≤ abs a + abs b := sum.rec_on (le.total 0 (a + b)) (assume H2 : 0 ≤ a + b, aux2 H2) (assume H2 : a + b ≤ 0, assert H3 : -a + -b = -(a + b), by rewrite neg_add, assert H4 : -(a + b) ≥ 0, from iff.mpr (neg_nonneg_iff_nonpos (a+b)) H2, have H5 : -a + -b ≥ 0, begin rewrite -H3 at H4, exact H4 end, calc abs (a + b) = abs (-a + -b) : by rewrite [-abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 H5 ... = abs a + abs b : by rewrite *abs_neg) end definition abs_sub_abs_le_abs_sub (a b : A) : abs a - abs b ≤ abs (a - b) := have H1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rewrite sub_add_cancel ... = abs (a - b + b) : by rewrite sub_add_cancel ... ≤ abs (a - b) + abs b : abs_add_le_abs_add_abs, algebra.le_of_add_le_add_right H1 end end algebra
63fb8550d095b0c498c433313caeb9776682e2ea
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/set/basic.lean
16c1cfe8eac6e17f0e05ac6c31970c8d9a6d12df
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
117,723
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 -/ import logic.unique import logic.relation import order.boolean_algebra /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `strict_subset s₁ s₂ : Prop` : the predicate `s₁ ⊆ s₂` but `s₁ ≠ s₂`. * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `range f : set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) * `s.prod t : set (α × β)` : the subset `s × t`. * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `f ⁻¹' t` for `preimage f t` * `f '' s` for `image f s` * `sᶜ` for the complement of `s` ## Implementation notes * `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universes u v w x run_cmd do e ← tactic.get_env, tactic.set_env $ e.mk_protected `set.compl lemma has_subset.subset.trans {α : Type*} [has_subset α] [is_trans α (⊆)] {a b c : α} (h : a ⊆ b) (h' : b ⊆ c) : a ⊆ c := trans h h' lemma has_subset.subset.antisymm {α : Type*} [has_subset α] [is_antisymm α (⊆)] {a b : α} (h : a ⊆ b) (h' : b ⊆ a) : a = b := antisymm h h' lemma has_ssubset.ssubset.trans {α : Type*} [has_ssubset α] [is_trans α (⊂)] {a b c : α} (h : a ⊂ b) (h' : b ⊂ c) : a ⊂ c := trans h h' lemma has_ssubset.ssubset.asymm {α : Type*} [has_ssubset α] [is_asymm α (⊂)] {a b : α} (h : a ⊂ b) : ¬(b ⊂ a) := asymm h namespace set variable {α : Type*} instance : has_le (set α) := ⟨(⊆)⟩ instance : has_lt (set α) := ⟨λ s t, s ≤ t ∧ ¬t ≤ s⟩ -- `⊂` is not defined until further down instance {α : Type*} : boolean_algebra (set α) := { sup := (∪), le := (≤), lt := (<), inf := (∩), bot := ∅, compl := set.compl, top := univ, sdiff := (\), .. (infer_instance : boolean_algebra (α → Prop)) } @[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl @[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl @[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl @[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl /-! `set.lt_eq_ssubset` is defined further down -/ @[simp] lemma compl_eq_compl : set.compl = (has_compl.compl : set α → set α) := rfl /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)] (s : set ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α s } instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) : can_lift (s → α) (ι → α) := pi_set_coe.can_lift ι (λ _, α) s instance set_coe.can_lift (s : set α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } end set section set_coe variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} : (∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) := (@set_coe.forall _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t := by { rintro rfl x hx, exact hx } namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of s = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred (∈ {a | p a}) := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl /-! ### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩ theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ mem_of_subset_of_mem h theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ instance : has_ssubset (set α) := ⟨(<)⟩ @[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (set α) _ s t lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s @[simp] lemma nonempty_coe_sort (s : set α) : nonempty ↥s ↔ s.nonempty := nonempty_subtype lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx theorem nonempty.ne_empty : ∀ {s : set α}, s.nonempty → s ≠ ∅ | _ ⟨x, hx⟩ rfl := hx @[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩ lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := nonempty_of_not_subset ht.2 lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_inter_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x : t, ↑x ∈ s := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xt⟩, xs⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xs, xt⟩⟩ lemma nonempty_inter_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x : s, ↑x ∈ t := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xs⟩, xt⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xt, xs⟩⟩ lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype (h : s.nonempty) : nonempty s := nonempty_subtype.2 h instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype @[simp] lemma nonempty_insert (a : α) (s : set α) : (insert a s).nonempty := ⟨a, or.inl rfl⟩ lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty := nonempty_subtype.mp ‹_› /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s. theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := (subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, is_empty_elim x /-- There is exactly one set of a type that is empty. -/ -- TODO[gh-6025]: make this an instance once safe to do so def unique_empty [is_empty α] : unique (set α) := { default := ∅, uniq := eq_empty_of_is_empty } lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] lemma empty_not_nonempty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := or_iff_not_imp_left.2 ne_empty_iff_nonempty.1 theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := iff_true_intro $ λ x, false.elim instance (α : Type u) : is_empty.{u+1} (∅ : set α) := ⟨λ x, x.2⟩ /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ @[simp] theorem set_of_true : {x : α | true} = univ := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α := eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩ theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ := λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := (subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩ theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ instance univ_decidable : decidable_pred (∈ @set.univ α) := λ x, is_true trivial lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s := by rw [←not_forall, ←eq_univ_iff_forall] lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} : ¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def] /-- `diagonal α` is the subset of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} @[simp] lemma mem_diagonal {α : Type*} (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _ @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _ @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _ theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ x, or.left_comm theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, or.right_comm @[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := union_eq_right_iff_subset.mpr h theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := union_eq_left_iff_subset.mpr h @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x, or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _) theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h subset.rfl theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union subset.rfl h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff]; exact union_subset_iff @[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq @[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _ @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _ @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _ theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ x, and.left_comm theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ x, and.right_comm @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib @[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s := inf_eq_right theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s := inter_eq_left_iff_subset.mpr theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t := inter_eq_right_iff_subset.mpr @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H subset.rfl theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter subset.rfl H theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right $ subset_union_left _ _ theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right $ subset_union_right _ _ /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} : x ∈ insert a s → x ≠ a → x ∈ s := or.resolve_left @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t := mt $ λ e, e.symm ▸ mem_insert _ _ theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _) theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := begin refine ⟨λ h x hx, _, insert_subset_insert⟩, rcases h (subset_insert _ _ hx) with (rfl|hxt), exacts [(ha hx).elim, hxt] end theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.refl _⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, or.left_comm theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype lemma insert_inter (x : α) (s t : set α) : insert x (s ∩ t) = insert x s ∩ insert x t := ext $ λ y, or_and_distrib_left -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (λ e, e.symm ▸ ha) (H _) theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) := bex_or_left_distrib.trans $ or_congr_left bex_eq_left theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := ball_or_left_distrib.trans $ and_congr_left' forall_eq /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := rfl @[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := ext_iff.trans eq_iff_eq_cancel_left theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _ @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s := by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans $ not_congr singleton_inter_nonempty @[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := ne_empty_iff_nonempty instance unique_singleton (a : α) : unique ↥({a} : set α) := ⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩ lemma eq_singleton_iff_unique_mem {s : set α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff lemma eq_singleton_iff_nonempty_unique_mem {s : set α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] lemma default_coe_singleton (x : α) : default ({x} : set α) = ⟨x, rfl⟩ := rfl /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} := (inter_eq_self_of_subset_right h).symm @[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅) (x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _) @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _ @[simp] lemma sep_true : {a ∈ s | true} = s := by { ext, simp } @[simp] lemma sep_false : {a ∈ s | false} = ∅ := by { ext, simp } lemma sep_inter_sep {p q : α → Prop} : {x ∈ s | p x} ∩ {x ∈ s | q x} = {x ∈ s | p x ∧ q x} := begin ext, simp_rw [mem_inter_iff, mem_sep_iff], rw [and_and_and_comm, and_self], end @[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := iff.rfl lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := begin obtain (rfl | hs) := s.eq_empty_or_nonempty, use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩, simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs], end lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ := begin rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)), end lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top @[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans $ not_congr $ compl_empty_iff lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := not_congr mem_singleton_iff lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff @[simp] lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} := by { ext, simp, } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext $ λ x, or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext $ λ x, and_iff_not_or_not @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _ @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s t _ @[simp] lemma compl_subset_compl {s t : set α} : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le _ t s _ theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ tᶜ ↔ t ⊆ sᶜ := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ tᶜ ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := (not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_of_le h theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := disjoint.sup_sdiff_cancel_left h theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := disjoint.sup_sdiff_cancel_right h @[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := sup_inf_sdiff s t @[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _ theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_self_sdiff ‹s₁ ≤ s₂› theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_self ‹t ≤ u› theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := sdiff_bot @[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := show s ≤ (s \ t) ∪ t, from le_sdiff_sup lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) : (s \ t) ∪ t = s := subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _) @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by { ext, split; simp [or_imp_distrib, h] {contextual := tt} } theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) : insert a s \ {a} = s := by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] } lemma insert_inter_of_mem {s₁ s₂ : set α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := by simp [set.insert_inter, h] lemma insert_inter_of_not_mem {s₁ s₂ : set α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := begin ext x, simp only [mem_inter_iff, mem_insert_iff, mem_inter_eq, and.congr_left_iff, or_iff_right_iff_imp], cc, end @[simp] theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left @[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := inf_sdiff_self_left @[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right @[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left @[simp] theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) := mem_diff_singleton.trans $ and_congr iff.rfl ne_empty_iff_nonempty lemma union_eq_diff_union_diff_union_inter (s t : set α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h @[simp] theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t := ext $ λ u, subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩ theorem monotone_powerset : monotone (powerset : set α → set (set α)) := λ s t, powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).nonempty := ⟨∅, empty_subset s⟩ @[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} := ext $ λ s, subset_empty_iff @[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ := eq_univ_of_forall subset_univ /-! ### If-then-else for sets -/ /-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t @[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t := by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s := by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq] @[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _ @[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite] @[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite] @[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' := by simp [set.ite] @[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s := by simp [set.ite] @[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t := by simp [set.ite] @[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t := by simp [set.ite] lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union (inter_subset_left _ _) (diff_subset _ _) lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _) lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by { ext x, finish [set.ite, iff_def] } lemma ite_inter (t s₁ s₂ s : set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := begin simp only [subset_def, ← forall_and_distrib], refine forall_congr (λ x, _), by_cases hx : x ∈ t; simp [*, set.ite] end /-! ### Inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s := by { congr' with x, apply_assumption } theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : set β) : f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl @[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl @[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) : (λ (x : α), b) ⁻¹' s = univ := eq_univ_of_forall $ λ x, h @[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) : (λ (x : α), b) ⁻¹' s = ∅ := eq_empty_of_subset_empty $ λ x hx, h hx theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] : (λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ := by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] } theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} : f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s := preimage_comp.symm theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by { rw [s_eq], simp }, assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩ lemma preimage_coe_coe_diagonal {α : Type*} (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := begin ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, simp [set.diagonal], end end preimage /-! ### Image of a set under a function -/ section image infix ` '' `:80 := image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem _root_.function.injective.mem_set_image {f : α → β} (hf : injective f) {s : set α} {a : α} : f a ∈ f '' s ↔ a ∈ s := ⟨λ ⟨b, hb, eq⟩, (hf eq) ▸ hb, mem_image_of_mem f⟩ theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := by simp theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := ball_image_iff.2 h theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) := by simp theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /-- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm /-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in terms of `≤`. -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩, by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩ @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp } lemma image_inter_subset (f : α → β) (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _) theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (image_inter_subset _ _ _) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by { simpa [image] } @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := by { ext, simp [image, eq_comm] } @[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by { simp only [eq_empty_iff_forall_not_mem], exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ } -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ tᶜ ∈ S := begin suffices : ∀ x, xᶜ = t ↔ tᶜ = x, { simp [this] }, intro x, split; { intro e, subst e, simp } end /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp } theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] } theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ := compl_subset_iff_union.2 $ by { rw ← image_union, simp [image_univ_of_surjective H] } theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) theorem subset_image_diff (f : α → β) (s t : set α) : f '' s \ f '' t ⊆ f '' (s \ t) := begin rw [diff_subset_iff, ← image_union, union_diff_self], exact image_subset f (subset_union_right t s) end theorem image_diff {f : α → β} (hf : injective f) (s t : set α) : f '' (s \ t) = f '' s \ f '' t := subset.antisymm (subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf) (subset_image_diff f s t) lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty | ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩ lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty | ⟨y, x, hx, _⟩ := ⟨x, hx⟩ @[simp] lemma nonempty_image_iff {f : α → β} {s : set α} : (f '' s).nonempty ↔ s.nonempty := ⟨nonempty.of_image, λ h, h.image f⟩ lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩ instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) := (set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype /-- image and preimage are a Galois connection -/ @[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} (s : set β) (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := iff.intro (assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq]) (assume eq, eq ▸ rfl) lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := begin apply subset.antisymm, { calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _ ... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) }, { rintros _ ⟨⟨x, h', rfl⟩, h⟩, exact ⟨x, ⟨h', h⟩, rfl⟩ } end lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, image_inter_preimage] @[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} : (f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty := by rw [←image_inter_preimage, nonempty_image_iff] lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t := by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage] theorem compl_image : image (compl : set α → set α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : set α → Prop} : compl '' {s | p s} = {s | p sᶜ} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton`, if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton := λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ @[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim @[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} := ⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩ lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] } lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α := ⟨λ a b, h (mem_univ a) (mem_univ b)⟩ @[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α := ⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩ lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s := subsingleton.mono subsingleton_univ (subset_univ s) lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} := λ x hx y hy, hx.unique (hy x) lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} := λ x hx y hy, hx.unique (hy x) /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton := begin split, { refine λ h, (λ a ha b hb, _), exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) }, { exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) } end /-- The preimage of a subsingleton under an injective map is a subsingleton. -/ theorem subsingleton.preimage {s : set β} (hs : s.subsingleton) {f : α → β} (hf : function.injective f) : (f ⁻¹' s).subsingleton := λ a ha b hb, hf $ hs ha hb /-- `s` is a subsingleton, if its image of an injective function is. -/ theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f) (s : set α) (hs : (f '' s).subsingleton) : s.subsingleton := (hs.preimage hf).mono $ subset_preimage_image _ _ theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl @[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := by simp theorem forall_subtype_range_iff {p : range f → Prop} : (∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ := ⟨λ H i, H _, λ H ⟨y, i, hi⟩, by { subst hi, apply H }⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := by simp lemma exists_range_iff' {p : α → Prop} : (∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) := by simpa only [exists_prop] using exists_range_iff lemma exists_subtype_range_iff {p : range f → Prop} : (∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ := ⟨λ ⟨⟨a, i, hi⟩, ha⟩, by { subst a, exact ⟨i, ha⟩}, λ ⟨i, hi⟩, ⟨_, hi⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall alias range_iff_surjective ↔ _ function.surjective.range_eq @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem _root_.prod.range_fst [nonempty β] : range (prod.fst : α × β → α) = univ := prod.fst_surjective.range_eq @[simp] theorem _root_.prod.range_snd [nonempty α] : range (prod.snd : α × β → β) = univ := prod.snd_surjective.range_eq @[simp] theorem range_eval {ι : Type*} {α : ι → Sort*} [Π i, nonempty (α i)] (i : ι) : range (eval i : (Π i, α i) → α i) = univ := (surjective_eval i).range_eq theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) := ⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc }, by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩ @[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ := is_compl_range_inl_range_inr.sup_eq_top @[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ := is_compl_range_inl_range_inr.inf_eq_bot @[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ := is_compl_range_inl_range_inr.symm.sup_eq_top @[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ := is_compl_range_inl_range_inr.symm.inf_eq_bot @[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ := by { ext, simp } @[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ := by { ext, simp } @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := (surjective_quot_mk r).range_eq @[simp] theorem image_univ {f : α → β} : f '' univ = range f := by { ext, simp [image, range] } theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f := mem_of_mem_of_subset h $ image_subset_range f s theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι := ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty := range_nonempty_iff_nonempty.2 h @[simp] lemma range_eq_empty_iff {f : ι → α} : range f = ∅ ↔ is_empty ι := by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty] lemma range_eq_empty [is_empty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_› instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype @[simp] lemma image_union_image_compl_eq_range (f : α → β) : (f '' s) ∪ (f '' sᶜ) = range f := by rw [← image_union, ← image_univ, ← union_compl_self] theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] instance set.can_lift [can_lift α β] : can_lift (set α) (set β) := { coe := λ s, can_lift.coe '' s, cond := λ s, ∀ x ∈ s, can_lift.cond β x, prf := λ s hs, ⟨can_lift.coe ⁻¹' s, image_preimage_eq_of_subset $ λ x hx, can_lift.prf _ (hs x hx)⟩ } lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f := ⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩ lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end @[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ @[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x lemma diagonal_eq_range {α : Type*} : diagonal α = range (λ x, (x, x)) := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } theorem preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).nonempty ↔ y ∈ range f := iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans $ not_congr preimage_singleton_nonempty lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x := by simp [range_subset_iff, funext_iff, mem_singleton] lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s := by rw [compl_eq_univ_diff, image_diff_preimage, image_univ] @[simp] theorem range_sigma_mk {β : α → Type*} (a : α) : range (sigma.mk a : β a → Σ a, β a) = sigma.fst ⁻¹' {a} := begin apply subset.antisymm, { rintros _ ⟨b, rfl⟩, simp }, { rintros ⟨x, y⟩ (rfl|_), exact mem_range_self y } end /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl @[simp] lemma range_factorization_coe (f : ι → β) (a : ι) : (range_factorization f a : β) = f a := rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end @[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ := eq_univ_of_forall mem_range_self /-- The range of a function from a `unique` type contains just the function applied to its single value. -/ lemma range_unique [h : unique ι] : range f = {f $ default ι} := begin ext x, rw mem_range, split, { rintros ⟨i, hi⟩, rw h.uniq i at hi, exact hi ▸ mem_singleton _ }, { exact λ h, ⟨default ι, h.symm⟩ } end lemma range_diff_image_subset (f : α → β) (s : set α) : range f \ f '' s ⊆ f '' sᶜ := λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩ lemma range_diff_image {f : α → β} (H : injective f) (s : set α) : range f \ f '' s = f '' sᶜ := subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸ ⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩ /-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/ noncomputable def range_splitting (f : α → β) : range f → α := λ x, x.2.some -- This can not be a `@[simp]` lemma because the head of the left hand side is a variable. lemma apply_range_splitting (f : α → β) (x : range f) : f (range_splitting f x) = x := x.2.some_spec attribute [irreducible] range_splitting @[simp] lemma comp_range_splitting (f : α → β) : f ∘ range_splitting f = coe := by { ext, simp only [function.comp_app], apply apply_range_splitting, } -- When `f` is injective, see also `equiv.of_injective`. lemma left_inverse_range_splitting (f : α → β) : left_inverse (range_factorization f) (range_splitting f) := λ x, by { ext, simp only [range_factorization_coe], apply apply_range_splitting, } lemma range_splitting_injective (f : α → β) : injective (range_splitting f) := (left_inverse_range_splitting f).injective lemma is_compl_range_some_none (α : Type*) : is_compl (range (some : α → option α)) {none} := ⟨λ x ⟨⟨a, ha⟩, (hn : x = none)⟩, option.some_ne_none _ (ha.trans hn), λ x hx, option.cases_on x (or.inr rfl) (λ x, or.inl $ mem_range_self _)⟩ @[simp] lemma compl_range_some (α : Type*) : (range (some : α → option α))ᶜ = {none} := (is_compl_range_some_none α).compl_eq @[simp] lemma range_some_inter_none (α : Type*) : range (some : α → option α) ∩ {none} = ∅ := (is_compl_range_some_none α).inf_eq_bot @[simp] lemma range_some_union_none (α : Type*) : range (some : α → option α) ∪ {none} = univ := (is_compl_range_some_none α).sup_eq_top end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y lemma pairwise_on_of_forall (s : set α) (p : α → α → Prop) (h : ∀ (a b : α), p a b) : pairwise_on s p := λ a _ b _ _, h a b lemma pairwise_on.imp_on {s : set α} {p q : α → α → Prop} (h : pairwise_on s p) (hpq : pairwise_on s (λ ⦃a b : α⦄, p a b → q a b)) : pairwise_on s q := λ a ha b hb hab, hpq a ha b hb hab (h a ha b hb hab) lemma pairwise_on.imp {s : set α} {p q : α → α → Prop} (h : pairwise_on s p) (hpq : ∀ ⦃a b : α⦄, p a b → q a b) : pairwise_on s q := h.imp_on (pairwise_on_of_forall s _ hpq) theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : r ≤ r') (hp : pairwise_on s r) : pairwise_on s r' := hp.imp H theorem pairwise_on_top (s : set α) : pairwise_on s ⊤ := pairwise_on_of_forall s _ (λ a b, trivial) protected lemma subsingleton.pairwise_on (h : s.subsingleton) (r : α → α → Prop) : pairwise_on s r := λ x hx y hy hne, (hne (h hx hy)).elim @[simp] lemma pairwise_on_empty (r : α → α → Prop) : (∅ : set α).pairwise_on r := subsingleton_empty.pairwise_on r @[simp] lemma pairwise_on_singleton (a : α) (r : α → α → Prop) : pairwise_on {a} r := subsingleton_singleton.pairwise_on r theorem nonempty.pairwise_on_iff_exists_forall {s : set α} (hs : s.nonempty) {f : α → β} {r : β → β → Prop} [is_equiv β r] : (pairwise_on s (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin fsplit, { rcases hs with ⟨y, hy⟩, refine λ H, ⟨f y, λ x hx, _⟩, rcases eq_or_ne x y with rfl|hne, { apply is_refl.refl }, { exact H _ hx _ hy hne } }, { rintro ⟨z, hz⟩ x hx y hy hne, exact @is_trans.trans β r _ (f x) z (f y) (hz _ hx) (is_symm.symm _ _ $ hz _ hy) } end /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.pairwise_on_eq_iff_exists_eq` for a version that assumes `[nonempty β]` instead of `set.nonempty s`. -/ theorem nonempty.pairwise_on_eq_iff_exists_eq {s : set α} (hs : s.nonempty) {f : α → β} : (pairwise_on s (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_on_iff_exists_forall lemma pairwise_on_iff_exists_forall [nonempty β] (s : set α) (f : α → β) {r : β → β → Prop} [is_equiv β r] : (pairwise_on s (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin rcases s.eq_empty_or_nonempty with rfl|hne, { simp }, { exact hne.pairwise_on_iff_exists_forall } end /-- A function `f : α → β` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.nonempty.pairwise_on_eq_iff_exists_eq` for a version that assumes `set.nonempty s` instead of `[nonempty β]`. -/ lemma pairwise_on_eq_iff_exists_eq [nonempty β] (s : set α) (f : α → β) : (pairwise_on s (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_on_iff_exists_forall s f lemma pairwise_on_union {α} {s t : set α} {r : α → α → Prop} : (s ∪ t).pairwise_on r ↔ s.pairwise_on r ∧ t.pairwise_on r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b ∧ r b a := begin simp only [pairwise_on, mem_union_eq, or_imp_distrib, forall_and_distrib], exact ⟨λ H, ⟨H.1.1, H.2.2, H.2.1, λ x hx y hy hne, H.1.2 y hy x hx hne.symm⟩, λ H, ⟨⟨H.1, λ x hx y hy hne, H.2.2.2 y hy x hx hne.symm⟩, H.2.2.1, H.2.1⟩⟩ end lemma pairwise_on_union_of_symmetric {α} {s t : set α} {r : α → α → Prop} (hr : symmetric r) : (s ∪ t).pairwise_on r ↔ s.pairwise_on r ∧ t.pairwise_on r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b := pairwise_on_union.trans $ by simp only [hr.iff, and_self] lemma pairwise_on_insert {α} {s : set α} {a : α} {r : α → α → Prop} : (insert a s).pairwise_on r ↔ s.pairwise_on r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_on_union, pairwise_on_singleton, true_and, mem_singleton_iff, forall_eq] lemma pairwise_on_insert_of_symmetric {α} {s : set α} {a : α} {r : α → α → Prop} (hr : symmetric r) : (insert a s).pairwise_on r ↔ s.pairwise_on r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_on_insert, hr.iff a, and_self] lemma pairwise_on_pair {r : α → α → Prop} {x y : α} : pairwise_on {x, y} r ↔ (x ≠ y → r x y ∧ r y x) := by simp [pairwise_on_insert] lemma pairwise_on_pair_of_symmetric {r : α → α → Prop} {x y : α} (hr : symmetric r) : pairwise_on {x, y} r ↔ (x ≠ y → r x y) := by simp [pairwise_on_insert_of_symmetric hr] lemma pairwise_on_disjoint_on_mono {s : set α} {f g : α → set β} (h : s.pairwise_on (disjoint on f)) (h' : ∀ x ∈ s, g x ⊆ f x) : s.pairwise_on (disjoint on g) := λ i hi j hj hij, disjoint.mono (h' i hi) (h' j hj) (h i hi j hj hij) end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s := preimage_image_eq s hf lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) := by { intro s, use f '' s, rw hf.preimage_image } lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} : (f '' s).subsingleton ↔ s.subsingleton := ⟨subsingleton_of_image hf s, λ h, h.image f⟩ lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s := image_preimage_eq s hf lemma surjective.image_surjective (hf : surjective f) : surjective (image f) := by { intro s, use f ⁻¹' s, rw hf.image_preimage } lemma surjective.nonempty_preimage (hf : surjective f) {s : set β} : (f ⁻¹' s).nonempty ↔ s.nonempty := by rw [← nonempty_image_iff, hf.image_preimage] lemma injective.image_injective (hf : injective f) : injective (image f) := by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] } lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ } lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) : range (g ∘ f) = range g := ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff] lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} : b ∈ range f ↔ ∃! a, f a = b := ⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩ lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) : ∃! a, f a = b := hf.mem_range_iff_exists_unique.mp hb theorem injective.compl_image_eq (hf : injective f) (s : set α) : (f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ := begin ext y, rcases em (y ∈ range f) with ⟨x, rfl⟩|hx, { simp [hf.eq_iff] }, { rw [mem_range, not_exists] at hx, simp [hx] } end lemma left_inverse.image_image {g : β → α} (h : left_inverse g f) (s : set α) : g '' (f '' s) = s := by rw [← image_comp, h.comp_eq_id, image_id] lemma left_inverse.preimage_preimage {g : β → α} (h : left_inverse g f) (s : set α) : f ⁻¹' (g ⁻¹' s) = s := by rw [← preimage_comp, h.comp_eq_id, preimage_id] end function open function lemma option.injective_iff {α β} {f : option α → β} : injective f ↔ injective (f ∘ some) ∧ f none ∉ range (f ∘ some) := begin simp only [mem_range, not_exists, (∘)], refine ⟨λ hf, ⟨hf.comp (option.some_injective _), λ x, hf.ne $ option.some_ne_none _⟩, _⟩, rintro ⟨h_some, h_none⟩ (_|a) (_|b) hab, exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)] end /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma coe_image {p : α → Prop} {s : set (subtype p)} : coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma coe_image_of_subset {s t : set α} (h : t ⊆ s) : coe '' {x : ↥s | ↑x ∈ t} = t := begin ext x, rw set.mem_image, exact ⟨λ ⟨x', hx', hx⟩, hx ▸ hx', λ hx, ⟨⟨x, h hx⟩, hx, rfl⟩⟩, end lemma range_coe {s : set α} : range (coe : s → α) = s := by { rw ← set.image_univ, simp [-set.image_univ, coe_image] } /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ lemma range_val {s : set α} : range (subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are `coe α (λ x, x ∈ s)`. -/ @[simp] lemma range_coe_subtype {p : α → Prop} : range (coe : subtype p → α) = {x | p x} := range_coe @[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ := by rw [← preimage_range (coe : s → α), range_coe] lemma range_val_subtype {p : α → Prop} : range (subtype.val : subtype p → α) = {x | p x} := range_coe theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : set α) : (coe : s → α) '' (coe ⁻¹' t) = t ∩ s := image_preimage_eq_inter_range.trans $ congr_arg _ range_coe theorem image_preimage_val (s t : set α) : (subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := begin rw [←image_preimage_coe, ←image_preimage_coe], split, { intro h, rw h }, intro h, exact coe_injective.image_injective h end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) := preimage_coe_eq_preimage_coe_iff lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩, convert image_subset_range _ _, rw [range_coe] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁ end lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty := by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff] lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ := by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty] @[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ := preimage_coe_eq_empty.2 (inter_compl_self s) @[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ := preimage_coe_eq_empty.2 (compl_inter_self s) end subtype namespace set /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : s.prod t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ s.prod t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} : (a, b) ∈ s.prod t = (a ∈ s ∧ b ∈ t) := rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ s.prod t := ⟨a_in, b_in⟩ theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁.prod t₁ ⊆ s₂.prod t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ lemma prod_subset_iff {P : set (α × β)} : (s.prod t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h ⟨_, _⟩ pin, h _ pin.1 _ pin.2⟩ lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s.prod t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) := prod_subset_iff lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s.prod t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) := by simp [and_assoc] @[simp] theorem prod_empty : s.prod ∅ = (∅ : set (α × β)) := by { ext, simp } @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := by { ext, simp } @[simp] theorem univ_prod_univ : (@univ α).prod (@univ β) = univ := by { ext ⟨x, y⟩, simp } lemma univ_prod {t : set β} : set.prod (univ : set α) t = prod.snd ⁻¹' t := by simp [prod_eq] lemma prod_univ {s : set α} : set.prod s (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq] @[simp] theorem singleton_prod {a : α} : set.prod {a} t = prod.mk a '' t := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] theorem prod_singleton {b : β} : s.prod {b} = (λ a, (a, b)) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } theorem singleton_prod_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α × β)) := by simp @[simp] theorem union_prod : (s₁ ∪ s₂).prod t = s₁.prod t ∪ s₂.prod t := by { ext ⟨x, y⟩, simp [or_and_distrib_right] } @[simp] theorem prod_union : s.prod (t₁ ∪ t₂) = s.prod t₁ ∪ s.prod t₂ := by { ext ⟨x, y⟩, simp [and_or_distrib_left] } theorem prod_inter_prod : s₁.prod t₁ ∩ s₂.prod t₂ = (s₁ ∩ s₂).prod (t₁ ∩ t₂) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } theorem insert_prod {a : α} : (insert a s).prod t = (prod.mk a '' t) ∪ s.prod t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } theorem prod_insert {b : β} : s.prod (insert b t) = ((λa, (a, b)) '' s) ∪ s.prod t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } theorem prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s).prod (g ⁻¹' t) = (λ p, (f p.1, g p.2)) ⁻¹' s.prod t := rfl lemma prod_preimage_left {f : γ → α} : (f ⁻¹' s).prod t = (λp, (f p.1, p.2)) ⁻¹' (s.prod t) := rfl lemma prod_preimage_right {g : δ → β} : s.prod (g ⁻¹' t) = (λp, (p.1, g p.2)) ⁻¹' (s.prod t) := rfl lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) : prod.map f g ⁻¹' (s.prod t) = (f ⁻¹' s).prod (g ⁻¹' t) := rfl lemma mk_preimage_prod (f : γ → α) (g : γ → β) : (λ x, (f x, g x)) ⁻¹' s.prod t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] lemma mk_preimage_prod_left {y : β} (h : y ∈ t) : (λ x, (x, y)) ⁻¹' s.prod t = s := by { ext x, simp [h] } @[simp] lemma mk_preimage_prod_right {x : α} (h : x ∈ s) : prod.mk x ⁻¹' s.prod t = t := by { ext y, simp [h] } @[simp] lemma mk_preimage_prod_left_eq_empty {y : β} (hy : y ∉ t) : (λ x, (x, y)) ⁻¹' s.prod t = ∅ := by { ext z, simp [hy] } @[simp] lemma mk_preimage_prod_right_eq_empty {x : α} (hx : x ∉ s) : prod.mk x ⁻¹' s.prod t = ∅ := by { ext z, simp [hx] } lemma mk_preimage_prod_left_eq_if {y : β} [decidable_pred (∈ t)] : (λ x, (x, y)) ⁻¹' s.prod t = if y ∈ t then s else ∅ := by { split_ifs; simp [h] } lemma mk_preimage_prod_right_eq_if {x : α} [decidable_pred (∈ s)] : prod.mk x ⁻¹' s.prod t = if x ∈ s then t else ∅ := by { split_ifs; simp [h] } lemma mk_preimage_prod_left_fn_eq_if {y : β} [decidable_pred (∈ t)] (f : γ → α) : (λ x, (f x, y)) ⁻¹' s.prod t = if y ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] lemma mk_preimage_prod_right_fn_eq_if {x : α} [decidable_pred (∈ s)] (g : δ → β) : (λ y, (x, g y)) ⁻¹' s.prod t = if x ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem preimage_swap_prod {s : set α} {t : set β} : prod.swap ⁻¹' t.prod s = s.prod t := by { ext ⟨x, y⟩, simp [and_comm] } theorem image_swap_prod : prod.swap '' t.prod s = s.prod t := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s).prod (m₂ '' t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (s.prod t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : (range m₁).prod (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem range_prod_map {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : range (prod.map m₁ m₂) = (range m₁).prod (range m₂) := prod_range_range_eq.symm theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : (range m₁).prod (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : (univ : set α).prod (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] lemma range_pair_subset {α β γ : Type*} (f : α → β) (g : α → γ) : range (λ x, (f x, g x)) ⊆ (range f).prod (range g) := have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl), by { rw [this, ← range_prod_map], apply range_comp_subset_range } theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_eq_empty_iff : s.prod t = ∅ ↔ (s = ∅ ∨ t = ∅) := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib] lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : s.prod t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (s.prod t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : s.prod t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' (s.prod t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (s.prod t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : s.prod t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' (s.prod t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ lemma prod_diff_prod : s.prod t \ s₁.prod t₁ = s.prod (t \ t₁) ∪ (s \ s₁).prod t := by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * } /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (s.prod t ⊆ s₁.prod t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, split, { assume H : s.prod t ⊆ s₁.prod t₁, have h' : s₁.nonempty ∧ t₁.nonempty := prod_nonempty_iff.1 (h.mono H), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } } end end prod /-! ### Lemmas about set-indexed products of sets -/ section pi variables {ι : Type*} {α : ι → Type*} {s s₁ : set ι} {t t₁ t₂ : Π i, set (α i)} /-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := { f | ∀i ∈ s, f i ∈ t i } @[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := by refl @[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp @[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] } @[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ := eq_univ_of_forall $ λ f i hi, mem_univ _ lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := λ x hx i hi, (h i hi $ hx i hi) lemma pi_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_eq] lemma pi_congr (h : s = s₁) (h' : ∀ i ∈ s, t i = t₁ i) : pi s t = pi s₁ t₁ := h ▸ (ext $ λ x, forall_congr $ λ i, forall_congr $ λ hi, h' i hi ▸ iff.rfl) lemma pi_eq_empty {i : ι} (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by { ext f, simp only [mem_empty_eq, not_forall, iff_false, mem_pi, not_imp], exact ⟨i, hs, by simp [ht]⟩ } lemma univ_pi_eq_empty {i : ι} (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [classical.skolem, set.nonempty] lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty := by simp [classical.skolem, set.nonempty] lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, (α i → false) ∨ (i ∈ s ∧ t i = ∅) := begin rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, apply exists_congr, intro i, split, { intro h, by_cases hα : nonempty (α i), { cases hα with x, refine or.inr ⟨(h x).1, by simp [eq_empty_iff_forall_not_mem, h]⟩ }, { exact or.inl (λ x, hα ⟨x⟩) }}, { rintro (h|h) x, exfalso, exact h x, simp [h] } end lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] lemma univ_pi_empty [h : nonempty ι] : pi univ (λ i, ∅ : Π i, set (α i)) = ∅ := univ_pi_eq_empty_iff.2 $ h.elim $ λ x, ⟨x, rfl⟩ @[simp] lemma range_dcomp {β : ι → Type*} (f : Π i, α i → β i) : range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) := begin apply subset.antisymm, { rintro _ ⟨x, rfl⟩ i -, exact ⟨x i, rfl⟩ }, { intros x hx, choose y hy using hx, exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ } end @[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) : pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t := by { ext, simp [pi, or_imp_distrib, forall_and_distrib] } @[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) : pi {i} t = (eval i ⁻¹' t i) := by { ext, simp [pi] } lemma singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) : pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ := begin ext f, split, { assume h, split; { rintros i ⟨his, hpi⟩, simpa [*] using h i } }, { rintros ⟨ht₁, ht₂⟩ i his, by_cases p i; simp * at * } end lemma union_pi : (s ∪ s₁).pi t = s.pi t ∩ s₁.pi t := by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and] @[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] lemma pi_update_of_not_mem [decidable_eq ι] {β : Π i, Type*} {i : ι} (hi : i ∉ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) := pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) } lemma pi_update_of_mem [decidable_eq ι] {β : Π i, Type*} {i : ι} (hi : i ∈ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) := calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) : by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] ... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) : by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp } lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) : pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage] open_locale classical lemma eval_image_pi {i : ι} (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i := begin ext x, rcases ht with ⟨f, hf⟩, split, { rintro ⟨g, hg, rfl⟩, exact hg i hs }, { intro hg, refine ⟨update f i x, _, by simp⟩, intros j hj, by_cases hji : j = i, { subst hji, simp [hg] }, { rw [mem_pi] at hf, simp [hji, hf, hj] }}, end @[simp] lemma eval_image_univ_pi {i : ι} (ht : (pi univ t).nonempty) : (λ f : Π i, α i, f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht lemma eval_preimage {ι} {α : ι → Type*} {i : ι} {s : set (α i)} : eval i ⁻¹' s = pi univ (update (λ i, univ) i s) := by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] } lemma eval_preimage' {ι} {α : ι → Type*} {i : ι} {s : set (α i)} : eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) := by { ext, simp } lemma update_preimage_pi {i : ι} {f : Π i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i := begin ext x, split, { intro h, convert h i hi, simp }, { intros hx j hj, by_cases h : j = i, { cases h, simpa }, { rw [update_noteq h], exact hf j hj h }} end lemma update_preimage_univ_pi {i : ι} {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : (update f i) ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) (λ j _, hf j) lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) := λ f hf i hi, ⟨f, hf, rfl⟩ lemma univ_pi_ite (s : set ι) (t : Π i, set (α i)) : pi univ (λ i, if i ∈ s then t i else univ) = s.pi t := by { ext, simp_rw [mem_univ_pi], apply forall_congr, intro i, split_ifs; simp [h] } end pi /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by { cases x, refl } @[simp] lemma inclusion_right {s t : set α} (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by { cases x, refl } @[simp] lemma coe_inclusion {s t : set α} (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 @[simp] lemma range_inclusion {s t : set α} (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := by { ext ⟨x, hx⟩, simp [inclusion] } lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t} (h_surj : function.surjective (inclusion h)) : s = t := begin rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj, exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩) end end inclusion /-! ### Injectivity and surjectivity lemmas for image and preimage -/ section image_preimage variables {α : Type u} {β : Type v} {f : α → β} @[simp] lemma preimage_injective : injective (preimage f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.preimage_injective⟩, obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty, { rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty }, exact ⟨x, hx⟩ end @[simp] lemma preimage_surjective : surjective (preimage f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩, cases h {x} with s hs, have := mem_singleton x, rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this end @[simp] lemma image_surjective : surjective (image f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.image_surjective⟩, cases h {y} with s hs, have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩, exact ⟨x, h2x⟩ end @[simp] lemma image_injective : injective (image f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.image_injective⟩, rw [← singleton_eq_singleton_iff], apply h, rw [image_singleton, image_singleton, hx] end lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} : f ⁻¹' s = t ↔ s = f '' t := by rw [← image_eq_image hf.1, hf.2.image_preimage] lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} : s = f ⁻¹' t ↔ f '' s = t := by rw [← image_eq_image hf.1, hf.2.image_preimage] end image_preimage /-! ### Lemmas about images of binary and ternary functions -/ section n_ary_image variables {α β γ δ ε : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} /-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ := {c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c } lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl @[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, h1, h2, rfl⟩ lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ }, λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) } lemma forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := ⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩ @[simp] lemma image2_subset_iff {u : set γ} : image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image2_iff lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := begin ext c, split, { rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] } end lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := begin ext c, split, { rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] } end @[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp @[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } @[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp @[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp @[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image2 f s t = image2 f' s t := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ } /-- A common special case of `image2_congr` -/ lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr (λ a _ b _, h a b) /-- The image of a ternary function `f : α → β → γ → δ` as a function `set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ := {d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d } @[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d := iff.rfl @[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) : image3 g s t u = image3 g' s t u := by { ext x, split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ } /-- A common special case of `image3_congr` -/ lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u := image3_congr (λ a _ b _ c _, h a b c) lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) : image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u := begin ext, split, { rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ } end lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) : image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u := begin ext, split, { rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ } end lemma image2_assoc {ε'} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := by simp only [image2_image2_left, image2_image2_right, h_assoc] lemma image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (λ a b, g (f a b)) s t := begin ext, split, { rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ } end lemma image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t := begin ext, split, { rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ } end lemma image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t := begin ext, split, { rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ } end lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ } @[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image_prod (f : α → β → γ) : (λ x : α × β, f x.1 x.2) '' s.prod t = image2 f s t := set.ext $ λ a, ⟨ by { rintros ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.mp ‹_›).1, (mem_prod.mp ‹_›).2, rfl⟩ }, by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }⟩ lemma nonempty.image2 (hs : s.nonempty) (ht : t.nonempty) : (image2 f s t).nonempty := by { cases hs with a ha, cases ht with b hb, exact ⟨f a b, ⟨a, b, ha, hb, rfl⟩⟩ } end n_ary_image end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} : x ∈ s ↔ s.nonempty := ⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩ end subsingleton
bee1bc7e438cf180736586386cfef4817e4739bd
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/order.lean
4d4c61bb434e1e026f2324c40f04cf711af58f70
[ "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
29,413
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 is_open.mem_nhds (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_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 = ⊥) @[priority 100] instance discrete_topology_bot (α : Type*) : @discrete_topology α ⊥ := { eq_bot := rfl } @[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 := is_open_compl_iff.1 $ (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := continuous_def.2 $ λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @is_open.mem_nhds α ⊥ 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) lemma forall_open_iff_discrete {X : Type*} [topological_space X] : (∀ s : set X, is_open s) ↔ discrete_topology X := ⟨λ h, ⟨by { ext U , show is_open U ↔ true, simp [h U] }⟩, λ a, @is_open_discrete _ _ a⟩ lemma singletons_open_iff_discrete {X : Type*} [topological_space X] : (∀ a : X, is_open ({a} : set X)) ↔ discrete_topology X := ⟨λ h, ⟨eq_bot_of_singletons_open h⟩, λ a _, @is_open_discrete _ _ a _⟩ 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 ∧ f ⁻¹' t = s) := begin simp only [← is_open_compl_iff, is_open_induced_iff], exact ⟨λ ⟨t, ht, heq⟩, ⟨tᶜ, by rwa compl_compl, by simp [preimage_compl, heq, compl_compl]⟩, λ ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ end /-- 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 lemma preimage_nhds_coinduced [topological_space α] {π : α → β} {s : set β} {a : α} (hs : s ∈ @nhds β (topological_space.coinduced π ‹_›) (π a)) : π ⁻¹' s ∈ 𝓝 a := begin letI := topological_space.coinduced π ‹_›, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, exact mem_nhds_iff.mpr ⟨π ⁻¹' V, set.preimage_mono hVs, V_op, mem_V⟩ end variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma continuous.coinduced_le (h : @continuous α β t t' f) : t.coinduced f ≤ t' := λ s hs, (continuous_def.1 h s hs : _) 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 continuous.le_induced (h : @continuous α β t t' f) : t ≤ t'.induced f := coinduced_le_iff_le_induced.1 h.coinduced_le 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 induced_const [t : topological_space α] {x : α} : t.induced (λ y : β, x) = ⊤ := le_antisymm le_top (@continuous_const β α ⊤ t x).le_induced 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 pempty := ⊥ instance : discrete_topology pempty := ⟨rfl⟩ instance : topological_space punit := ⊥ instance : discrete_topology punit := ⟨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₂ := continuous_def.trans 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 @[continuity] lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := by { rw continuous_def, assume s h, exact ⟨_, h, rfl⟩ } lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := begin rw continuous_def, rintros s ⟨t, ht, s_eq⟩, simpa [← s_eq] using continuous_def.1 h t ht, end lemma continuous_induced_rng' [topological_space α] [topological_space β] [topological_space γ] {g : γ → α} (f : α → β) (H : ‹topological_space α› = ‹topological_space β›.induced f) (h : continuous (f ∘ g)) : continuous g := H.symm ▸ continuous_induced_rng h lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := by { rw continuous_def, assume s h, exact h } lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := begin rw continuous_def at h ⊢, assume s hs, exact h _ hs end lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₁ _ (h₂ s h) end lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₂ s (h₁ s h) end lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := begin rw continuous_def at h₁ h₂ ⊢, assume s h, exact ⟨h₁ s h, h₂ s h⟩ end 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_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)) := by { ext s, rw [mem_nhds_induced, 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 : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] (f a) := by rw [nhds_induced, filter.map_comap, nhds_within] lemma map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap_of_mem h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := by simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm] 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 is_open_singleton_true.preimage h, 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]⟩ lemma is_open_iff_continuous_mem {s : set α} : is_open s ↔ continuous (λ x, x ∈ s) := continuous_Prop.symm 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 := by simp [← is_open_compl_iff, is_open_supr_iff] end infi
91110ed4f581939d54f956ce0989bb6973f482a5
791eaf247d44ef2d812f6b2fe1c021232e9ce686
/src/bb_alg.lean
92142193030cfb5ba1c6b7753d9c75b012c4c91f
[]
no_license
MarkosDe/bb_alg
2f100b2e82bfa95a85863eedb33d9aea542bd5c2
11b12ab83de0da825857b4f9bb8304475be05877
refs/heads/master
1,587,996,505,019
1,558,014,699,000
1,558,014,699,000
174,397,884
0
1
null
null
null
null
UTF-8
Lean
false
false
11,653
lean
import data.polynomial linear_algebra.multivariate_polynomial import ring_theory.ideals data.nat.choose order.zorn import algebra.module open set open ring open polynomial universes u section variables {σ : Type*} [decidable_linear_order σ] -- '.sort' makes list def multiset.lex (m1 m2 : multiset σ) : Prop := m1.sort (≥) ≤ m2.sort (≥) instance (m1 m2 : multiset σ) : decidable (multiset.lex m1 m2) := by unfold multiset.lex; apply_instance -- example : linear_order (list σ) := by apply_instance lemma multiset.sort_ext {m1 m2 : multiset σ} : m1 = m2 ↔ m1.sort(≥) = m2.sort(≥) := iff.intro (sorry) (assume h, multiset.ext.2 sorry) def multiset.lex_is_total (σ) [decidable_linear_order σ]: decidable_linear_order (multiset σ) := { le := multiset.lex, le_refl := λ m, le_refl _, le_trans := λ m1 m2 m3 h1 h2, le_trans h1 h2, le_antisymm := λ m1 m2 h1 h2, multiset.sort_ext.2 (le_antisymm h1 h2), le_total := λ m1 m2, le_total _ _, decidable_le := λ _ _, by apply_instance } end local attribute [instance, priority 10000] multiset.lex_is_total -- example (σ) [decidable_linear_order σ]: -- ∀ a b : σ , decidable (a ≤ b) :=--decidable_rel ((≤) : multiset σ → multiset σ → Prop) := -- by apply_instance def my_mvpolynomial (σ : Type*) (α: Type*) [comm_semiring α]: Type* := finsupp (multiset σ) α variables {α : Type} {σ : Type*} [decidable_linear_order σ] [discrete_linear_ordered_field α] --to mame * between my_mvpolynomials instance : comm_ring (my_mvpolynomial σ α):= finsupp.to_comm_ring example : linear_order (multiset σ) := by apply_instance example : partial_order (multiset σ) := by apply_instance def my_mvpolynomial.coef (pol : my_mvpolynomial σ α): multiset σ -> α := pol.to_fun --DEGREE of MONOMIAL def monomial_degree (ms: multiset σ) : ℕ := multiset.card ms def my_mvpolynomial.leading_mon (pol: my_mvpolynomial σ α ) : option (multiset σ) := (finsupp.support pol).max def degree_LM (pol: my_mvpolynomial σ α) : ℕ := monomial_degree ((my_mvpolynomial.leading_mon pol).iget) def is_zero (pol : my_mvpolynomial σ α) : bool := pol = 0 def zero_ideal := ([0]: list (my_mvpolynomial σ α)) --variables (polt1 polt2: my_mvpolynomial σ α) def my_mvpolynomial.leading_coef (pol: my_mvpolynomial σ α): α := match (my_mvpolynomial.leading_mon pol) with | some ms := pol.coef ms | none := 0 end -----LEADING TERM def my_mvpolynomial.l_t (pol: my_mvpolynomial σ α ) : my_mvpolynomial σ α := finsupp.single (my_mvpolynomial.leading_mon pol).iget (my_mvpolynomial.leading_coef pol) --Representation of the polynomial def my_mvpolynomial.repr [has_repr σ] [has_repr α] (p : my_mvpolynomial σ α) : string := if p = 0 then "0" else ((finsupp.support p).sort multiset.lex).foldr (λ ms s, let coef := p.to_fun ms in s ++ (if (coef ≥ 0 ∧ s.length > 0) then " +" ++ repr coef else " " ++ repr coef) ++ repr ms ) "" instance [has_repr σ] [has_repr α] : has_repr (my_mvpolynomial σ α) := ⟨my_mvpolynomial.repr⟩ --used in for LCM of monomials def multiset.add_repeats (ms: multiset σ) (aa : σ) (n: nat) : multiset σ := (multiset.repeat aa n) + ms #check @multiset.add_repeats #eval multiset.add_repeats ({} : multiset ℕ) 2 5 --finds LCM of LM1 LM2, outputs in diff order --for every x add to {} the max repetitions from m1 m2 def multiset.mon_LCM (m1 m2 : multiset σ) : multiset σ := ((m1.to_finset) ∪ (m2.to_finset)).fold multiset.add ({}) (λ x, multiset.add_repeats ({} : multiset σ) x (max (multiset.count x m1) (multiset.count x m2))) #check multiset.mon_LCM #eval multiset.mon_LCM ({3,3,2} : multiset ℕ) ({2,2, 8} : multiset ℕ) def example_pol: my_mvpolynomial ℕ ℚ := finsupp.single {1,3} 1 - finsupp.single {2,2} 1 --representation #eval example_pol #eval my_mvpolynomial.leading_coef example_pol #eval my_mvpolynomial.leading_mon example_pol #eval my_mvpolynomial.l_t example_pol --define polyniomial examples def f1: my_mvpolynomial ℕ ℚ := finsupp.single {3,3,2} 1 - finsupp.single {} 1 def f2: my_mvpolynomial ℕ ℚ := finsupp.single {3,2,2} 1 - finsupp.single {3} 1 def f3: my_mvpolynomial ℕ ℚ := finsupp.single {3,3} 1 - finsupp.single {2} 1 def f4: my_mvpolynomial ℕ ℚ := finsupp.single {2,2} 1 - finsupp.single {} 1 def g1: my_mvpolynomial ℕ ℚ := finsupp.single {3,3} 1 + finsupp.single {3,2,2} 1 def g2: my_mvpolynomial ℕ ℚ := finsupp.single {3,3} 1 - finsupp.single {2,2,2} 1 def g3: my_mvpolynomial ℕ ℚ := finsupp.single {2,2,2} 1 - finsupp.single {2,2} 1 def g4: my_mvpolynomial ℕ ℚ := finsupp.single {3,2,2} 1 + finsupp.single {2,2} 1 --LCM(LM1, LM2) / LM1 def s_monomial_l (pol1 pol2: my_mvpolynomial σ α): multiset σ := let lmp1 := (my_mvpolynomial.leading_mon pol1).iget in (multiset.mon_LCM lmp1 (my_mvpolynomial.leading_mon pol2).iget) - lmp1 #eval f1 #eval my_mvpolynomial.leading_coef f1 #eval my_mvpolynomial.leading_mon f1 #eval my_mvpolynomial.l_t f1 #eval s_monomial_l f1 f2 #eval s_monomial_l f1 f3 #eval s_monomial_l f2 f3 --LCM(LM1, LM2) / LM2 def s_monomial_r (pol1 pol2: my_mvpolynomial σ α): multiset σ := let lmp2 := (my_mvpolynomial.leading_mon pol2).iget in (multiset.mon_LCM (my_mvpolynomial.leading_mon pol1).iget lmp2) - lmp2 #eval my_mvpolynomial.leading_mon f2 #eval multiset.mon_LCM (my_mvpolynomial.leading_mon f1).iget (my_mvpolynomial.leading_mon f2).iget #eval s_monomial_r f1 f2 #eval s_monomial_r f1 f3 #eval s_monomial_r f2 f3 --(LCM(LM1, LM2) / LT1) * 1 --(take monomaial and coef and make poly) * pol1 def s_polynomial_l (pol1 pol2: my_mvpolynomial σ α) : my_mvpolynomial σ α := (finsupp.single (s_monomial_l pol1 pol2) (1 / (my_mvpolynomial.leading_coef pol1))) * pol1 #eval s_polynomial_l f1 f2 #eval s_polynomial_l f1 f3 #eval s_polynomial_l f2 f3 --(LCM(LM1, LM2) / LT2) * 2 def s_polynomial_r (pol1 pol2: my_mvpolynomial σ α) : my_mvpolynomial σ α := (finsupp.single (s_monomial_r pol1 pol2) (1 / (my_mvpolynomial.leading_coef pol2))) * pol2 #eval s_polynomial_r f1 f2 #eval s_polynomial_r f1 f3 #eval s_polynomial_r f2 f3 -- S-Pol -- S(pol1,pol2) = s_polynomial_l - s_polynomial_r def s_polynomial (pol1 pol2: my_mvpolynomial σ α) : my_mvpolynomial σ α := (s_polynomial_l pol1 pol2) - (s_polynomial_r pol1 pol2) #eval s_polynomial f1 f2 #eval s_polynomial f1 f3 #eval s_polynomial f2 f3 --pol2 = num, pol1 = den --gives which mon from pol2 can be divided with lm(pol1) def divide_witness (pol_d pol_n : my_mvpolynomial σ α) : option (multiset σ) := let lmp1 := (my_mvpolynomial.leading_mon pol_d).iget in list.find (λ s2, ∀ s ∈ lmp1, (lmp1).count s ≤ (s2: multiset σ).count s) ((finsupp.support pol_n).sort multiset.lex) --make multiset from divide_witness a polynomial def divide_witness_pol (pol_d pol_n : my_mvpolynomial σ α) : my_mvpolynomial σ α := match divide_witness pol_d pol_n with | some ms := finsupp.single ms (pol_n.to_fun ms) | none := 0 end -- n/d, q = 0, r = n, --while divides tt, t = (C(r) / LC(d)) * (M(r) / LM(d)) -- q = q + t, -- r = r - t * d def find_pol_t (pol_r pol_d: my_mvpolynomial σ α) : my_mvpolynomial σ α := let dw := (divide_witness pol_d pol_r).iget in finsupp.single (dw - (my_mvpolynomial.leading_mon pol_d).iget) ((divide_witness_pol pol_d pol_r).coef dw / my_mvpolynomial.leading_coef pol_d) --pol_n = pol_d * q + r -> pol_n/pol_d = q + (r / pol_d) def find_new_q (pol_r pol_d pol_q: my_mvpolynomial σ α) : my_mvpolynomial σ α := (pol_q + find_pol_t pol_r pol_d) def find_new_r (pol_r pol_d: my_mvpolynomial σ α) : my_mvpolynomial σ α := pol_r - (find_pol_t pol_r pol_d) * pol_d -- def smaller (pp1 pp2: my_mvpolynomial σ α) : bool := -- (((pp1.leading_mon α σ).iget).sort (≥) < ((pp2.leading_mon _ _).iget).sort (≥)) -- #eval smaller _ _ f1 f2 variables (σ α) def wf_rel : (Σ' n : my_mvpolynomial σ α, list(my_mvpolynomial σ α)) → (Σ' n : my_mvpolynomial σ α , list (my_mvpolynomial σ α)) → Prop := λ m1 m2, ((m2.1.leading_mon).iget).sort (≥) < ((m1.1.leading_mon).iget).sort (≥) #check wf_rel _ _ -- #check @well_founded _ lemma wf_rel_wf : well_founded (wf_rel α σ) := sorry variables {σ α} def long_div: my_mvpolynomial σ α -> list (my_mvpolynomial σ α) -> my_mvpolynomial σ α | pol_n (h::t) := have h1 : wf_rel α σ ⟨find_new_r pol_n h, h::t⟩ ⟨pol_n, h::t⟩, from sorry, have h2 : wf_rel α σ ⟨pol_n, t⟩ ⟨pol_n, h::t⟩, from sorry, if (divide_witness h pol_n) = none then long_div pol_n t else long_div (find_new_r pol_n h) (h::t) | pol_n [] := pol_n using_well_founded {rel_tac := λ α σ, `[exact ⟨wf_rel α σ, wf_rel_wf α σ⟩], dec_tac := `[assumption]} #eval long_div (s_polynomial f1 f2) [f1,f2] #eval long_div (s_polynomial f2 f2) [f1,f2,f3,f4] #eval long_div (s_polynomial f3 f3) [f1,f2,f3,f4] #eval long_div (s_polynomial f4 f4) [f1,f2,f3,f4] #eval long_div (s_polynomial f1 f3) [f1,f2,f3] #eval long_div (s_polynomial f1 f3) [f1,f2,f3] #eval long_div (s_polynomial f2 f3) [f1,f2,f3] #eval long_div (s_polynomial f2 f4) [f1,f2,f3,f4] #eval long_div (s_polynomial f3 f4) [f1,f2,f3,f4] #eval long_div (0) [f1,f2,f3,f4] ------------------------------- Definition Ideal.---------------------- -- A subset I ⊂ k[x1, . . . , xn] is an ideal if it satisfies: -- (i) 0 ∈ I . -- (ii) If f, g ∈ I , then f + g ∈ I . -- (iii) If f ∈ I and h ∈ k[x1, . . . , xn], then h f ∈ I . ------------------------------------- Lemma ----------------------------- -- If f1, . . . , fs polynomials in k[x1, . . . , xn], then ⟨f1, . . . , fs⟩ is an ideal of -- k[x1, . . . , xn]. We call ⟨f1,...,fs⟩ the ideal generated by f1,...,fs --a basis G = {g1,...,gt} for I ≠ pol_zero is a gb if ∀ pairs i ≠ j the remainder of S(gi, gt) / G (use my long_div) == 0 def bb_criterion (basis: list (my_mvpolynomial σ α)) : bool := ∀ x ∈ basis, ∀ y ∈ basis, x ≠ y -> (long_div (s_polynomial x y) (basis) = 0) --let I a pol ideal ≠ 0. then a gb for I can be constructed in a finite n of steps by the alg: --1 input is an I = <f1, ... ,fs> --2 output a GB, G = (g1, . . . , gt) for I , with F ⊂ G --3 take input, F = (f1,...,fs). ∀ pairs i ≠ j, if remainder of S_pol is ≠ 0, add it to F --check case where s_pol = 0, also should be r = 0 -- G := F -- REPEAT -- G := G -- FOR each pair {p,q}, p = q in G DO -- S := S(p,q)G -- IF S = 0 THEN G := G ∪ {S} -- UNTIL G = G -- def smaller (pp1 pp2: my_mvpolynomial σ α) : bool := -- (((pp1.leading_mon _ _).iget).sort (≥) ≤ ((pp2.leading_mon _ _).iget).sort (≥)) --every nonzero ideal I ⊂ k[x1, . . . , xn] has a Groebner basis --(h: my_ideal ≠ zero_ideal α σ) meta def bb_alg_ax: list(my_mvpolynomial σ α) -> list (my_mvpolynomial σ α) | [] := [] | (h::t) := ((h::t) : list (my_mvpolynomial σ α)).foldr(λ p l, (((h::t): list (my_mvpolynomial σ α)).foldr(λ p1 l1, let remainder := (long_div (s_polynomial p p1) (h::t)) in if (remainder ≠ 0 ∧ remainder ∉ ((h::t) : list (my_mvpolynomial σ α))) then bb_alg_ax ((h::t) ++ [remainder]) else l1)) (l)) (h::t) meta def bb_alg: list(my_mvpolynomial σ α) -> list (my_mvpolynomial σ α) | [] := [] | [zero_ideal] := [] | (h::t) := bb_alg_ax (h::t) #eval bb_alg [f1, f2] #eval bb_alg [g1,g2,g3] #eval bb_criterion [f1,f2,f3,f4] #eval bb_criterion [f1,f2] #eval bb_criterion [g1,g2,g3,g4]
ca0a4e5f60bc74a9c7ca72ab2cec36d9fb71caae
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Parser/Extension.lean
5ac78213036ea175c02917b9919c0b01ff346cae
[ "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
25,754
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ /-! Extensible parsing via attributes -/ import Lean.Parser.Basic import Lean.Parser.StrInterpolation import Lean.KeyedDeclsAttribute namespace Lean namespace Parser builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {} /- Global table with all SyntaxNodeKind's -/ builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {} def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit := builtinSyntaxNodeKindSetRef.modify fun s => s.insert k builtin_initialize registerBuiltinNodeKind choiceKind registerBuiltinNodeKind identKind registerBuiltinNodeKind strLitKind registerBuiltinNodeKind numLitKind registerBuiltinNodeKind charLitKind registerBuiltinNodeKind nameLitKind builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {} private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α := throw s!"parser category '{catName}' has already been defined" private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories := if categories.contains catName then throwParserCategoryAlreadyDefined catName else pure $ categories.insert catName initial /-- All builtin parser categories are Pratt's parsers -/ private def addBuiltinParserCategory (catName : Name) (leadingIdentAsSymbol : Bool) : IO Unit := do let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol} builtinParserCategoriesRef.set categories inductive ParserExtensionOleanEntry | token (val : Token) : ParserExtensionOleanEntry | kind (val : SyntaxNodeKind) : ParserExtensionOleanEntry | category (catName : Name) (leadingIdentAsSymbol : Bool) | parser (catName : Name) (declName : Name) (prio : Nat) : ParserExtensionOleanEntry inductive ParserExtensionEntry | token (val : Token) : ParserExtensionEntry | kind (val : SyntaxNodeKind) : ParserExtensionEntry | category (catName : Name) (leadingIdentAsSymbol : Bool) | parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : ParserExtensionEntry structure ParserExtensionState := (tokens : TokenTable := {}) (kinds : SyntaxNodeKindSet := {}) (categories : ParserCategories := {}) (newEntries : List ParserExtensionOleanEntry := []) instance : Inhabited ParserExtensionState := ⟨{}⟩ abbrev ParserExtension := PersistentEnvExtension ParserExtensionOleanEntry ParserExtensionEntry ParserExtensionState private def ParserExtension.mkInitial : IO ParserExtensionState := do let tokens ← builtinTokenTable.get let kinds ← builtinSyntaxNodeKindSetRef.get let categories ← builtinParserCategoriesRef.get pure { tokens := tokens, kinds := kinds, categories := categories } private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do if tk == "" then throw "invalid empty symbol" else match tokens.find? tk with | none => pure $ tokens.insert tk tk | some _ => pure tokens def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α := throw s!"unknown parser category '{catName}'" abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory := categories.find? catName def addLeadingParser (categories : ParserCategories) (catName : Name) (parserName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => let addTokens (tks : List Token) : Except String ParserCategories := let tks := tks.map $ fun tk => Name.mkSimple tk let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with leadingTable := tables.leadingTable.insert tk (p, prio) }) cat.tables pure $ categories.insert catName { cat with tables := tables } match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers } pure $ categories.insert catName { cat with tables := tables } private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables := let addTokens (tks : List Token) : PrattParsingTables := let tks := tks.map fun tk => Name.mkSimple tk tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with trailingTable := tables.trailingTable.insert tk (p, prio) }) tables match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers } def addTrailingParser (categories : ParserCategories) (catName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => pure $ categories.insert catName { cat with tables := addTrailingParserAux cat.tables p prio } def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := match leading, p with | true, p => addLeadingParser categories catName declName p prio | false, p => addTrailingParser categories catName p prio def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable := let newTokens := info.collectTokens [] newTokens.foldlM addTokenConfig tokenTable private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do let tokenTable ← builtinTokenTable.swap {} match addParserTokens tokenTable info with | Except.ok tokenTable => builtinTokenTable.set tokenTable | Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}") def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParser categories catName declName leading p prio builtinParserCategoriesRef.set categories builtinSyntaxNodeKindSetRef.modify p.info.collectKinds updateBuiltinTokens p.info declName def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit := addBuiltinParser catName declName true p prio def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit := addBuiltinParser catName declName false p prio private def ParserExtensionAddEntry (s : ParserExtensionState) (e : ParserExtensionEntry) : ParserExtensionState := match e with | ParserExtensionEntry.token tk => match addTokenConfig s.tokens tk with | Except.ok tokens => { s with tokens := tokens, newEntries := ParserExtensionOleanEntry.token tk :: s.newEntries } | _ => unreachable! | ParserExtensionEntry.kind k => { s with kinds := s.kinds.insert k, newEntries := ParserExtensionOleanEntry.kind k :: s.newEntries } | ParserExtensionEntry.category catName leadingIdentAsSymbol => if s.categories.contains catName then s else { s with categories := s.categories.insert catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol }, newEntries := ParserExtensionOleanEntry.category catName leadingIdentAsSymbol :: s.newEntries } | ParserExtensionEntry.parser catName declName leading parser prio => match addParser s.categories catName declName leading parser prio with | Except.ok categories => { s with categories := categories, newEntries := ParserExtensionOleanEntry.parser catName declName prio :: s.newEntries } | _ => unreachable! unsafe def mkParserOfConstantUnsafe (env : Environment) (opts : Options) (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → Except String Parser) : Except String (Bool × Parser) := match env.find? constName with | none => throw s!"unknow constant '{constName}'" | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => do let p ← env.evalConst Parser opts constName pure ⟨false, p⟩ | Expr.const `Lean.Parser.Parser _ _ => do let p ← env.evalConst Parser opts constName pure ⟨true, p⟩ | Expr.const `Lean.ParserDescr _ _ => do let d ← env.evalConst ParserDescr opts constName let p ← compileParserDescr d pure ⟨true, p⟩ | Expr.const `Lean.TrailingParserDescr _ _ => do let d ← env.evalConst TrailingParserDescr opts constName let p ← compileParserDescr d pure ⟨false, p⟩ | _ => throw s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected" @[implementedBy mkParserOfConstantUnsafe] constant mkParserOfConstantAux (env : Environment) (opts : Options) (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → Except String Parser) : Except String (Bool × Parser) partial def compileParserDescr (env : Environment) (opts : Options) (categories : ParserCategories) (d : ParserDescr) : Except String Parser := let rec visit : ParserDescr → Except String Parser | ParserDescr.andthen d₁ d₂ => andthen <$> visit d₁ <*> visit d₂ | ParserDescr.orelse d₁ d₂ => orelse <$> visit d₁ <*> visit d₂ | ParserDescr.optional d => optional <$> visit d | ParserDescr.lookahead d => lookahead <$> visit d | ParserDescr.«try» d => «try» <$> visit d | ParserDescr.notFollowedBy d => do let p ← visit d; pure $ notFollowedBy p "element" -- TODO allow user to set msg at ParserDescr | ParserDescr.many d => many <$> visit d | ParserDescr.many1 d => many1 <$> visit d | ParserDescr.sepBy d₁ d₂ b => sepBy (allowTrailingSep := b) <$> visit d₁ <*> visit d₂ | ParserDescr.sepBy1 d₁ d₂ b => sepBy1 (allowTrailingSep := b) <$> visit d₁ <*> visit d₂ | ParserDescr.node k prec d => leadingNode k prec <$> visit d | ParserDescr.trailingNode k prec d => trailingNode k prec <$> visit d | ParserDescr.symbol tk => pure $ symbol tk | ParserDescr.noWs => pure $ checkNoWsBefore | ParserDescr.numLit => pure $ numLit | ParserDescr.strLit => pure $ strLit | ParserDescr.charLit => pure $ charLit | ParserDescr.nameLit => pure $ nameLit | ParserDescr.interpolatedStr d => interpolatedStr <$> visit d | ParserDescr.ident => pure $ ident | ParserDescr.checkCol strict => pure $ if strict then checkColGt else checkColGe | ParserDescr.withPosition d => withPosition <$> visit d | ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol tk includeIdent | ParserDescr.parser constName => do let (_, p) ← mkParserOfConstantAux env opts categories constName visit; pure p | ParserDescr.cat catName prec => match getCategory categories catName with | some _ => pure $ categoryParser catName prec | none => throwUnknownParserCategory catName visit d def mkParserOfConstant (env : Environment) (opts : Options) (categories : ParserCategories) (constName : Name) : Except String (Bool × Parser) := mkParserOfConstantAux env opts categories constName (compileParserDescr env opts categories) structure ParserAttributeHook := /- Called after a parser attribute is applied to a declaration. -/ (postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit) builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {} def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do parserAttributeHooks.modify fun hooks => hook::hooks def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do let hooks ← parserAttributeHooks.get hooks.forM fun hook => hook.postAdd catName declName builtin builtin_initialize registerBuiltinAttribute { name := `runBuiltinParserAttributeHooks, descr := "explicitly run hooks normally activated by builtin parser attributes", add := fun decl args persistent => do if args.hasArgs then throwError "invalid attribute 'runBuiltinParserAttributeHooks', unexpected argument" runParserAttributeHooks Name.anonymous decl (builtin := true) } builtin_initialize registerBuiltinAttribute { name := `runParserAttributeHooks, descr := "explicitly run hooks normally activated by parser attributes", add := fun decl args persistent => do if args.hasArgs then throwError "invalid attribute 'runParserAttributeHooks', unexpected argument" runParserAttributeHooks Name.anonymous decl (builtin := false) } private def ParserExtension.addImported (es : Array (Array ParserExtensionOleanEntry)) : ImportM ParserExtensionState := do let ctx ← read let s ← ParserExtension.mkInitial es.foldlM (init := s) fun s entries => entries.foldlM (init := s) fun s entry => match entry with | ParserExtensionOleanEntry.token tk => do let tokens ← IO.ofExcept (addTokenConfig s.tokens tk) pure { s with tokens := tokens } | ParserExtensionOleanEntry.kind k => pure { s with kinds := s.kinds.insert k } | ParserExtensionOleanEntry.category catName leadingIdentAsSymbol => do let categories ← IO.ofExcept (addParserCategoryCore s.categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol}) pure { s with categories := categories } | ParserExtensionOleanEntry.parser catName declName prio => do let p ← IO.ofExcept $ mkParserOfConstant ctx.env ctx.opts s.categories declName let categories ← IO.ofExcept $ addParser s.categories catName declName p.1 p.2 prio pure { s with categories := categories } builtin_initialize parserExtension : ParserExtension ← registerPersistentEnvExtension { name := `parserExt, mkInitial := ParserExtension.mkInitial, addImportedFn := ParserExtension.addImported, addEntryFn := ParserExtensionAddEntry, exportEntriesFn := fun s => s.newEntries.reverse.toArray, statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length } def isParserCategory (env : Environment) (catName : Name) : Bool := (parserExtension.getState env).categories.contains catName def addParserCategory (env : Environment) (catName : Name) (leadingIdentAsSymbol : Bool) : Except String Environment := do if isParserCategory env catName then throwParserCategoryAlreadyDefined catName else pure $ parserExtension.addEntry env $ ParserExtensionEntry.category catName leadingIdentAsSymbol /- Return true if in the given category leading identifiers in parsers may be treated as atoms/symbols. See comment at `ParserCategory`. -/ def leadingIdentAsSymbol (env : Environment) (catName : Name) : Bool := match getCategory (parserExtension.getState env).categories catName with | none => false | some cat => cat.leadingIdentAsSymbol def mkCategoryAntiquotParser (kind : Name) : Parser := mkAntiquot kind.toString none -- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377 @[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn := (mkCategoryAntiquotParser kind).fn def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s => let catName := if catName == `syntax then `stx else catName -- temporary Hack let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | some cat => prattParser catName cat.tables cat.leadingIdentAsSymbol (mkCategoryAntiquotParserFn catName) ctx s | none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'") @[builtinInit] def setCategoryParserFnRef : IO Unit := categoryParserFnRef.set categoryParserFnImpl def addToken (env : Environment) (tk : Token) : Except String Environment := do -- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail. -- So, we must run it here to handle exception. addTokenConfig (parserExtension.getState env).tokens tk pure $ parserExtension.addEntry env $ ParserExtensionEntry.token tk def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment := parserExtension.addEntry env $ ParserExtensionEntry.kind k def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool := let kinds := (parserExtension.getState env).kinds kinds.contains k def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do let kinds := (parserExtension.getState env).kinds kinds.foldl (fun ks k _ => k::ks) [] def getTokenTable (env : Environment) : TokenTable := (parserExtension.getState env).tokens def mkInputContext (input : String) (fileName : String) : InputContext := { input := input, fileName := fileName, fileMap := input.toFileMap } def mkParserContext (env : Environment) (ctx : InputContext) : ParserContext := { prec := 0, toInputContext := ctx, env := env, tokens := getTokenTable env } def mkParserState (input : String) : ParserState := { cache := initCacheForInput input } /- convenience function for testing -/ def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax := let c := mkParserContext env (mkInputContext input fileName) let s := mkParserState input let s := whitespace c s let s := categoryParserFnImpl catName c s if s.hasError then Except.error (s.toErrorMsg c) else if input.atEnd s.pos then Except.ok s.stxStack.back else Except.error ((s.mkError "end of input").toErrorMsg c) def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := let name := `_regBuiltinParser ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkNatLit prio] let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'")) | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName prio def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser catName declName prio def getParserPriority (args : Syntax) : Except String Nat := match args.getNumArgs with | 0 => pure 0 | 1 => match (args.getArg 0).isNatLit? with | some prio => pure prio | none => throw "invalid parser attribute, numeral expected" | _ => throw "invalid parser attribute, no argument or numeral expected" private def BuiltinParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (args : Syntax) (persistent : Bool) : AttrM Unit := do let prio ← ofExcept (getParserPriority args) unless persistent do throwError! "invalid attribute '{attrName}', must be persistent" let decl ← getConstInfo declName let env ← getEnv match decl.type with | Expr.const `Lean.Parser.TrailingParser _ _ => do let env ← liftIO $ declareTrailingBuiltinParser env catName declName prio setEnv env | Expr.const `Lean.Parser.Parser _ _ => do let env ← liftIO $ declareLeadingBuiltinParser env catName declName prio setEnv env | _ => throwError! "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)" runParserAttributeHooks catName declName (builtin := true) /- The parsing tables for builtin parsers are "stored" in the extracted source code. -/ def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Unit := do addBuiltinParserCategory catName leadingIdentAsSymbol registerBuiltinAttribute { name := attrName, descr := "Builtin parser", add := fun declName args persistent => liftM $ BuiltinParserAttribute.add attrName catName declName args persistent, applicationTime := AttributeApplicationTime.afterCompilation } private def ParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (args : Syntax) (persistent : Bool) : AttrM Unit := do let prio ← ofExcept (getParserPriority args) let env ← getEnv let opts ← getOptions let categories := (parserExtension.getState env).categories match mkParserOfConstant env opts categories declName with | Except.error ex => throwError ex | Except.ok p => do let leading := p.1 let parser := p.2 let tokens := parser.info.collectTokens [] tokens.forM fun token => do let env ← getEnv match addToken env token with | Except.ok env => setEnv env | Except.error msg => throwError! "invalid parser '{declName}', {msg}" let kinds := parser.info.collectKinds {} kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind match addParser categories catName declName leading parser prio with | Except.ok _ => modifyEnv fun env => parserExtension.addEntry env $ ParserExtensionEntry.parser catName declName leading parser prio | Except.error ex => throwError ex runParserAttributeHooks catName declName /- builtin -/ false def mkParserAttributeImpl (attrName : Name) (catName : Name) : AttributeImpl := { name := attrName, descr := "parser", add := fun declName args persistent => liftM $ ParserAttribute.add attrName catName declName args persistent, applicationTime := AttributeApplicationTime.afterCompilation } /- A builtin parser attribute that can be extended by users. -/ def registerBuiltinDynamicParserAttribute (attrName : Name) (catName : Name) : IO Unit := do registerBuiltinAttribute (mkParserAttributeImpl attrName catName) @[builtinInit] private def registerParserAttributeImplBuilder : IO Unit := registerAttributeImplBuilder `parserAttr fun args => match args with | [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName | _ => throw "invalid parser attribute implementation builder arguments" def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Environment := do let env ← IO.ofExcept $ addParserCategory env catName leadingIdentAsSymbol registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName] -- declare `termParser` here since it is used everywhere via antiquotations builtin_initialize registerBuiltinParserAttribute `builtinTermParser `term builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term -- declare `commandParser` to break cyclic dependency builtin_initialize registerBuiltinParserAttribute `builtinCommandParser `command builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command @[inline] def commandParser (rbp : Nat := 0) : Parser := categoryParser `command rbp def notFollowedByCategoryTokenFn (catName : Name) : ParserFn := fun ctx s => let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | none => s.mkUnexpectedError s!"unknown parser category '{catName}'" | some cat => let (s, stx) := peekToken ctx s match stx with | some (Syntax.atom _ sym) => if ctx.insideQuot && sym == "$" then s else match cat.tables.leadingTable.find? (Name.mkSimple sym) with | some _ => s.mkUnexpectedError (toString catName) | _ => s | _ => s @[inline] def notFollowedByCategoryToken (catName : Name) : Parser := { fn := notFollowedByCategoryTokenFn catName } abbrev notFollowedByCommandToken : Parser := notFollowedByCategoryToken `command abbrev notFollowedByTermToken : Parser := notFollowedByCategoryToken `term end Parser end Lean
fb5da02fc6f1956505e2f6baa3edf536fa19a813
1f6fe2f89976b14a4567ab298c35792b21f2e50b
/univalent_subcategory.hlean
fca280a7e6a3386b2f8271dba786d0ba94d9d949
[ "Apache-2.0" ]
permissive
jonas-frey/Spectral
e5c1c2f7bcac26aa55f7b1e041a81272a146198d
72d521091525a4bc9a31cac859840efe9461cf66
refs/heads/master
1,610,235,743,345
1,505,417,795,000
1,505,417,795,000
102,653,342
0
0
null
1,504,728,483,000
1,504,728,483,000
null
UTF-8
Lean
false
false
14,889
hlean
import homotopy.sphere2 algebra.category.functor.attributes open eq pointed sigma is_equiv equiv fiber algebra group is_trunc function prod prod.ops iso functor namespace category section univ_subcat parameters {C : Precategory} {D : Category} (F : functor C D) (p : is_embedding F) (q : fully_faithful F) variables {a b : carrier C} include p q definition eq_equiv_iso_of_fully_faithful : a = b ≃ a ≅ b := equiv.mk !ap !p -- a = b ≃ F a = F b ⬝e equiv.mk iso_of_eq !iso_of_path_equiv -- F a = F b ≃ F a ≅ F b ⬝e equiv.symm !iso_equiv_F_iso_F -- F a ≅ F b ≃ a ≅ b definition eq_equiv_iso_of_fully_faithful_homot : @eq_equiv_iso_of_fully_faithful a b ~ iso_of_eq := begin intro r, esimp [eq_equiv_iso_of_fully_faithful], refine _ ⬝ left_inv (iso_equiv_F_iso_F F _ _) _, apply ap (inv (to_fun !iso_equiv_F_iso_F)), apply symm, induction r, apply respect_refl end definition is_univalent_domain_of_fully_faithful_embedding : is_univalent C := begin intros, apply homotopy_closed eq_equiv_iso_of_fully_faithful eq_equiv_iso_of_fully_faithful_homot end end univ_subcat definition precategory_Group.{u} [instance] [constructor] : precategory.{u+1 u} Group := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end definition precategory_AbGroup.{u} [instance] [constructor] : precategory.{u+1 u} AbGroup := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end definition Group_is_iso_of_is_equiv {G H : Group} (φ : G →g H) (H : is_equiv (group_fun φ)) : is_iso φ := begin fconstructor, { exact (isomorphism.mk φ H)⁻¹ᵍ }, { apply homomorphism_eq, rexact left_inv φ }, { apply homomorphism_eq, rexact right_inv φ } end definition Group_is_equiv_of_is_iso {G H : Group} (φ : G ⟶ H) (Hφ : is_iso φ) : is_equiv (group_fun φ) := begin fapply adjointify, { exact group_fun φ⁻¹ʰ }, { note p := right_inverse φ, exact ap010 group_fun p }, { note p := left_inverse φ, exact ap010 group_fun p } end definition Group_iso_equiv (G H : Group) : (G ≅ H) ≃ (G ≃g H) := begin fapply equiv.MK, { intro φ, induction φ with φ φi, constructor, exact Group_is_equiv_of_is_iso φ _ }, { intro v, induction v with φ φe, constructor, exact Group_is_iso_of_is_equiv φ _ }, { intro v, induction v with φ φe, apply isomorphism_eq, reflexivity }, { intro φ, induction φ with φ φi, apply iso_eq, reflexivity } end definition Group_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} := begin induction v with m v, induction v with i o, fapply trunctype.mk, { exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) × (Πa, m (i a) a = o) }, { apply is_trunc_of_imp_is_trunc, intro v, induction v with H v, have is_prop (Πa, m a o = a), from _, have is_prop (Πa, m o a = a), from _, have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _, have is_prop (Πa, m (i a) a = o), from _, apply is_trunc_prod } end definition AbGroup_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} := begin induction v with m v, induction v with i o, fapply trunctype.mk, { exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) × (Πa, m (i a) a = o) × (Πa b, m a b = m b a)}, { apply is_trunc_of_imp_is_trunc, intro v, induction v with H v, have is_prop (Πa, m a o = a), from _, have is_prop (Πa, m o a = a), from _, have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _, have is_prop (Πa, m (i a) a = o), from _, have is_prop (Πa b, m a b = m b a), from _, apply is_trunc_prod } end definition AbGroup_sigma.{u} : AbGroup.{u} ≃ Σ A : Type.{u}, ab_group A := begin repeat (assumption | induction a with a b | intro a | fconstructor) end definition Group_sigma.{u} : Group.{u} ≃ Σ A : Type.{u}, group A := begin fconstructor, exact λ a, dpair (Group.carrier a) (Group.struct' a), repeat (assumption | induction a with a b | intro a | fconstructor) end definition group.sigma_char.{u} (A : Type) : group.{u} A ≃ Σ (v : (A → A → A) × (A → A) × A), Group_props v := begin fapply equiv.MK, {intro g, induction g with m s ma o om mo i mi, repeat (fconstructor; do 2 try assumption), }, {intro v, induction v with x v, repeat induction x with y x, repeat induction v with x v, constructor, repeat assumption }, { intro, repeat induction b with b x, induction x, repeat induction x_1 with v x_1, reflexivity }, { intro v, repeat induction v with x v, reflexivity }, end definition Group.sigma_char2.{u} : Group.{u} ≃ Σ(A : Type.{u}) (v : (A → A → A) × (A → A) × A), Group_props v := Group_sigma ⬝e sigma_equiv_sigma_right group.sigma_char definition ab_group.sigma_char.{u} (A : Type) : ab_group.{u} A ≃ Σ (v : (A → A → A) × (A → A) × A), AbGroup_props v := begin fapply equiv.MK, {intro g, induction g with m s ma o om mo i mi, repeat (fconstructor; do 2 try assumption), }, {intro v, induction v with x v, repeat induction x with y x, repeat induction v with x v, constructor, repeat assumption }, { intro, repeat induction b with b x, induction x, repeat induction x_1 with v x_1, reflexivity }, { intro v, repeat induction v with x v, reflexivity }, end definition AbGroup_Group_props {A : Type} (v : (A → A → A) × (A → A) × A) : AbGroup_props v ≃ Group_props v × ∀ a b, v.1 a b = v.1 b a := begin fapply equiv.MK, induction v with m v, induction v with i e, intro, fconstructor, repeat induction a with b a, repeat (fconstructor; assumption), assumption, exact a.2.2.2.2.2, intro, induction a, repeat induction v with b v, repeat induction a with b a, repeat (fconstructor; assumption), assumption, intro b, assert H : is_prop (Group_props v × ∀ a b, v.1 a b = v.1 b a), apply is_trunc_prod, assert K : is_set A, induction b, induction v, induction a_1, induction a_2_1, assumption, exact _, apply is_prop.elim, intro, apply is_prop.elim, end open sigma.ops definition sigma_prod_equiv_sigma_sigma {A} {B C : A→Type} : (Σa, B a × C a) ≃ Σ p : (Σa, B a), C p.1 := sigma_equiv_sigma_right (λa, !sigma.equiv_prod⁻¹ᵉ) ⬝e !sigma_assoc_equiv definition ab_group_equiv_group_comm (A : Type) : ab_group A ≃ Σ (g : group A), ∀ a b : A, a * b = b * a := begin refine !ab_group.sigma_char ⬝e _, refine sigma_equiv_sigma_right AbGroup_Group_props ⬝e _, refine sigma_prod_equiv_sigma_sigma ⬝e _, apply equiv.symm, apply sigma_equiv_sigma !group.sigma_char, intros, induction a, reflexivity end section local attribute group.to_has_mul group.to_has_inv [coercion] theorem inv_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A G ~2 @mul A H) : @inv A G ~ @inv A H := begin have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g, from λg, !mul_inv_cancel_right⁻¹, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4, change Gi ~ Hi, intro g, have p' : Gm ~2 Hm, from p, calc Gi g = Hm (Hm (Gi g) g) (Hi g) : foo ... = Hm (Gm (Gi g) g) (Hi g) : by rewrite p' ... = Hm G1 (Hi g) : by rewrite Gh4 ... = Gm G1 (Hi g) : by rewrite p' ... = Hi g : Gh2 end theorem one_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A (group.to_has_mul G) ~2 @mul A (group.to_has_mul H)) : @one A (group.to_has_one G) = @one A (group.to_has_one H) := begin cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4, exact (Hh2 G1)⁻¹ ⬝ (p H1 G1)⁻¹ ⬝ Gh3 H1, end end definition group_of_Group_props.{u} {A : Type.{u}} {m : A → A → A} {i : A → A} {o : A} (H : Group_props (m, (i, o))) : group A := ⦃group, mul := m, inv := i, one := o, is_set_carrier := H.1, mul_one := H.2.1, one_mul := H.2.2.1, mul_assoc := H.2.2.2.1, mul_left_inv := H.2.2.2.2⦄ theorem Group_eq_equiv_lemma2 {A : Type} {m m' : A → A → A} {i i' : A → A} {o o' : A} (H : Group_props (m, (i, o))) (H' : Group_props (m', (i', o'))) : (m, (i, o)) = (m', (i', o')) ≃ (m ~2 m') := begin have is_set A, from pr1 H, apply equiv_of_is_prop, { intro p, exact apd100 (eq_pr1 p)}, { intro p, apply prod_eq (eq_of_homotopy2 p), apply prod_eq: esimp [Group_props] at *; esimp, { apply eq_of_homotopy, exact inv_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }, { exact one_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }} end open Group theorem Group_eq_equiv_lemma {G H : Group} (p : (sigma_char2 G).1 = (sigma_char2 H).1) : ((sigma_char2 G).2 =[p] (sigma_char2 H).2) ≃ (is_mul_hom (equiv_of_eq (proof p qed : Group.carrier G = Group.carrier H))) := begin refine !sigma_pathover_equiv_of_is_prop ⬝e _, induction G with G g, induction H with H h, esimp [sigma_char2] at p, esimp [sigma_functor] at p, esimp [Group_sigma] at *, induction p, refine !pathover_idp ⬝e _, induction g with s m ma o om mo i mi, induction h with σ μ μa ε εμ με ι μι, exact Group_eq_equiv_lemma2 (sigma_char2 (Group.mk G (group.mk s m ma o om mo i mi))).2.2 (sigma_char2 (Group.mk G (group.mk σ μ μa ε εμ με ι μι))).2.2 end definition isomorphism.sigma_char (G H : Group) : (G ≃g H) ≃ Σ(e : G ≃ H), is_mul_hom e := begin fapply equiv.MK, { intro φ, exact ⟨equiv_of_isomorphism φ, to_respect_mul φ⟩ }, { intro v, induction v with e p, exact isomorphism_of_equiv e p }, { intro v, induction v with e p, induction e, reflexivity }, { intro φ, induction φ with φ H, induction φ, reflexivity }, end definition Group_eq_equiv (G H : Group) : G = H ≃ (G ≃g H) := begin refine (eq_equiv_fn_eq_of_equiv sigma_char2 G H) ⬝e _, refine !sigma_eq_equiv ⬝e _, refine sigma_equiv_sigma_right Group_eq_equiv_lemma ⬝e _, transitivity (Σ(e : (sigma_char2 G).1 ≃ (sigma_char2 H).1), @is_mul_hom _ _ _ _ (to_fun e)), apply sigma_ua, exact !isomorphism.sigma_char⁻¹ᵉ end definition to_fun_Group_eq_equiv {G H : Group} (p : G = H) : Group_eq_equiv G H p ~ isomorphism_of_eq p := begin induction p, reflexivity end definition Group_eq2 {G H : Group} {p q : G = H} (r : isomorphism_of_eq p ~ isomorphism_of_eq q) : p = q := begin apply eq_of_fn_eq_fn (Group_eq_equiv G H), apply isomorphism_eq, intro g, refine to_fun_Group_eq_equiv p g ⬝ r g ⬝ (to_fun_Group_eq_equiv q g)⁻¹, end definition Group_eq_equiv_Group_iso (G₁ G₂ : Group) : G₁ = G₂ ≃ G₁ ≅ G₂ := Group_eq_equiv G₁ G₂ ⬝e (Group_iso_equiv G₁ G₂)⁻¹ᵉ definition category_Group.{u} : category Group.{u} := category.mk precategory_Group begin intro G H, apply is_equiv_of_equiv_of_homotopy (Group_eq_equiv_Group_iso G H), intro p, induction p, fapply iso_eq, apply homomorphism_eq, reflexivity end definition AbGroup_to_Group [constructor] : functor (Precategory.mk AbGroup _) (Category.mk Group category_Group) := mk (λ x : AbGroup, (x : Group)) (λ a b x, x) (λ x, rfl) begin intros, reflexivity end definition is_set_group (X : Type) : is_set (group X) := begin apply is_trunc_of_imp_is_trunc, intros, assert H : is_set X, exact @group.is_set_carrier X a, clear a, apply is_trunc_equiv_closed, apply equiv.symm, apply group.sigma_char end definition ab_group_to_group (A : Type) (g : ab_group A) : group A := _ definition group_comm_to_group (A : Type) : (Σ g : group A, ∀ (a b : A), a*b = b*a) → group A := pr1 definition is_embedding_group_comm_to_group (A : Type) : is_embedding (group_comm_to_group A) := begin unfold group_comm_to_group, intros, induction a, assert H : is_set A, induction a, assumption, assert H :is_set (group A), apply is_set_group, induction a', fconstructor, intros, apply sigma_eq, apply is_prop.elimo, intro, esimp at *, assumption, intros, apply is_prop.elim, intros, apply is_prop.elim, intros, apply is_prop.elim end definition ab_group_to_group_homot (A : Type) : @ab_group_to_group A ~ group_comm_to_group A ∘ ab_group_equiv_group_comm A := begin intro, induction x, reflexivity end definition is_embedding_ab_group_to_group (A : Type) : is_embedding (@ab_group_to_group A) := begin apply is_embedding_homotopy_closed_rev (ab_group_to_group_homot A), apply is_embedding_compose, exact is_embedding_group_comm_to_group A, apply is_embedding_of_is_equiv end definition is_embedding_total_of_is_embedding_fiber {A} {B C : A → Type} {f : Π a, B a → C a} : (∀ a, is_embedding (f a)) → is_embedding (total f) := begin intro e, fapply is_embedding_of_is_prop_fiber, intro p, induction p with a c, assert H : (fiber (total f) ⟨a, c⟩)≃ fiber (f a) c, apply fiber_total_equiv, assert H2 : is_prop (fiber (f a) c), apply is_prop_fiber_of_is_embedding, apply is_trunc_equiv_closed -1 (H⁻¹ᵉ), end definition AbGroup_to_Group_homot : AbGroup_to_Group ~ Group_sigma⁻¹ ∘ total ab_group_to_group ∘ AbGroup_sigma := begin intro g, induction g, reflexivity end definition is_embedding_AbGroup_to_Group : is_embedding AbGroup_to_Group := begin apply is_embedding_homotopy_closed_rev AbGroup_to_Group_homot, apply is_embedding_compose, apply is_embedding_of_is_equiv, apply is_embedding_compose, apply is_embedding_total_of_is_embedding_fiber is_embedding_ab_group_to_group, apply is_embedding_of_is_equiv end definition is_univalent_AbGroup : is_univalent precategory_AbGroup := begin apply is_univalent_domain_of_fully_faithful_embedding AbGroup_to_Group is_embedding_AbGroup_to_Group, intros, apply is_equiv_id end definition category_AbGroup : category AbGroup := category.mk precategory_AbGroup is_univalent_AbGroup definition Grp.{u} [constructor] : Category := category.Mk Group.{u} category_Group definition AbGrp [constructor] : Category := category.Mk AbGroup category_AbGroup end category
bd42093ed957c4e4f8635a99a50d9a7329d4c310
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/MacroRules.lean
8384c81fc0826657c49f8f87c8235bf4c96c320d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
3,342
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Syntax import Lean.Elab.AuxDef namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command /-- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (doc? : Option (TSyntax ``docComment)) (attrs? : Option (TSepArray ``attrInstance ",")) (attrKind : TSyntax ``attrKind) (tk : Syntax) (k : SyntaxNodeKind) (alts : Array (TSyntax ``matchAlt)) : CommandElabM Syntax := do let alts ← alts.mapM fun (alt : TSyntax ``matchAlt) => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0]! if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if checkRuleKind k' k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with | none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $(⟨pats⟩),* => $rhs) else throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax let attr ← `(attrInstance| $attrKind macro $(Lean.mkIdent k)) let attrs := match attrs? with | some attrs => attrs.getElems.push attr | none => #[attr] `($[$doc?:docComment]? @[$attrs,*] aux_def macroRules $(mkIdentFrom tk k (canonical := true)) : Macro := fun $alts:matchAlt* | _ => no_error_if_unused% throw Lean.Macro.Exception.unsupportedSyntax) @[builtin_command_elab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match stx with | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk $alts:matchAlt*) => -- exclude command prefix from synthetic position used for e.g. jumping to the macro definition withRef (mkNullNode #[tk, mkNullNode alts]) do expandNoKindMacroRulesAux alts "macro_rules" fun kind? alts => `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules $[(kind := $(mkIdent <$> kind?))]? $alts:matchAlt*) | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk (kind := $kind) | $x:ident => $rhs) => withRef (mkNullNode #[tk, rhs]) do let attr ← `(attrInstance| $attrKind:attrKind macro $kind) let attrs := match attrs? with | some attrs => attrs.getElems.push attr | none => #[attr] `($[$doc?:docComment]? @[$attrs,*] aux_def $(mkIdentFrom tk kind.getId (canonical := true)) $kind : Macro := fun $x:ident => $rhs) | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro_rules%$tk (kind := $kind) $alts:matchAlt*) => withRef (mkNullNode #[tk, mkNullNode alts]) do elabMacroRulesAux doc? attrs? attrKind tk (← resolveSyntaxKind kind.getId) alts | _ => throwUnsupportedSyntax end Lean.Elab.Command
f1f9b2da65733d158d21646aafae905a94535744
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/pnat/basic.lean
a235d1e72c7309a89b4d71052f20d0db70699a49
[ "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
14,158
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Neil Strickland -/ import data.nat.basic /-! # The positive natural numbers This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : linear_order ℕ+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n:ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n:ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : add_comm_semigroup ℕ+ := { add := λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩, add_comm := λ a b, subtype.eq (add_comm a b), add_assoc := λ a b c, subtype.eq (add_assoc a b c) } @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl instance coe_add_hom : is_add_hom (coe : ℕ+ → ℕ) := ⟨add_coe⟩ instance : add_left_cancel_semigroup ℕ+ := { add_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_right_inj (a : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } instance : add_right_cancel_semigroup ℕ+ := { add_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_left_inj (b : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property, ..(by apply_instance : partial_order ℕ+) } @[simp] lemma bot_eq_zero : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : ℕ+ → ℕ) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : left_cancel_semigroup ℕ+ := { mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. (pnat.comm_monoid) } instance : right_cancel_semigroup ℕ+ := { mul_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_left_inj b.pos).mp h)}, .. (pnat.comm_monoid) } instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, .. (pnat.left_cancel_semigroup), .. (pnat.right_cancel_semigroup), .. (pnat.linear_order), .. (pnat.comm_monoid)} instance : distrib ℕ+ := { left_distrib := λ a b c, eq (mul_add a b c), right_distrib := λ a b c, eq (add_mul a b c), ..(pnat.add_comm_semigroup), ..(pnat.comm_monoid) } /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) = ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `pnat`. -/ lemma strong_induction_on {p : pnat → Prop} : ∀ (n : pnat) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `(n : pnat)` is different from `1`, then it is the successor of some `(k : pnat)`. -/ lemma exists_eq_succ_of_ne_one : ∀ {n : pnat} (h1 : n ≠ 1), ∃ (k : pnat), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ lemma case_strong_induction_on {p : pnat → Prop} (a : pnat) (hz : p 1) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a := begin apply strong_induction_on a, intros k hk, by_cases h1 : k = 1, { rwa h1 }, obtain ⟨b, rfl⟩ := exists_eq_succ_of_ne_one h1, simp only [lt_add_one_iff] at hk, exact hi b hk end /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : (m : ℕ) = (mod m k) + k * (div m k) := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀).symm, end theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), le_of_lt (nat.mod_lt (m : ℕ) k.pos)⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : ℕ) k.pos) h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [mod_add_div m k, dvd_iff'.mp h, nat.mul_succ, add_comm], end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a := begin apply zero_lt_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat
9a3499b0d34d20326d2ea8141b28a5b2ef5fdfa8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fin/vec_notation.lean
29033f48f7911b5e0a095e1a5d6f7e9ccd24d6c9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,355
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.fin.tuple.basic import data.list.range import group_theory.group_action.pi import meta.univs /-! # Matrix and vector notation > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives coefficients of a matrix, so `![![a, b], ![c, d]] : fin 2 → fin 2 → α`. In later files we introduce `!![a, b; c, d]` as notation for `matrix.of ![![a, b], ![c, d]]`. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin.elim0' /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ variables {m n : ℕ} /-- Use `![...]` notation for displaying a vector `fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance _root_.pi_fin.has_repr [has_repr α] : has_repr (fin n → α) := { repr := λ f, "![" ++ (string.intercalate ", " ((list.fin_range n).map (λ n, repr (f n)))) ++ "]" } end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} lemma empty_eq (v : fin 0 → α) : v = ![] := subsingleton.elim _ _ section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty _ @[simp] lemma range_cons_empty (x : α) (u : fin 0 → α) : set.range (matrix.vec_cons x u) = {x} := by rw [range_cons, range_empty, set.union_empty] @[simp] lemma range_cons_cons_empty (x y : α) (u : fin 0 → α) : set.range (vec_cons x $ vec_cons y u) = {x, y} := by rw [range_cons, range_cons_empty, set.singleton_union] @[simp] lemma vec_cons_const (a : α) : vec_cons a (λ k : fin n, a) = λ _, a := funext $ fin.forall_fin_succ.2 ⟨rfl, cons_val_succ _ _⟩ lemma vec_single_eq_const (a : α) : ![a] = λ _, a := funext $ unique.forall_iff.2 rfl /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl } @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { refine fin.forall_fin_one.2 _ i, refl } lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) := funext (cons_val_fin_one x u) meta instance _root_.pi_fin.reflect [reflected_univ.{u}] [reflected _ α] [has_reflect α] : Π {n}, has_reflect (fin n → α) | 0 v := (subsingleton.elim vec_empty v).rec ((by reflect_name : reflected _ (@vec_empty.{u})).subst `(α)) | (n + 1) v := (cons_head_tail v).rec $ (by reflect_name : reflected _ @vec_cons.{u}).subst₄ `(α) `(n) `(_) (_root_.pi_fin.reflect _) /-- Convert a vector of pexprs to the pexpr constructing that vector.-/ meta def _root_.pi_fin.to_pexpr : Π {n}, (fin n → pexpr) → pexpr | 0 v := ``(![]) | (n + 1) v := ``(vec_cons %%(v 0) %%(_root_.pi_fin.to_pexpr $ vec_tail v)) /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ /-- `vec_append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. This is a variant of `fin.append` with an additional `ho` argument, which provides control of definitional equality for the vector length. This turns out to be helpful when providing simp lemmas to reduce `![a, b, c] n`, and also means that `vec_append ho u v 0` is valid. `fin.append u v 0` is not valid in this case because there is no `has_zero (fin (m + n))` instance. -/ def vec_append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := fin.append u v ∘ fin.cast ho lemma vec_append_eq_ite {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : vec_append ho u v = λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (tsub_lt_iff_left (le_of_not_lt h)).2 (ho ▸ i.property)⟩ := begin ext i, rw [vec_append, fin.append, function.comp_apply, fin.add_cases], congr' with hi, simp only [eq_rec_constant], refl, end @[simp] lemma vec_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n) (u : fin (m + 1) → α) (v : fin n → α) : vec_append ho u v 0 = u 0 := rfl @[simp] lemma empty_vec_append (v : fin n → α) : vec_append (zero_add _).symm ![] v = v := by { ext, simp [vec_append_eq_ite] } @[simp] lemma cons_vec_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : vec_append ho (vec_cons x u) v = vec_cons x (vec_append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [vec_append_eq_ite], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_vec_append (v : fin n → α) : vec_alt0 rfl (vec_append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, vec_append_eq_ite], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw tsub_lt_iff_left h, exact add_lt_add i.property i.property } end lemma vec_alt1_vec_append (v : fin (n + 1) → α) : vec_alt1 rfl (vec_append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, vec_append_eq_ite], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw fin.coe_mk at h, rw fin.coe_one, rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), rw nat.mod_eq_of_lt h }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw tsub_lt_iff_left h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := by simp [vec_head, vec_alt1] @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (vec_append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_vec_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (vec_append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_vec_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section smul variables {M : Type*} [has_smul M α] @[simp] lemma smul_empty (x : M) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_cons (x : M) (y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x • y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma cons_add_cons (x : α) (v : fin n → α) (y : α) (w : fin n → α) : vec_cons x v + vec_cons y w = vec_cons (x + y) (v + w) := by simp @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma cons_sub_cons (x : α) (v : fin n → α) (y : α) (w : fin n → α) : vec_cons x v - vec_cons y w = vec_cons (x - y) (v - w) := by simp @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg end matrix
d6bac9da3cb4dc02ced21a833e0a2d86a6326fb8
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/omin/def_choice/choice3.lean
d362b24726a77811522c76e25d71a5616e0e924e
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
9,748
lean
import algebra.module.ordered import order.conditionally_complete_lattice import o_minimal.sheaf.pfun import o_minimal.sheaf.quantifiers import .order import ..oqm -- import ..tame -- Definable choice in 1 dimension. section -- TODO: for_mathlib order.bounds -- also add mem_lower_bounds/is_least_def/etc. lemma is_lub_def {α : Type*} [preorder α] (s : set α) (x : α) : is_lub s x ↔ (∀ a ∈ s, a ≤ x) ∧ (∀ y, (∀ a ∈ s, a ≤ y) → x ≤ y) := iff.rfl lemma is_glb_def {α : Type*} [preorder α] (s : set α) (x : α) : is_glb s x ↔ (∀ a ∈ s, x ≤ a) ∧ (∀ y, (∀ a ∈ s, y ≤ a) → y ≤ x) := iff.rfl end local infixr ` <|| `:2 := roption.orelse_pure local notation x ` >>* `:55 f:55 := f <$> x open o_minimal universe u instance {R : Type u} {S : struc R} : is_definable S punit := begin constructor, convert S.definable_univ 0, apply set.eq_univ_of_forall, intro x, use ⟨⟩, ext i, fin_cases i end variables {R : Type u} [OQM R] local notation `½` := (1/2 : ℚ) variables {S : struc R} [o_minimal_add S] variables {Y : Type u} [has_coordinates R Y] [definable_rep S Y] /- lemma def_fun.rat_smul (q : ℚ) : def_fun S (λ (r : R), q • r) := begin unfold def_fun, induction q using rat.num_denom_cases_on' with n d hd, -- need to clear denominators to get {p : R × R | n • p.fst = d • p.snd}, -- prove definability of nsmul by constant sorry end -/ lemma half_add_half {a : R} : ½ • a + ½ • a = a := by { rw ←add_smul, norm_num } lemma def_fun.half : def_fun S (λ (r : R), ½ • r) := begin unfold def_fun, have : def_set S {p : R × R | p.1 = p.2 + p.2} := def_set_eq def_fun.fst (definable.add def_fun.snd def_fun.snd), convert this, ext ⟨x, y⟩, dsimp, split; intro h, { subst y, rw half_add_half }, { subst x, rw [smul_add, half_add_half] } end noncomputable def one : has_one R := ⟨classical.some (no_top 0)⟩ local attribute [instance] one /- let's try to prove: axiom definable_choice_1 {s : set (Y × R)} (hs : def_set S s) (h : prod.fst '' s = set.univ) : ∃ g : Y → R, def_fun S g ∧ ∀ y, (y, g y) ∈ s -/ variables (S) -- Goal: Prove the following type is inhabited. def definable_choice_function : Type u := {choice : set R →. R // definable S choice ∧ choice.dom = set.nonempty ∧ ∀ X H, tame X → (choice X).get H ∈ X} variables {S} /-- Construct a definable partial function on sets from a definable relation. This is sensible when the relation is single-valued: `r` s.t. `rel X r` is unique if it exists. We ask for the proof of uniqueness now to avoid having to write it later. -/ noncomputable def pfun_of_rel (rel : set R → R → Prop) (uni : ∀ X r r', rel X r → rel X r' → r = r') : set R →. R := λ X, { dom := ∃ r, rel X r, get := λ h, classical.some h } lemma mem_pfun_of_rel_iff {rel : set R → R → Prop} (uni : ∀ X r r', rel X r → rel X r' → r = r') (X : set R) (r : R) : r ∈ pfun_of_rel rel uni X ↔ rel X r := begin split; intro H, { rcases H with ⟨H, rfl⟩, apply classical.some_spec }, { exact ⟨⟨r, H⟩, uni _ _ _ (classical.some_spec _) H⟩ } end lemma get_pfun_of_rel_eq_of_rel {rel : set R → R → Prop} {uni} {X : set R} {r : R} (h : rel X r) {H} : (pfun_of_rel rel uni X).get H = r := uni X _ _ (classical.some_spec _) h lemma def_pfun_of_rel {rel : set R → R → Prop} {uni} (drel : definable S rel) : definable S (pfun_of_rel rel uni) := begin apply definable_pfun_of_graph, rw definable_iff_uncurry at drel, convert drel, ext ⟨x, y⟩, apply mem_pfun_of_rel_iff uni end noncomputable def the_least : set R →. R := pfun_of_rel is_least (λ _ _ _, is_least.unique) @[simp] lemma the_least_dom {X : set R} : (the_least X).dom = ∃ e, is_least X e := rfl lemma def_is_least : definable S (is_least : set R → R → Prop) := show definable S (λ X (r : R), r ∈ X ∧ ∀ x ∈ X, r ≤ x), begin [defin] intro X, intro r, app, app, exact definable.and.definable _, app, app, exact definable.mem.definable _, var, var, all x, imp, app, app, exact definable.mem.definable _, var, var, app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var end lemma def_the_least : definable S (the_least : set R →. R) := def_pfun_of_rel def_is_least -- Now repeat for inf, sup. noncomputable def the_inf : set R →. R := pfun_of_rel is_glb (λ _ _ _, is_glb.unique) noncomputable def the_sup : set R →. R := pfun_of_rel is_lub (λ _ _ _, is_lub.unique) @[simp] lemma the_inf_dom {X : set R} : (the_inf X).dom = ∃ a, is_glb X a := rfl @[simp] lemma the_sup_dom {X : set R} : (the_sup X).dom = ∃ b, is_lub X b := rfl lemma def_the_inf : definable S (the_inf : set R →. R) := begin refine def_pfun_of_rel _, begin [defin] intro X, intro r, app, app, exact definable.and.definable _, { all x, imp, app, app, exact definable.mem.definable _, var, var, app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var }, { all y, imp, { all x, imp, app, app, exact definable.mem.definable _, var, var, app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var }, { app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var } } end end lemma def_the_sup : definable S (the_sup : set R →. R) := begin refine def_pfun_of_rel _, begin [defin] intro X, intro r, app, app, exact definable.and.definable _, { all x, imp, app, app, exact definable.mem.definable _, var, var, app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var }, { all y, imp, { all x, imp, app, app, exact definable.mem.definable _, var, var, app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var }, { app, app, exact (definable_iff_def_rel₂.mpr definable_le').definable _, var, var } } end end -- TODO: "generalize" core library's `guard` to return `punit`? -- TODO: super hack: we return 0 (ignored) instead of `punit` -- just to be able to use `def_pfun_set.bind` in its current form; -- but we could generalize the types involved in `def_pfun_set` to -- arbitrary definable types to avoid this -- TODO: We might have already generalized it enough. def zero_when_nonempty : set R →. R := λ X, { dom := X.nonempty, get := λ _, (0 : R) } noncomputable def chosen_one : set R → R := λ X, the_least X <|| (the_inf X >>* λ a, (the_sup {b | a < b ∧ set.Ioo a b ⊆ X} >>* λ b, ½ • (a + b)) <|| a + 1) <|| (the_sup {b | set.Iio b ⊆ X} >>* λ b, b - 1) <|| 0 open_locale classical lemma nonempty_of_not_tame {s : set R} (h : ¬ tame s) : s.nonempty := begin rw ← set.ne_empty_iff_nonempty, contrapose! h, subst s, exact tame_empty end noncomputable def chosen_one' : set R → R := λ X, if h : tame X then chosen_one X else classical.some (nonempty_of_not_tame h) lemma def_zero_when_nonempty : definable S (zero_when_nonempty : set R →. R) := begin apply definable_pfun_of_graph, change definable S {p : set R × R | ∃ (H : p.1.nonempty), 0 = p.2}, simp_rw exists_prop, begin [defin] intro p, app, app, exact definable.and.definable _, { app, exact definable_nonempty.definable _, app, exact definable.fst.definable _, var }, { app, app, swap, exact def_fun_const, exact definable_sheaf.eq, app, exact definable.snd.definable _, var } end end lemma definable_chosen_one : definable S (chosen_one : set R → R) := begin unfold chosen_one, simp only [sub_eq_add_neg], begin [defin] intro X, app, app, exact definable_orelse_pure.definable _, { app, exact def_the_least.definable _, var }, app, app, exact definable_orelse_pure.definable _, { app, app, exact definable_roption_map.definable _, swap, { app, exact def_the_inf.definable _, var }, intro a, app, app, exact definable_orelse_pure.definable _, { app, app, exact definable_roption_map.definable _, swap, app, exact def_the_sup.definable _, { intro b, app, app, exact definable.and.definable _, -- TODO: sheafy order classes app, app, exact (definable_iff_def_rel₂.mpr definable_lt').definable _, var, var, app, app, exact definable_subset.definable _, app, app, exact definable_Ioo.definable _, var, var, var }, { intro b, app, exact (definable_iff_def_fun.mpr def_fun.half).definable _, -- TODO: sheafy algebra classes app, app, exact (definable_iff_def_fun₂.mpr definable_add).definable _, var, var } }, { app, app, exact (definable_iff_def_fun₂.mpr definable_add).definable _, var, -- TODO: this is abstraction-breaking exact def_fun_const } }, app, app, exact definable_orelse_pure.definable _, { app, app, exact definable_roption_map.definable _, swap, app, exact def_the_sup.definable _, { intro b, app, app, exact definable_subset.definable _, app, exact definable_Iio.definable _, var, var }, { intro b, app, app, exact (definable_iff_def_fun₂.mpr definable_add).definable _, var, exact def_fun_const } }, exact def_fun_const end end -- STILL TO DO (done in other files): -- * Prove that, when `X` is tame and nonempty, `chosen_one X` is an element of `X`. -- Hopefully it's not too hard to reason about what `chosen_one` will produce; -- but it still requires understanding the local behavior of tame sets.
b69272c9169588aa7aaddc3400fd8625bdfbce37
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/martingale/upcrossing.lean
2bc98deb4de6a3d79054b73ba9296514a1e6129a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
41,393
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import data.set.intervals.monotone import probability.process.hitting_time import probability.martingale.basic /-! # Doob's upcrossing estimate Given a discrete real-valued submartingale $(f_n)_{n \in \mathbb{N}}$, denoting $U_N(a, b)$ the number of times $f_n$ crossed from below $a$ to above $b$ before time $N$, Doob's upcrossing estimate (also known as Doob's inequality) states that $$(b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(f_N - a)^+].$$ Doob's upcrossing estimate is an important inequality and is central in proving the martingale convergence theorems. ## Main definitions * `measure_theory.upper_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing above `b` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.lower_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing below `a` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.upcrossing_strat a b f N`: is the predictable process which is 1 if `n` is between a consecutive pair of lower and upper crossing and is 0 otherwise. Intuitively one might think of the `upcrossing_strat` as the strategy of buying 1 share whenever the process crosses below `a` for the first time after selling and selling 1 share whenever the process crosses above `b` for the first time after buying. * `measure_theory.upcrossings_before a b f N`: is the number of times `f` crosses from below `a` to above `b` before time `N`. * `measure_theory.upcrossings a b f`: is the number of times `f` crosses from below `a` to above `b`. This takes value in `ℝ≥0∞` and so is allowed to be `∞`. ## Main results * `measure_theory.adapted.is_stopping_time_upper_crossing_time`: `upper_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.adapted.is_stopping_time_lower_crossing_time`: `lower_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.submartingale.mul_integral_upcrossings_before_le_integral_pos_part`: Doob's upcrossing estimate. * `measure_theory.submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part`: the inequality obtained by taking the supremum on both sides of Doob's upcrossing estimate. ### References We mostly follow the proof from [Kallenberg, *Foundations of modern probability*][kallenberg2021] -/ open topological_space filter open_locale nnreal ennreal measure_theory probability_theory big_operators topology namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} /-! ## Proof outline In this section, we will denote $U_N(a, b)$ the number of upcrossings of $(f_n)$ from below $a$ to above $b$ before time $N$. To define $U_N(a, b)$, we will construct two stopping times corresponding to when $(f_n)$ crosses below $a$ and above $b$. Namely, we define $$ \sigma_n := \inf \{n \ge \tau_n \mid f_n \le a\} \wedge N; $$ $$ \tau_{n + 1} := \inf \{n \ge \sigma_n \mid f_n \ge b\} \wedge N. $$ These are `lower_crossing_time` and `upper_crossing_time` in our formalization which are defined using `measure_theory.hitting` allowing us to specify a starting and ending time. Then, we may simply define $U_N(a, b) := \sup \{n \mid \tau_n < N\}$. Fixing $a < b \in \mathbb{R}$, we will first prove the theorem in the special case that $0 \le f_0$ and $a \le f_N$. In particular, we will show $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[f_N]. $$ This is `measure_theory.integral_mul_upcrossings_before_le_integral` in our formalization. To prove this, we use the fact that given a non-negative, bounded, predictable process $(C_n)$ (i.e. $(C_{n + 1})$ is adapted), $(C \bullet f)_n := \sum_{k \le n} C_{k + 1}(f_{k + 1} - f_k)$ is a submartingale if $(f_n)$ is. Define $C_n := \sum_{k \le n} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)$. It is easy to see that $(1 - C_n)$ is non-negative, bounded and predictable, and hence, given a submartingale $(f_n)$, $(1 - C) \bullet f$ is also a submartingale. Thus, by the submartingale property, $0 \le \mathbb{E}[((1 - C) \bullet f)_0] \le \mathbb{E}[((1 - C) \bullet f)_N]$ implying $$ \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[(1 \bullet f)_N] = \mathbb{E}[f_N] - \mathbb{E}[f_0]. $$ Furthermore, \begin{align} (C \bullet f)_N & = \sum_{n \le N} \sum_{k \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} \sum_{n \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} (f_{\sigma_k + 1} - f_{\sigma_k} + f_{\sigma_k + 2} - f_{\sigma_k + 1} + \cdots + f_{\tau_{k + 1}} - f_{\tau_{k + 1} - 1})\\ & = \sum_{k \le N} (f_{\tau_{k + 1}} - f_{\sigma_k}) \ge \sum_{k < U_N(a, b)} (b - a) = (b - a) U_N(a, b) \end{align} where the inequality follows since for all $k < U_N(a, b)$, $f_{\tau_{k + 1}} - f_{\sigma_k} \ge b - a$ while for all $k > U_N(a, b)$, $f_{\tau_{k + 1}} = f_{\sigma_k} = f_N$ and $f_{\tau_{U_N(a, b) + 1}} - f_{\sigma_{U_N(a, b)}} = f_N - a \ge 0$. Hence, we have $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[f_N] - \mathbb{E}[f_0] \le \mathbb{E}[f_N], $$ as required. To obtain the general case, we simply apply the above to $((f_n - a)^+)_n$. -/ /-- `lower_crossing_time_aux a f c N` is the first time `f` reached below `a` after time `c` before time `N`. -/ noncomputable def lower_crossing_time_aux [preorder ι] [has_Inf ι] (a : ℝ) (f : ι → Ω → ℝ) (c N : ι) : Ω → ι := hitting f (set.Iic a) c N /-- `upper_crossing_time a b f N n` is the first time before time `N`, `f` reaches above `b` after `f` reached below `a` for the `n - 1`-th time. -/ noncomputable def upper_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) : ℕ → Ω → ι | 0 := ⊥ | (n + 1) := λ ω, hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time n ω) N ω) N ω /-- `lower_crossing_time a b f N n` is the first time before time `N`, `f` reaches below `a` after `f` reached above `b` for the `n`-th time. -/ noncomputable def lower_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (n : ℕ) : Ω → ι := λ ω, hitting f (set.Iic a) (upper_crossing_time a b f N n ω) N ω section variables [preorder ι] [order_bot ι] [has_Inf ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} @[simp] lemma upper_crossing_time_zero : upper_crossing_time a b f N 0 = ⊥ := rfl @[simp] lemma lower_crossing_time_zero : lower_crossing_time a b f N 0 = hitting f (set.Iic a) ⊥ N := rfl lemma upper_crossing_time_succ : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time a b f N n ω) N ω) N ω := by rw upper_crossing_time lemma upper_crossing_time_succ_eq (ω : Ω) : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time a b f N n ω) N ω := begin simp only [upper_crossing_time_succ], refl, end end section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} lemma upper_crossing_time_le : upper_crossing_time a b f N n ω ≤ N := begin cases n, { simp only [upper_crossing_time_zero, pi.bot_apply, bot_le] }, { simp only [upper_crossing_time_succ, hitting_le] }, end @[simp] lemma upper_crossing_time_zero' : upper_crossing_time a b f ⊥ n ω = ⊥ := eq_bot_iff.2 upper_crossing_time_le lemma lower_crossing_time_le : lower_crossing_time a b f N n ω ≤ N := by simp only [lower_crossing_time, hitting_le ω] lemma upper_crossing_time_le_lower_crossing_time : upper_crossing_time a b f N n ω ≤ lower_crossing_time a b f N n ω := by simp only [lower_crossing_time, le_hitting upper_crossing_time_le ω] lemma lower_crossing_time_le_upper_crossing_time_succ : lower_crossing_time a b f N n ω ≤ upper_crossing_time a b f N (n + 1) ω := begin rw upper_crossing_time_succ, exact le_hitting lower_crossing_time_le ω, end lemma lower_crossing_time_mono (hnm : n ≤ m) : lower_crossing_time a b f N n ω ≤ lower_crossing_time a b f N m ω := begin suffices : monotone (λ n, lower_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans lower_crossing_time_le_upper_crossing_time_succ upper_crossing_time_le_lower_crossing_time) end lemma upper_crossing_time_mono (hnm : n ≤ m) : upper_crossing_time a b f N n ω ≤ upper_crossing_time a b f N m ω := begin suffices : monotone (λ n, upper_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans upper_crossing_time_le_lower_crossing_time lower_crossing_time_le_upper_crossing_time_succ), end end conditionally_complete_linear_order_bot variables {a b : ℝ} {f : ℕ → Ω → ℝ} {N : ℕ} {n m : ℕ} {ω : Ω} lemma stopped_value_lower_crossing_time (h : lower_crossing_time a b f N n ω ≠ N) : stopped_value f (lower_crossing_time a b f N n) ω ≤ a := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne lower_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 lower_crossing_time_le⟩, hj₂⟩, end lemma stopped_value_upper_crossing_time (h : upper_crossing_time a b f N (n + 1) ω ≠ N) : b ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne upper_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 (hitting_le _)⟩, hj₂⟩, end lemma upper_crossing_time_lt_lower_crossing_time (hab : a < b) (hn : lower_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N (n + 1) ω < lower_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne upper_crossing_time_le_lower_crossing_time (λ h, not_le.2 hab $ le_trans _ (stopped_value_lower_crossing_time hn)), simp only [stopped_value], rw ← h, exact stopped_value_upper_crossing_time (h.symm ▸ hn), end lemma lower_crossing_time_lt_upper_crossing_time (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : lower_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne lower_crossing_time_le_upper_crossing_time_succ (λ h, not_le.2 hab $ le_trans (stopped_value_upper_crossing_time hn) _), simp only [stopped_value], rw ← h, exact stopped_value_lower_crossing_time (h.symm ▸ hn), end lemma upper_crossing_time_lt_succ (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time (lower_crossing_time_lt_upper_crossing_time hab hn) lemma lower_crossing_time_stabilize (hnm : n ≤ m) (hn : lower_crossing_time a b f N n ω = N) : lower_crossing_time a b f N m ω = N := le_antisymm lower_crossing_time_le (le_trans (le_of_eq hn.symm) (lower_crossing_time_mono hnm)) lemma upper_crossing_time_stabilize (hnm : n ≤ m) (hn : upper_crossing_time a b f N n ω = N) : upper_crossing_time a b f N m ω = N := le_antisymm upper_crossing_time_le (le_trans (le_of_eq hn.symm) (upper_crossing_time_mono hnm)) lemma lower_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ lower_crossing_time a b f N n ω) : lower_crossing_time a b f N m ω = N := lower_crossing_time_stabilize hnm (le_antisymm lower_crossing_time_le hn) lemma upper_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ upper_crossing_time a b f N n ω) : upper_crossing_time a b f N m ω = N := upper_crossing_time_stabilize hnm (le_antisymm upper_crossing_time_le hn) -- `upper_crossing_time_bound_eq` provides an explicit bound lemma exists_upper_crossing_time_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : ∃ n, upper_crossing_time a b f N n ω = N := begin by_contra h, push_neg at h, have : strict_mono (λ n, upper_crossing_time a b f N n ω) := strict_mono_nat_of_lt_succ (λ n, upper_crossing_time_lt_succ hab (h _)), obtain ⟨_, ⟨k, rfl⟩, hk⟩ : ∃ m (hm : m ∈ set.range (λ n, upper_crossing_time a b f N n ω)), N < m := ⟨upper_crossing_time a b f N (N + 1) ω, ⟨N + 1, rfl⟩, lt_of_lt_of_le (N.lt_succ_self) (strict_mono.id_le this (N + 1))⟩, exact not_le.2 hk upper_crossing_time_le end lemma upper_crossing_time_lt_bdd_above (hab : a < b) : bdd_above {n | upper_crossing_time a b f N n ω < N} := begin obtain ⟨k, hk⟩ := exists_upper_crossing_time_eq f N ω hab, refine ⟨k, λ n (hn : upper_crossing_time a b f N n ω < N), _⟩, by_contra hn', exact hn.ne (upper_crossing_time_stabilize (not_le.1 hn').le hk) end lemma upper_crossing_time_lt_nonempty (hN : 0 < N) : {n | upper_crossing_time a b f N n ω < N}.nonempty := ⟨0, hN⟩ lemma upper_crossing_time_bound_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : upper_crossing_time a b f N N ω = N := begin by_cases hN' : N < nat.find (exists_upper_crossing_time_eq f N ω hab), { refine le_antisymm upper_crossing_time_le _, have hmono : strict_mono_on (λ n, upper_crossing_time a b f N n ω) (set.Iic (nat.find (exists_upper_crossing_time_eq f N ω hab)).pred), { refine strict_mono_on_Iic_of_lt_succ (λ m hm, upper_crossing_time_lt_succ hab _), rw nat.lt_pred_iff at hm, convert nat.find_min _ hm }, convert strict_mono_on.Iic_id_le hmono N (nat.le_pred_of_lt hN') }, { rw not_lt at hN', exact upper_crossing_time_stabilize hN' (nat.find_spec (exists_upper_crossing_time_eq f N ω hab)) } end lemma upper_crossing_time_eq_of_bound_le (hab : a < b) (hn : N ≤ n) : upper_crossing_time a b f N n ω = N := le_antisymm upper_crossing_time_le ((le_trans (upper_crossing_time_bound_eq f N ω hab).symm.le (upper_crossing_time_mono hn))) variables {ℱ : filtration ℕ m0} lemma adapted.is_stopping_time_crossing (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) ∧ is_stopping_time ℱ (lower_crossing_time a b f N n) := begin induction n with k ih, { refine ⟨is_stopping_time_const _ 0, _⟩, simp [hitting_is_stopping_time hf measurable_set_Iic] }, { obtain ⟨ih₁, ih₂⟩ := ih, have : is_stopping_time ℱ (upper_crossing_time a b f N (k + 1)), { intro n, simp_rw upper_crossing_time_succ_eq, exact is_stopping_time_hitting_is_stopping_time ih₂ (λ _, lower_crossing_time_le) measurable_set_Ici hf _ }, refine ⟨this, _⟩, { intro n, exact is_stopping_time_hitting_is_stopping_time this (λ _, upper_crossing_time_le) measurable_set_Iic hf _ } } end lemma adapted.is_stopping_time_upper_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) := hf.is_stopping_time_crossing.1 lemma adapted.is_stopping_time_lower_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (lower_crossing_time a b f N n) := hf.is_stopping_time_crossing.2 /-- `upcrossing_strat a b f N n` is 1 if `n` is between a consecutive pair of lower and upper crossings and is 0 otherwise. `upcrossing_strat` is shifted by one index so that it is adapted rather than predictable. -/ noncomputable def upcrossing_strat (a b : ℝ) (f : ℕ → Ω → ℝ) (N n : ℕ) (ω : Ω) : ℝ := ∑ k in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator 1 n lemma upcrossing_strat_nonneg : 0 ≤ upcrossing_strat a b f N n ω := finset.sum_nonneg (λ i hi, set.indicator_nonneg (λ ω hω, zero_le_one) _) lemma upcrossing_strat_le_one : upcrossing_strat a b f N n ω ≤ 1 := begin rw [upcrossing_strat, ← set.indicator_finset_bUnion_apply], { exact set.indicator_le_self' (λ _ _, zero_le_one) _ }, { intros i hi j hj hij, rw set.Ico_disjoint_Ico, obtain (hij' | hij') := lt_or_gt_of_ne hij, { rw [min_eq_left ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_right (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) }, { rw gt_iff_lt at hij', rw [min_eq_right ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_left (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) } } end lemma adapted.upcrossing_strat_adapted (hf : adapted ℱ f) : adapted ℱ (upcrossing_strat a b f N) := begin intro n, change strongly_measurable[ℱ n] (λ ω, ∑ k in finset.range N, ({n | lower_crossing_time a b f N k ω ≤ n} ∩ {n | n < upper_crossing_time a b f N (k + 1) ω}).indicator 1 n), refine finset.strongly_measurable_sum _ (λ i hi, strongly_measurable_const.indicator ((hf.is_stopping_time_lower_crossing_time n).inter _)), simp_rw ← not_le, exact (hf.is_stopping_time_upper_crossing_time n).compl, end lemma submartingale.sum_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)) ℱ μ := hf.sum_mul_sub hf.adapted.upcrossing_strat_adapted (λ _ _, upcrossing_strat_le_one) (λ _ _, upcrossing_strat_nonneg) lemma submartingale.sum_sub_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)) ℱ μ := begin refine hf.sum_mul_sub (λ n, (adapted_const ℱ 1 n).sub (hf.adapted.upcrossing_strat_adapted n)) (_ : ∀ n ω, (1 - upcrossing_strat a b f N n) ω ≤ 1) _, { exact λ n ω, sub_le_self _ upcrossing_strat_nonneg }, { intros n ω, simp [upcrossing_strat_le_one] } end lemma submartingale.sum_mul_upcrossing_strat_le [is_finite_measure μ] (hf : submartingale f ℱ μ) : μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)] ≤ μ[f n] - μ[f 0] := begin have h₁ : (0 : ℝ) ≤ μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)], { have := (hf.sum_sub_upcrossing_strat_mul a b N).set_integral_le (zero_le n) measurable_set.univ, rw [integral_univ, integral_univ] at this, refine le_trans _ this, simp only [finset.range_zero, finset.sum_empty, integral_zero'] }, have h₂ : μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)] = μ[∑ k in finset.range n, (f (k + 1) - f k)] - μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)], { simp only [sub_mul, one_mul, finset.sum_sub_distrib, pi.sub_apply, finset.sum_apply, pi.mul_apply], refine integral_sub (integrable.sub (integrable_finset_sum _ (λ i hi, hf.integrable _)) (integrable_finset_sum _ (λ i hi, hf.integrable _))) _, convert (hf.sum_upcrossing_strat_mul a b N).integrable n, ext, simp }, rw [h₂, sub_nonneg] at h₁, refine le_trans h₁ _, simp_rw [finset.sum_range_sub, integral_sub' (hf.integrable _) (hf.integrable _)], end /-- The number of upcrossings (strictly) before time `N`. -/ noncomputable def upcrossings_before [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (ω : Ω) : ℕ := Sup {n | upper_crossing_time a b f N n ω < N} @[simp] lemma upcrossings_before_bot [preorder ι] [order_bot ι] [has_Inf ι] {a b : ℝ} {f : ι → Ω → ℝ} {ω : Ω} : upcrossings_before a b f ⊥ ω = ⊥ := by simp [upcrossings_before] lemma upcrossings_before_zero : upcrossings_before a b f 0 ω = 0 := by simp [upcrossings_before] @[simp] lemma upcrossings_before_zero' : upcrossings_before a b f 0 = 0 := by { ext ω, exact upcrossings_before_zero } lemma upper_crossing_time_lt_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n ≤ upcrossings_before a b f N ω) : upper_crossing_time a b f N n ω < N := begin have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := (upper_crossing_time_lt_nonempty hN).cSup_mem ((order_bot.bdd_below _).finite_of_bdd_above (upper_crossing_time_lt_bdd_above hab)), exact lt_of_le_of_lt (upper_crossing_time_mono hn) this, end lemma upper_crossing_time_eq_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : upper_crossing_time a b f N n ω = N := begin refine le_antisymm upper_crossing_time_le (not_lt.1 _), convert not_mem_of_cSup_lt hn (upper_crossing_time_lt_bdd_above hab), end lemma upcrossings_before_le (f : ℕ → Ω → ℝ) (ω : Ω) (hab : a < b) : upcrossings_before a b f N ω ≤ N := begin by_cases hN : N = 0, { subst hN, rw upcrossings_before_zero }, { refine cSup_le ⟨0, zero_lt_iff.2 hN⟩ (λ n (hn : _ < _), _), by_contra hnN, exact hn.ne (upper_crossing_time_eq_of_bound_le hab (not_le.1 hnN).le) }, end lemma crossing_eq_crossing_of_lower_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : lower_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have h' : upper_crossing_time a b f N n ω < N := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time h, induction n with k ih, { simp only [nat.nat_zero_eq_zero, upper_crossing_time_zero, bot_eq_zero', eq_self_iff_true, lower_crossing_time_zero, true_and, eq_comm], refine hitting_eq_hitting_of_exists hNM _, simp only [lower_crossing_time, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, { specialize ih (lt_of_le_of_lt (lower_crossing_time_mono (nat.le_succ _)) h) (lt_of_le_of_lt (upper_crossing_time_mono (nat.le_succ _)) h'), have : upper_crossing_time a b f M k.succ ω = upper_crossing_time a b f N k.succ ω, { simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h' ⊢, obtain ⟨j, hj₁, hj₂⟩ := h', rw [eq_comm, ih.2], exact hitting_eq_hitting_of_exists hNM ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, refine ⟨this, _⟩, simp only [lower_crossing_time, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, rw [lower_crossing_time, hitting_lt_iff _ le_rfl] at h, swap, { apply_instance }, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ } end lemma crossing_eq_crossing_of_upper_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N (n + 1) ω < N) : upper_crossing_time a b f M (n + 1) ω = upper_crossing_time a b f N (n + 1) ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have := (crossing_eq_crossing_of_lower_crossing_time_lt hNM (lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ h)).2, refine ⟨_, this⟩, rw [upper_crossing_time_succ_eq, upper_crossing_time_succ_eq, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ end lemma upper_crossing_time_eq_upper_crossing_time_of_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω := begin cases n, { simp }, { exact (crossing_eq_crossing_of_upper_crossing_time_lt hNM h).1 } end lemma upcrossings_before_mono (hab : a < b) : monotone (λ N ω, upcrossings_before a b f N ω) := begin intros N M hNM ω, simp only [upcrossings_before], by_cases hemp : {n : ℕ | upper_crossing_time a b f N n ω < N}.nonempty, { refine cSup_le_cSup (upper_crossing_time_lt_bdd_above hab) hemp (λ n hn, _), rw [set.mem_set_of_eq, upper_crossing_time_eq_upper_crossing_time_of_lt hNM hn], exact lt_of_lt_of_le hn hNM }, { rw set.not_nonempty_iff_eq_empty at hemp, simp [hemp, cSup_empty, bot_eq_zero', zero_le'] } end lemma upcrossings_before_lt_of_exists_upcrossing (hab : a < b) {N₁ N₂ : ℕ} (hN₁: N ≤ N₁) (hN₁': f N₁ ω < a) (hN₂: N₁ ≤ N₂) (hN₂': b < f N₂ ω) : upcrossings_before a b f N ω < upcrossings_before a b f (N₂ + 1) ω := begin refine lt_of_lt_of_le (nat.lt_succ_self _) (le_cSup (upper_crossing_time_lt_bdd_above hab) _), rw [set.mem_set_of_eq, upper_crossing_time_succ_eq, hitting_lt_iff _ le_rfl], swap, { apply_instance }, { refine ⟨N₂, ⟨_, nat.lt_succ_self _⟩, hN₂'.le⟩, rw [lower_crossing_time, hitting_le_iff_of_lt _ (nat.lt_succ_self _)], refine ⟨N₁, ⟨le_trans _ hN₁, hN₂⟩, hN₁'.le⟩, by_cases hN : 0 < N, { have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := nat.Sup_mem (upper_crossing_time_lt_nonempty hN) (upper_crossing_time_lt_bdd_above hab), rw upper_crossing_time_eq_upper_crossing_time_of_lt (hN₁.trans (hN₂.trans $ nat.le_succ _)) this, exact this.le }, { rw [not_lt, le_zero_iff] at hN, rw [hN, upcrossings_before_zero, upper_crossing_time_zero], refl } }, end lemma lower_crossing_time_lt_of_lt_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : lower_crossing_time a b f N n ω < N := lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn) lemma le_sub_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : b - a ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω := sub_le_sub (stopped_value_upper_crossing_time (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn).ne) (stopped_value_lower_crossing_time (lower_crossing_time_lt_of_lt_upcrossings_before hN hab hn).ne) lemma sub_eq_zero_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω = 0 := begin have : N ≤ upper_crossing_time a b f N n ω, { rw upcrossings_before at hn, rw ← not_lt, exact λ h, not_le.2 hn (le_cSup (upper_crossing_time_lt_bdd_above hab) h) }, simp [stopped_value, upper_crossing_time_stabilize' (nat.le_succ n) this, lower_crossing_time_stabilize' le_rfl (le_trans this upper_crossing_time_le_lower_crossing_time)] end lemma mul_upcrossings_before_le (hf : a ≤ f N ω) (hab : a < b) : (b - a) * upcrossings_before a b f N ω ≤ ∑ k in finset.range N, upcrossing_strat a b f N k ω * (f (k + 1) - f k) ω := begin classical, by_cases hN : N = 0, { simp [hN] }, simp_rw [upcrossing_strat, finset.sum_mul, ← set.indicator_mul_left, pi.one_apply, pi.sub_apply, one_mul], rw finset.sum_comm, have h₁ : ∀ k, ∑ n in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator (λ m, f (m + 1) ω - f m ω) n = stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω, { intro k, rw [finset.sum_indicator_eq_sum_filter, (_ : (finset.filter (λ i, i ∈ set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)) (finset.range N)) = finset.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)), finset.sum_Ico_eq_add_neg _ lower_crossing_time_le_upper_crossing_time_succ, finset.sum_range_sub (λ n, f n ω), finset.sum_range_sub (λ n, f n ω), neg_sub, sub_add_sub_cancel], { refl }, { ext i, simp only [set.mem_Ico, finset.mem_filter, finset.mem_range, finset.mem_Ico, and_iff_right_iff_imp, and_imp], exact λ _ h, lt_of_lt_of_le h upper_crossing_time_le } }, simp_rw [h₁], have h₂ : ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω), { calc ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range (upcrossings_before a b f N ω), (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum (λ i hi, le_sub_of_le_upcrossings_before (zero_lt_iff.2 hN) hab _), rwa finset.mem_range at hi, end ...≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum_of_subset_of_nonneg (finset.range_subset.2 (upcrossings_before_le f ω hab)) (λ i _ hi, _), by_cases hi' : i = upcrossings_before a b f N ω, { subst hi', simp only [stopped_value], rw upper_crossing_time_eq_of_upcrossings_before_lt hab (nat.lt_succ_self _), by_cases heq : lower_crossing_time a b f N (upcrossings_before a b f N ω) ω = N, { rw [heq, sub_self] }, { rw sub_nonneg, exact le_trans (stopped_value_lower_crossing_time heq) hf } }, { rw sub_eq_zero_of_upcrossings_before_lt hab, rw [finset.mem_range, not_lt] at hi, exact lt_of_le_of_ne hi (ne.symm hi') }, end }, refine le_trans _ h₂, rw [finset.sum_const, finset.card_range, nsmul_eq_mul, mul_comm], end lemma integral_mul_upcrossings_before_le_integral [is_finite_measure μ] (hf : submartingale f ℱ μ) (hfN : ∀ ω, a ≤ f N ω) (hfzero : 0 ≤ f 0) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[f N] := calc (b - a) * μ[upcrossings_before a b f N] ≤ μ[∑ k in finset.range N, upcrossing_strat a b f N k * (f (k + 1) - f k)] : begin rw ← integral_mul_left, refine integral_mono_of_nonneg _ ((hf.sum_upcrossing_strat_mul a b N).integrable N) _, { exact eventually_of_forall (λ ω, mul_nonneg (sub_nonneg.2 hab.le) (nat.cast_nonneg _)) }, { refine eventually_of_forall (λ ω, _), simpa using mul_upcrossings_before_le (hfN ω) hab }, end ...≤ μ[f N] - μ[f 0] : hf.sum_mul_upcrossing_strat_le ...≤ μ[f N] : (sub_le_self_iff _).2 (integral_nonneg hfzero) lemma crossing_pos_eq (hab : a < b) : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = upper_crossing_time a b f N n ∧ lower_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = lower_crossing_time a b f N n := begin have hab' : 0 < b - a := sub_pos.2 hab, have hf : ∀ ω i, b - a ≤ (f i ω - a)⁺ ↔ b ≤ f i ω, { intros i ω, refine ⟨λ h, _, λ h, _⟩, { rwa [← sub_le_sub_iff_right a, ← lattice_ordered_comm_group.pos_eq_self_of_pos_pos (lt_of_lt_of_le hab' h)] }, { rw ← sub_le_sub_iff_right a at h, rwa lattice_ordered_comm_group.pos_of_nonneg _ (le_trans hab'.le h) } }, have hf' : ∀ ω i, (f i ω - a)⁺ ≤ 0 ↔ f i ω ≤ a, { intros ω i, rw [lattice_ordered_comm_group.pos_nonpos_iff, sub_nonpos] }, induction n with k ih, { refine ⟨rfl, _⟩, simp only [lower_crossing_time_zero, hitting, set.mem_Icc, set.mem_Iic], ext ω, split_ifs with h₁ h₂ h₂, { simp_rw [hf'] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, { have : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N (k + 1) = upper_crossing_time a b f N (k + 1), { ext ω, simp only [upper_crossing_time_succ_eq, ← ih.2, hitting, set.mem_Ici, tsub_le_iff_right], split_ifs with h₁ h₂ h₂, { simp_rw [← sub_le_iff_le_add, hf ω] }, { simp_rw [set.mem_Ici, ← hf _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Ici, hf _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, refine ⟨this, _⟩, ext ω, simp only [lower_crossing_time, this, hitting, set.mem_Iic], split_ifs with h₁ h₂ h₂, { simp_rw [hf' ω] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } } end lemma upcrossings_before_pos_eq (hab : a < b) : upcrossings_before 0 (b - a) (λ n ω, (f n ω - a)⁺) N ω = upcrossings_before a b f N ω := by simp_rw [upcrossings_before, (crossing_pos_eq hab).1] lemma mul_integral_upcrossings_before_le_integral_pos_part_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin refine le_trans (le_of_eq _) (integral_mul_upcrossings_before_le_integral (hf.sub_martingale (martingale_const _ _ _)).pos (λ ω, lattice_ordered_comm_group.pos_nonneg _) (λ ω, lattice_ordered_comm_group.pos_nonneg _) (sub_pos.2 hab)), simp_rw [sub_zero, ← upcrossings_before_pos_eq hab], refl, end /-- **Doob's upcrossing estimate**: given a real valued discrete submartingale `f` and real values `a` and `b`, we have `(b - a) * 𝔼[upcrossings_before a b f N] ≤ 𝔼[(f N - a)⁺]` where `upcrossings_before a b f N` is the number of times the process `f` crossed from below `a` to above `b` before the time `N`. -/ theorem submartingale.mul_integral_upcrossings_before_le_integral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) (N : ℕ) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin by_cases hab : a < b, { exact mul_integral_upcrossings_before_le_integral_pos_part_aux hf hab }, { rw [not_lt, ← sub_nonpos] at hab, exact le_trans (mul_nonpos_of_nonpos_of_nonneg hab (integral_nonneg (λ ω, nat.cast_nonneg _))) (integral_nonneg (λ ω, lattice_ordered_comm_group.pos_nonneg _)) } end /-! ### Variant of the upcrossing estimate Now, we would like to prove a variant of the upcrossing estimate obtained by taking the supremum over $N$ of the original upcrossing estimate. Namely, we want the inequality $$ (b - a) \sup_N \mathbb{E}[U_N(a, b)] \le \sup_N \mathbb{E}[f_N]. $$ This inequality is central for the martingale convergence theorem as it provides a uniform bound for the upcrossings. We note that on top of taking the supremum on both sides of the inequality, we had also used the monotone convergence theorem on the left hand side to take the supremum outside of the integral. To do this, we need to make sure $U_N(a, b)$ is measurable and integrable. Integrability is easy to check as $U_N(a, b) ≤ N$ and so it suffices to show measurability. Indeed, by noting that $$ U_N(a, b) = \sum_{i = 1}^N \mathbf{1}_{\{U_N(a, b) < N\}} $$ $U_N(a, b)$ is measurable as $\{U_N(a, b) < N\}$ is a measurable set since $U_N(a, b)$ is a stopping time. -/ lemma upcrossings_before_eq_sum (hab : a < b) : upcrossings_before a b f N ω = ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i := begin by_cases hN : N = 0, { simp [hN] }, rw ← finset.sum_Ico_consecutive _ (nat.succ_le_succ zero_le') (nat.succ_le_succ (upcrossings_before_le f ω hab)), have h₁ : ∀ k ∈ finset.Ico 1 (upcrossings_before a b f N ω + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 1, { rintro k hk, rw finset.mem_Ico at hk, rw set.indicator_of_mem, { refl }, { exact upper_crossing_time_lt_of_le_upcrossings_before (zero_lt_iff.2 hN) hab (nat.lt_succ_iff.1 hk.2) } }, have h₂ : ∀ k ∈ finset.Ico (upcrossings_before a b f N ω + 1) (N + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 0, { rintro k hk, rw [finset.mem_Ico, nat.succ_le_iff] at hk, rw set.indicator_of_not_mem, simp only [set.mem_set_of_eq, not_lt], exact (upper_crossing_time_eq_of_upcrossings_before_lt hab hk.1).symm.le }, rw [finset.sum_congr rfl h₁, finset.sum_congr rfl h₂, finset.sum_const, finset.sum_const, smul_eq_mul, mul_one, smul_eq_mul, mul_zero, nat.card_Ico, nat.add_succ_sub_one, add_zero, add_zero], end lemma adapted.measurable_upcrossings_before (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings_before a b f N) := begin have : upcrossings_before a b f N = λ ω, ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i, { ext ω, exact upcrossings_before_eq_sum hab }, rw this, exact finset.measurable_sum _ (λ i hi, measurable.indicator measurable_const $ ℱ.le N _ (hf.is_stopping_time_upper_crossing_time.measurable_set_lt_of_pred N)) end lemma adapted.integrable_upcrossings_before [is_finite_measure μ] (hf : adapted ℱ f) (hab : a < b) : integrable (λ ω, (upcrossings_before a b f N ω : ℝ)) μ := begin have : ∀ᵐ ω ∂μ, ‖(upcrossings_before a b f N ω : ℝ)‖ ≤ N, { refine eventually_of_forall (λ ω, _), rw [real.norm_eq_abs, nat.abs_cast, nat.cast_le], refine upcrossings_before_le _ _ hab }, exact ⟨measurable.ae_strongly_measurable (measurable_from_top.comp (hf.measurable_upcrossings_before hab)), has_finite_integral_of_bounded this⟩ end /-- The number of upcrossings of a realization of a stochastic process (`upcrossing` takes value in `ℝ≥0∞` and so is allowed to be `∞`). -/ noncomputable def upcrossings [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (ω : Ω) : ℝ≥0∞ := ⨆ N, (upcrossings_before a b f N ω : ℝ≥0∞) lemma adapted.measurable_upcrossings (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings a b f) := measurable_supr (λ N, measurable_from_top.comp (hf.measurable_upcrossings_before hab)) lemma upcrossings_lt_top_iff : upcrossings a b f ω < ∞ ↔ ∃ k, ∀ N, upcrossings_before a b f N ω ≤ k := begin have : upcrossings a b f ω < ∞ ↔ ∃ k : ℝ≥0, upcrossings a b f ω ≤ k, { split, { intro h, lift upcrossings a b f ω to ℝ≥0 using h.ne with r hr, exact ⟨r, le_rfl⟩ }, { rintro ⟨k, hk⟩, exact lt_of_le_of_lt hk ennreal.coe_lt_top } }, simp_rw [this, upcrossings, supr_le_iff], split; rintro ⟨k, hk⟩, { obtain ⟨m, hm⟩ := exists_nat_ge k, refine ⟨m, λ N, nat.cast_le.1 ((hk N).trans _)⟩, rwa [← ennreal.coe_nat, ennreal.coe_le_coe] }, { refine ⟨k, λ N, _⟩, simp only [ennreal.coe_nat, nat.cast_le, hk N] } end /-- A variant of Doob's upcrossing estimate obtained by taking the supremum on both sides. -/ lemma submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) : ennreal.of_real (b - a) * ∫⁻ ω, upcrossings a b f ω ∂μ ≤ ⨆ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ := begin by_cases hab : a < b, { simp_rw [upcrossings], have : ∀ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ = ennreal.of_real (∫ ω, (f N ω - a)⁺ ∂μ), { intro N, rw of_real_integral_eq_lintegral_of_real, { exact (hf.sub_martingale (martingale_const _ _ _)).pos.integrable _ }, { exact eventually_of_forall (λ ω, lattice_ordered_comm_group.pos_nonneg _) } }, rw lintegral_supr', { simp_rw [this, ennreal.mul_supr, supr_le_iff], intro N, rw [(by simp : ∫⁻ ω, upcrossings_before a b f N ω ∂μ = ∫⁻ ω, ↑(upcrossings_before a b f N ω : ℝ≥0) ∂μ), lintegral_coe_eq_integral, ← ennreal.of_real_mul (sub_pos.2 hab).le], { simp_rw [nnreal.coe_nat_cast], exact (ennreal.of_real_le_of_real (hf.mul_integral_upcrossings_before_le_integral_pos_part a b N)).trans (le_supr _ N) }, { simp only [nnreal.coe_nat_cast, hf.adapted.integrable_upcrossings_before hab] } }, { exact λ n, measurable_from_top.comp_ae_measurable (hf.adapted.measurable_upcrossings_before hab).ae_measurable }, { refine eventually_of_forall (λ ω N M hNM, _), rw nat.cast_le, exact upcrossings_before_mono hab hNM ω } }, { rw [not_lt, ← sub_nonpos] at hab, rw [ennreal.of_real_of_nonpos hab, zero_mul], exact zero_le _ } end end measure_theory
ad2478664e676068fcb0eb196f694bef1b6c04f5
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/category/CompleteLat.lean
1649a5cc2e6fc45620cd121670390481d2b89367
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
2,486
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.category.BddLat import order.hom.complete_lattice /-! # The category of complete lattices This file defines `CompleteLat`, the category of complete lattices. -/ universes u open category_theory /-- The category of complete lattices. -/ def CompleteLat := bundled complete_lattice namespace CompleteLat instance : has_coe_to_sort CompleteLat Type* := bundled.has_coe_to_sort instance (X : CompleteLat) : complete_lattice X := X.str /-- Construct a bundled `CompleteLat` from a `complete_lattice`. -/ def of (α : Type*) [complete_lattice α] : CompleteLat := bundled.of α @[simp] lemma coe_of (α : Type*) [complete_lattice α] : ↥(of α) = α := rfl instance : inhabited CompleteLat := ⟨of punit⟩ instance : bundled_hom @complete_lattice_hom := { to_fun := λ _ _ _ _, coe_fn, id := @complete_lattice_hom.id, comp := @complete_lattice_hom.comp, hom_ext := λ X Y _ _, by exactI fun_like.coe_injective } instance : large_category.{u} CompleteLat := bundled_hom.category complete_lattice_hom instance : concrete_category CompleteLat := bundled_hom.concrete_category complete_lattice_hom instance has_forget_to_BddLat : has_forget₂ CompleteLat BddLat := { forget₂ := { obj := λ X, BddLat.of X, map := λ X Y, complete_lattice_hom.to_bounded_lattice_hom }, forget_comp := rfl } /-- Constructs an isomorphism of complete lattices from an order isomorphism between them. -/ @[simps] def iso.mk {α β : CompleteLat.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : CompleteLat ⥤ CompleteLat := { obj := λ X, of Xᵒᵈ, map := λ X Y, complete_lattice_hom.dual } /-- The equivalence between `CompleteLat` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : CompleteLat ≌ CompleteLat := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end CompleteLat lemma CompleteLat_dual_comp_forget_to_BddLat : CompleteLat.dual ⋙ forget₂ CompleteLat BddLat = forget₂ CompleteLat BddLat ⋙ BddLat.dual := rfl
29a90efc26bf6007cf5d625cd98594d0e671ccbc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/pprod_auto.lean
1f75d13bf13c00c15e0cf814e76ab33dff37994f
[]
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
503
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Extra facts about `pprod` -/ @[simp] theorem pprod.mk.eta {α : Sort u_1} {β : Sort u_2} {p : PProd α β} : { fst := pprod.fst p, snd := pprod.snd p } = p := pprod.cases_on p fun (a : α) (b : β) => rfl end Mathlib
74d2f4c62d43635369e9b2dbe559f8be86c7ffb8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/direct_sum/finsupp.lean
2272e12a4104a9d68dc36724d698e791e0452e70
[]
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
3,659
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.finsupp import Mathlib.linear_algebra.direct_sum.tensor_product import Mathlib.PostPort universes u u_1 v u_2 u_3 u_4 u_5 namespace Mathlib /-! # Results on direct sums and finitely supported functions. 1. The linear equivalence between finitely supported functions `ι →₀ M` and the direct sum of copies of `M` indexed by `ι`. 2. The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N). -/ /-- The finitely supported functions ι →₀ M are in linear equivalence with the direct sum of copies of M indexed by ι. -/ def finsupp_lequiv_direct_sum (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] (ι : Type u_1) [DecidableEq ι] : linear_equiv R (ι →₀ M) (direct_sum ι fun (i : ι) => M) := linear_equiv.of_linear (coe_fn finsupp.lsum ((fun (this : ι → linear_map R M (direct_sum ι fun (i : ι) => M)) => this) (direct_sum.lof R ι fun (i : ι) => M))) (direct_sum.to_module R ι (ι →₀ M) finsupp.lsingle) sorry sorry @[simp] theorem finsupp_lequiv_direct_sum_single (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] (ι : Type u_1) [DecidableEq ι] (i : ι) (m : M) : coe_fn (finsupp_lequiv_direct_sum R M ι) (finsupp.single i m) = coe_fn (direct_sum.lof R ι (fun (i : ι) => M) i) m := finsupp.sum_single_index (linear_map.map_zero ((fun (this : ι → linear_map R M (direct_sum ι fun (i : ι) => M)) => this) (direct_sum.lof R ι fun (i : ι) => M) i)) @[simp] theorem finsupp_lequiv_direct_sum_symm_lof (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] (ι : Type u_1) [DecidableEq ι] (i : ι) (m : M) : coe_fn (linear_equiv.symm (finsupp_lequiv_direct_sum R M ι)) (coe_fn (direct_sum.lof R ι (fun (i : ι) => M) i) m) = finsupp.single i m := direct_sum.to_module_lof R i m /-- The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N). -/ def finsupp_tensor_finsupp (R : Type u_1) (M : Type u_2) (N : Type u_3) (ι : Type u_4) (κ : Type u_5) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] : linear_equiv R (tensor_product R (ι →₀ M) (κ →₀ N)) (ι × κ →₀ tensor_product R M N) := linear_equiv.trans (tensor_product.congr (finsupp_lequiv_direct_sum R M ι) (finsupp_lequiv_direct_sum R N κ)) (linear_equiv.trans (tensor_product.direct_sum R ι κ (fun (i : ι) => M) fun (i : κ) => N) (linear_equiv.symm (finsupp_lequiv_direct_sum R (tensor_product R M N) (ι × κ)))) @[simp] theorem finsupp_tensor_finsupp_single (R : Type u_1) (M : Type u_2) (N : Type u_3) (ι : Type u_4) (κ : Type u_5) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] (i : ι) (m : M) (k : κ) (n : N) : coe_fn (finsupp_tensor_finsupp R M N ι κ) (tensor_product.tmul R (finsupp.single i m) (finsupp.single k n)) = finsupp.single (i, k) (tensor_product.tmul R m n) := sorry @[simp] theorem finsupp_tensor_finsupp_symm_single (R : Type u_1) (M : Type u_2) (N : Type u_3) (ι : Type u_4) (κ : Type u_5) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] (i : ι × κ) (m : M) (n : N) : coe_fn (linear_equiv.symm (finsupp_tensor_finsupp R M N ι κ)) (finsupp.single i (tensor_product.tmul R m n)) = tensor_product.tmul R (finsupp.single (prod.fst i) m) (finsupp.single (prod.snd i) n) := sorry
d75c0fa0f872e54b11e56a4ec2cdb76465c76ddf
390c7d44c0470f935f1ff06637607521791400da
/mk_inhabitant.lean
2ab6b7eceaa0037f62cc0459977bc3350e1dd824
[]
no_license
avigad/auto
32baee2744dd3ae53f1cffd3f04523b953e5a9eb
1aa4ebf60f900e8d61bb423105592a4010fa6ec5
refs/heads/master
1,594,791,920,875
1,475,608,824,000
1,475,608,824,000
67,415,120
2
0
null
null
null
null
UTF-8
Lean
false
false
551
lean
open tactic /- mk_inthabitant_using A t assumes A is an expression denoting a type. It creates a goal with type A, applies t, and returns the expression that results. -/ meta_definition mk_inhabitant_using (A : expr) (t : tactic unit) : tactic expr := do m ← mk_meta_var A, gs ← get_goals, set_goals [m], t, r ← instantiate_mvars m, set_goals gs, return r meta_definition my_tac : tactic expr := do A ← to_expr `(true ∧ true), mk_inhabitant_using A (trace_state >> repeat constructor) run_command my_tac >>= trace
d2152b09a3074f6cfedefdbbe4deff3888e6bd99
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/noncomp.lean
62bef47d727fab2b405e26b9bf748f1cd83aa9dc
[ "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
137
lean
open nat axiom n : nat definition f (x : nat) := -- Error this is not computable x + n noncomputable definition f (x : nat) := x + n
afbb6da3fca6b476ec7778202f8c5686445c9b72
2fb7334a212c3858db44039b5fa6cd57fd5d1443
/experiments/equalizer_puzzle.lean
234291aa71fd9cda2d1b7f518cffd338f899fc63
[]
no_license
ImperialCollegeLondon/condensed-sets
24514be041533b07fd62d337b1d6a5ce2b09c78c
e308291646396003dbed3896e5fbb40cb57c7050
refs/heads/master
1,628,397,992,041
1,601,549,576,000
1,601,549,576,000
224,198,323
3
1
null
1,601,549,578,000
1,574,774,780,000
Lean
UTF-8
Lean
false
false
3,625
lean
/- # An equalizer lemma. In category theory, if f and g are morphisms from X to Y, then the equalizer of (f,g) is isomorphic to the equalizer of (g,f). -/ import category_theory.limits.shapes.equalizers import category_theory.discrete_category open category_theory open category_theory.limits universes v u variables {C : Type u} [𝒞 : category.{v} C] [has_equalizers.{v} C] include 𝒞 variables {A B : C} (f g : A ⟶ B) /- I will assume people know the mathematics of equalizers and limits. ## General category-theory set-up: The abstract small category with two objects and two morphisms left -----> zero one -----> right is called `walking_parallel_pair` and there is an API which means that you often don't have to use these names explicitly. Let's just call it J. Say A and B are two objects of a category 𝒞 which has equalizers. Say f and g are two morphisms from A to B. The functor from the `walking_parallel_pair` category `J` to 𝒞 sending `zero` to `A`, `one` to `B`, `left` to `f` and `right` to `g` is called `parallel_pair f g`. We think of this functor as a diagram in the category: f ---> A B ---> g A term of type `fork f g` is a cone for this diagram, i.e. an object X and maps X -> A and X -> B making the triangles involving f and g commute. Note however that this package of data (the maps and the proofs that the diagrams commute) packaged up as a natural transformation π from the constant functor J -> 𝒞 to the `parallel_pair F G` functor (recall that a natural transformation between two functors J ⥤ C is a morphism in C for each object in J, and a proof that a diagram commutes for each morphism in J). Note that the fork is determined by the map ι : X -> A. ## How to work with the limits. The limit data itself (the object and the cone and the proof that the cone satisfies a universal property) is obtained by type class inference. User access to the limit data is via an API. The limit object is `equalizer f g`. The map from this object to A is `equalizer.ι f g` . The universal property is given by equalizer.lift -/ #check category_theory.limits.has_limit #check category_theory.limits.limit #check equalizer --set_option profiler true def equalizer.symm.hom : equalizer g f ⟶ equalizer f g := equalizer.lift _ _ (equalizer.ι g f) (equalizer.condition g f).symm -- elaboration of equalizer.symm.hom took 935ms /- let s : cone (parallel_pair f g) := fork.of_ι (limit.π (parallel_pair g f) walking_parallel_pair.zero) begin convert limit.w (parallel_pair g f) walking_parallel_pair_hom.right, convert limit.w (parallel_pair g f) walking_parallel_pair_hom.left, end in (has_limit.is_limit (parallel_pair f g)).lift s -/ #print equalizer.symm.hom def equalizer.symm : equalizer f g ≅ equalizer g f := { hom := equalizer.symm.hom g f, inv := equalizer.symm.hom f g, -- this follows from uniqueness of maps making stuff commute hom_inv_id' := begin letI haslim : has_limit (parallel_pair f g) := by apply_instance, rw (haslim.is_limit.uniq haslim.cone (𝟙 (equalizer f g))), { rw haslim.is_limit.uniq haslim.cone (equalizer.symm.hom g f ≫ equalizer.symm.hom f g), intro j, rw category.assoc, let XXX := haslim.is_limit.fac, unfold equalizer.symm.hom, rw haslim.is_limit.fac, let YYY := (has_limit.is_limit (parallel_pair f g)).fac (has_limit.cone (parallel_pair f g)) j, convert YYY using 1, rw YYY, sorry}, { sorry}, -- apply limit.hom_ext, end, inv_hom_id' := sorry }
21fe440d5d259f5b678a9e996d610646aa2ac844
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/pfunctor/univariate/default.lean
157e8d4adb6cd281abebdcb428cdb3b0e3cf4e9c
[ "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
72
lean
import data.pfunctor.univariate.basic import data.pfunctor.univariate.M
e52ec92d79016699228b8d149576c0cd9ac1f99f
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/topology/algebra/group.lean
30cb0696cdd8b724958518913d9f8647e98294c3
[ "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
17,307
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of topological groups. -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph open classical set filter topological_space open_locale classical topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group section prio set_option default_priority 100 -- see Note [default priority] /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends topological_add_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive topological_add_group] class topological_group (α : Type*) [topological_space α] [group α] extends topological_monoid α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) end prio variables [topological_space α] [group α] @[to_additive] lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv @[to_additive] lemma continuous.inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf @[to_additive] lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) := tendsto.comp (continuous_iff_continuous_at.mp topological_group.continuous_inv a) hf @[to_additive] lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β} (hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x := hf.inv @[to_additive] lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) : continuous_within_at (λx, (f x)⁻¹) s x := hf.inv @[to_additive topological_add_group] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv } attribute [instance] prod.topological_add_group @[to_additive] protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive] protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv α } @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) := tendsto_mul (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) ((𝓝 (1:α)).prod (𝓝 (1:α))) (𝓝 1), { simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ (𝓝 (1:α)).prod (𝓝 (1:α)) := this (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1), { simpa using (@tendsto_id α (𝓝 1)).inv }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa }, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : set α) [normal_subgroup N] @[to_additive] instance {α : Type u} [group α] [topological_space α] (N : set α) [normal_subgroup N] : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance open quotient_group @[to_additive quotient_add_group_saturate] lemma quotient_group_saturate {α : Type u} [group α] (N : set α) [normal_subgroup N] (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left, hi]⟩ } end @[to_additive] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive topological_add_group_quotient] instance topological_group_quotient : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_fst.sub continuous_snd lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := continuous_sub.comp_continuous_on (hf.prod hg) lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x end topological_add_group section prio set_option default_priority 100 -- see Note [default priority] /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z [] : filter α) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) end prio namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ v w ∈ V, v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ (Z α).prod (Z α) := add_Z (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 b t0 hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa using eqt _ _ hxt hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : topological_add_monoid α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α)) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul local attribute [instance] set.pointwise_one set.pointwise_mul set.pointwise_add filter.pointwise_mul filter.pointwise_add filter.pointwise_one section variables [topological_space α] [group α] [topological_group α] @[to_additive] lemma is_open_pointwise_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : α), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw pointwise_mul_eq_Union_mul_left, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open_pointwise_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : α), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw pointwise_mul_eq_Union_mul_right, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (α) lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space α] : regular_space α := ⟨assume s a hs ha, let f := λ p : α × α, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in begin use s * t₂, use is_open_pointwise_mul_left ht₂, use λ x hx, ⟨x, hx, 1, one_mem_t₂, (mul_one _).symm⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, hy, z, hz, yz⟩, have : x * z⁻¹ ∈ -s := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α end section variables [topological_space α] [comm_group α] [topological_group α] @[to_additive] lemma nhds_pointwise_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, v_mem, w, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, ⟨b, hb, ba⟩, c, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, _, y, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_pointwise_mul _ _⟩ end end filter_mul
5d3b0366e786e9fe0ef553f2c11a6c4661c5a9f8
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/pnat/interval.lean
3505c0fe5fff13c4ed5fe6b3174754300ddb261a
[ "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
2,003
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.nat.interval /-! # Finite intervals of positive naturals This file proves that `ℕ+` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset pnat instance : locally_finite_order ℕ+ := subtype.locally_finite_order _ namespace pnat variables (a b : ℕ+) lemma Icc_eq_finset_subtype : Icc a b = (Icc (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma map_subtype_embedding_Icc : (Icc a b).map (function.embedding.subtype _) = Icc (a : ℕ) b := map_subtype_embedding_Icc _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) lemma map_subtype_embedding_Ioc : (Ioc a b).map (function.embedding.subtype _) = Ioc (a : ℕ) b := map_subtype_embedding_Ioc _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) lemma map_subtype_embedding_Ioo : (Ioo a b).map (function.embedding.subtype _) = Ioo (a : ℕ) b := map_subtype_embedding_Ioo _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [←nat.card_Icc, ←map_subtype_embedding_Icc, card_map] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioc, card_map] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [←nat.card_Ioo, ←map_subtype_embedding_Ioo, card_map] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] end pnat
46d5d17d0b44c8dd8845e01713188507cefdcf44
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/measure_theory/outer_measure.lean
f74c7fa524c7f2ce159df240058bb5518117119d
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
40,626
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 analysis.specific_limits import measure_theory.measurable_space import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ennreal`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ennreal` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators nnreal namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑'i, measure_of (s i))) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑'i, m (s i)) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma injective_coe_fn : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := injective_coe_fn $ funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ennreal, from coe_fn) injective_coe_fn rfl (λ _ _, rfl) } instance : has_scalar ennreal (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ennreal) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ennreal) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul := (•), .. injective.semimodule ennreal ⟨show outer_measure α → set α → ennreal, from coe_fn, coe_zero, coe_add⟩ injective_coe_fn coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := nonpos_iff_eq_zero.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ (∑' (i : ℕ), m (f i)) : m.Union_nat _ ... ≤ (∑'i, ⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ennreal] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, injective_coe_fn rfl, map_smul' := λ c m, injective_coe_fn rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ennreal] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ennreal] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr ((⊤ : ennreal) • dirac a) trivial) end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑'i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑'i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑'i, m (f i)) = ∑ i in {0}, m (f i) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ (∑'i, m (s i))) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section bounded_by variables {α : Type*} (m : set α → ennreal) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ (∑'i, m (s i))) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact is_caratheodory_union m (h n (le_refl (n + 1))) (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), is_caratheodory_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.is_measurable' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.is_measurable' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ennreal} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.is_measurable' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := begin have hm2 : ((measure_theory.outer_measure.restrict s) '' m).nonempty := set.nonempty_image_iff.mpr hm, ext1 u, rw [restrict_apply, Inf_apply hm, Inf_apply hm2], apply le_antisymm; simp only [set.mem_image, infi_exists, le_infi_iff]; intros t hu, { refine infi_le_of_le (λ n, (t n) ∩ s) _, refine infi_le_of_le _ _, { rw [← Union_inter], exact inter_subset_inter hu subset.rfl }, apply ennreal.tsum_le_tsum (λ n, _) , simp only [and_imp, set.mem_image, infi_exists, le_infi_iff], rintro _ ⟨μ, h_μ_in_s, rfl⟩, refine infi_le_of_le μ _, refine infi_le_of_le h_μ_in_s _, simp_rw [restrict_apply, le_refl] }, { refine infi_le_of_le (λ n, (t n) ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [inter_subset, set.union_comm, Union_union] at hu }, apply ennreal.tsum_le_tsum (λ n, _), refine le_binfi (λ μ hμ, _), refine infi_le_of_le (restrict s μ) _, refine infi_le_of_le ⟨_, hμ, rfl⟩ _, rw [restrict_apply, union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, end end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = is_measurable`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ennreal) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ennreal`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ennreal := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ennreal} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = (∑'i, m (f i) (hm i))) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ (∑'i, m (f i) (hm i))) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = (∑'i, m (f i) (hm i))) : extend m (⋃i, f i) = (∑'i, extend m (f i)) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ (∑'i, extend m (s i)) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = (∑'i, extend m (f i)) := begin rw [← encodable.Union_decode2, ← tsum_Union_decode2], { exact extend_Union_nat PU (λ n, encodable.Union_decode2_cases P0 hm) (mU _ (encodable.Union_decode2_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ⊤) {ε : ℝ≥0} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.is_measurable' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `is_measurable` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), is_measurable s → ennreal} variables (m0 : m ∅ is_measurable.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union is_measurable.empty m0 is_measurable.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ (∑'i, extend m (s i)) := begin refine extend_Union_le_tsum_nat' is_measurable.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (is_measurable.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (is_measurable.disjointed h _) (inter_subset_left _ _) end lemma induced_outer_measure_eq_extend {s : set α} (hs : is_measurable s) : induced_outer_measure m is_measurable.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : is_measurable s) : induced_outer_measure m is_measurable.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) is_measurable.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s := induced_outer_measure_eq' is_measurable.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim := λ s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, is_measurable s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi is_measurable.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (le_trim _) @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ is_measurable.univ) (zero_le _) theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := begin ext1 s, simp only [trim_eq_infi', add_apply], rw ennreal.infi_add_infi, rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩, exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩, add_le_add (m₁.mono' (inter_subset_left _ _)) (m₂.mono' (inter_subset_right _ _))⟩, end theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_is_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ m t = 0 := begin erw [trim_eq_infi, infi_eq_bot] at h, choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ m t < n⁻¹, { assume n, have : (0 : ennreal) < n⁻¹ := (ennreal.inv_pos.2 $ ennreal.nat_ne_top _), rcases h _ this with ⟨t, ht⟩, use [t], simpa only [infi_lt_iff, exists_prop] using ht }, refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩, refine le_antisymm _ (zero_le _), refine le_of_tendsto_of_tendsto tendsto_const_nhds ennreal.tendsto_inv_nat_nhds_zero (eventually_of_forall $ assume n, _), exact le_trans (m.mono' $ Inter_subset _ _) (le_of_lt (ht n).2.2) end theorem trim_smul (c : ennreal) (m : outer_measure α) : (c • m).trim = c • m.trim := begin ext1 s, simp only [trim_eq_infi', smul_apply], haveI : nonempty {t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ _, is_measurable.univ⟩⟩, refine ennreal.infi_mul_left (assume hc hs, _), rw ← trim_eq_infi' at hs, simpa [and_assoc] using exists_is_measurable_superset_of_trim_eq_zero hs end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : is_measurable s) : (restrict s μ).trim = restrict s μ.trim := begin apply measure_theory.outer_measure.ext, intro t, simp_rw [restrict_apply, trim_eq_infi, restrict_apply], apply le_antisymm, { simp only [le_infi_iff], intros v h_subset hv, refine infi_le_of_le (v ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [set.union_comm, ← inter_subset] }, refine infi_le_of_le (hv.union hs.compl) _, rw [union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, { simp only [le_infi_iff], intros u h_subset hu, refine infi_le_of_le (u ∩ s) _, refine infi_le_of_le (set.inter_subset_inter_left _ h_subset) _, refine infi_le_of_le (hu.inter hs) le_rfl }, end end outer_measure end measure_theory
123c335b98286c480af1e741d167fdf9b847ca02
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_561.lean
a830f0dea58fbe9db965f048d8b00393680c203c
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
88
lean
variables p : Prop -- BEGIN example (h₁ : ¬p) (h₂ : p) : false := h₁ h₂ -- END
931f366ccddeb8404743f5631195d007ef7ea099
9b0cdc31ceef59f5fbd4e20acad77a7a59044088
/src/exercises/03_forall_or.lean
0a68d11c26dc72d8634465628db0468d05953029
[ "Apache-2.0" ]
permissive
andrewparr/tutorials
964ebb8b4eae2b658a946843f8f9fc5c69b79761
0fd6cefe7e62f0d4bfa12ebd115913f8ef4fbd62
refs/heads/master
1,687,573,595,883
1,626,653,659,000
1,626,653,659,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,146
lean
import data.real.basic import algebra.group.pi set_option pp.beta true /- In this file, we'll learn about the ∀ quantifier, and the disjunction operator ∨ (logical OR). Let P be a predicate on a type X. This means for every mathematical object x with type X, we get a mathematical statement P x. In Lean, P x has type Prop. Lean sees a proof h of `∀ x, P x` as a function sending any `x : X` to a proof `h x` of `P x`. This already explains the main way to use an assumption or lemma which starts with a ∀. In order to prove `∀ x, P x`, we use `intros x` to fix an arbitrary object with type X, and call it x. Note also we don't need to give the type of x in the expression `∀ x, P x` as long as the type of P is clear to Lean, which can then infer the type of x. Let's define two predicates to play with ∀. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = -f x /- In the next proof, we also take the opportunity to introduce the `unfold` tactic, which simply unfolds definitions. Here this is purely for didactic reason, Lean doesn't need those `unfold` invocations. We will also use `rfl` which is a term proving equalities that are true by definition (in a very strong sense to be discussed later). -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin -- Assume f is even intros hf, -- which means ∀ x, f (-x) = f x unfold even_fun at hf, -- and the same for g intros hg, unfold even_fun at hg, -- We need to prove ∀ x, (f+g)(-x) = (f+g)(x) unfold even_fun, -- Let x be any real number intros x, -- and let's compute calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g (-x) : by rw hf x ... = f x + g x : by rw hg x ... = (f + g) x : rfl end /- In the preceding proof, all `unfold` lines are purely for psychological comfort. Sometimes unfolding is necessary because we want to apply a tactic that operates purely on the syntactical level. The main such tactic is `rw`. The same property of `rw` explain why the first computation line is necessary, although its proof is simply `rfl`. Before that line, `rw hf x` won't find anything like `f (-x)` hence will give up. The last line is not necessary however, since it only proves something that is true by definition, and is not followed by a `rw`. Also, Lean doesn't need to be told that hf should be specialized to x before rewriting, exactly as in the first file 01_equality_rewriting. We can also gather several rewrites using a list of expressions. One last trick is that `rw` can take a list of expressions to use for rewriting. For instance `rw [h₁, h₂, h₃]` is equivalent to three lines `rw h₁`, `rw h₂` and `rw h₃`. Note that you can inspect the tactic state between those rewrites when reading a proof using this syntax. You simply need to move the cursor inside the list. Hence we can compress the above proof to: -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin intros hf hg x, calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g x : by rw [hf, hg] end /- Now let's practice. If you need to learn how to type a unicode symbol, you can put your mouse cursor above the symbol and wait for one second. -/ -- 0023 example (f g : ℝ → ℝ) : even_fun f → even_fun (g ∘ f) := begin sorry end -- 0024 example (f g : ℝ → ℝ) : odd_fun f → odd_fun g → odd_fun (g ∘ f) := begin sorry end /- Let's have more quantifiers, and play with forward and backward reasoning. In the next definitions, note how `∀ x₁, ∀ x₂` is abreviated to `∀ x₁ x₂`. -/ def non_decreasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≤ f x₂ def non_increasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≥ f x₂ /- Let's be very explicit and use forward reasonning first. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- Since f is non-decreasing, f x₁ ≤ f x₂. have step₁ : f x₁ ≤ f x₂, exact hf x₁ x₂ h, -- Since g is non-decreasing, we then get g (f x₁) ≤ g (f x₂). exact hg (f x₁) (f x₂) step₁, end /- In the above proof, note how inconvenient it is to specify x₁ and x₂ in `hf x₁ x₂ h` since they could be inferred from the type of h. We could have written `hf _ _ h` and Lean would have filled the holes denoted by _. Even better we could have written the definition of `non_decreasing` as: ∀ {x₁ x₂}, x₁ ≤ x₂ → f x₁ ≤ f x₂, with curly braces to denote implicit arguments. But let's leave that aside for now. One possible variation on the above proof is to use the `specialize` tactic to replace hf by its specialization to the relevant value. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, specialize hf x₁ x₂ h, exact hg (f x₁) (f x₂) hf, end /- This `specialize` tactic is mostly useful for exploration, or in preparation for rewriting in the assumption. One can very often replace its use by using more complicated expressions directly involving the original assumption, as in the next variation: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, exact hg (f x₁) (f x₂) (hf x₁ x₂ h), end /- Since the above proof uses only `intros` and `exact`, we could very easily replace it by the raw proof term: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := λ x₁ x₂ h, hg (f x₁) (f x₂) (hf x₁ x₂ h) /- Of course the above proof is difficult to decipher. The principle in mathlib is to use such a proof when the result is obvious and you don't want to read the proof anyway. Instead of pursuing this style, let's see how backward reasoning would look like here. As usual with this style, we use `apply` and enjoy Lean specializing assumptions for us using unification. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- We need to prove (g ∘ f) x₁ ≤ (g ∘ f) x₂. -- Since g is non-decreasing, it suffices to prove f x₁ ≤ f x₂ apply hg, -- which follows from our assumption on f apply hf, -- and on x₁ and x₂ exact h end -- 0025 example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_increasing g) : non_increasing (g ∘ f) := begin sorry end /- Let's switch to disjunctions now. Lean denotes by ∨ the logical OR operator. In order to make use of an assumption hyp : P ∨ Q we use the cases tactic: cases hyp with hP hQ which creates two proof branches: one branch assuming hP : P, and one branch assuming hQ : Q. In order to directly prove a goal P ∨ Q, we use either the `left` tactic and prove P or the `right` tactic and prove Q. In the next proof we use `ring` and `linarith` to get rid of easy computations or inequalities, as well as one lemma: mul_eq_zero : a*b = 0 ↔ a = 0 ∨ b = 0 -/ example (a b : ℝ) : a = a*b → a = 0 ∨ b = 1 := begin intro hyp, have H : a*(1 - b) = 0, { calc a*(1 - b) = a - a*b : by ring ... = 0 : by linarith, }, rw mul_eq_zero at H, cases H with Ha Hb, { left, exact Ha, }, { right, linarith, }, end -- 0026 example (x y : ℝ) : x^2 = y^2 → x = y ∨ x = -y := begin sorry end /- In the next exercise, we can use: eq_or_lt_of_le : x ≤ y → x = y ∨ x < y -/ -- 0027 example (f : ℝ → ℝ) : non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y := begin sorry end /- In the next exercise, we can use: le_total x y : x ≤ y ∨ y ≤ x -/ -- 0028 example (f : ℝ → ℝ) (h : non_decreasing f) (h' : ∀ x, f (f x) = x) : ∀ x, f x = x := begin sorry end
cd4b2791aadec8808bdbcc70f13d4c235b8f3b74
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex16.lean
a92633ce38e12570d42f6a1ccfc4e390f81f18cd
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
449
lean
def double (x : ℕ) : ℕ := x + x print double check double 3 eval double 3 -- 6 def square (x : ℕ) := x * x print square check square 3 eval square 3 -- 9 def do_twice (f : ℕ → ℕ) (x : ℕ) : ℕ := f (f x) eval do_twice double 2 -- 8 /- These definitions are equivalent to -/ def double' : ℕ → ℕ := λ x, x + x def square' : ℕ → ℕ := λ x, x * x def do_twice' : (ℕ → ℕ) → ℕ → ℕ := λ f x, f (f x)
734eaeefaca17d3c152165d296b69f33fa4e505a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/cover.lean
b8b9b6e84213fc6dff64e61c8f3cb8a10804b809
[ "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
16,172
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, Violeta Hernández Palacios, Grayson Burton, Floris van Doorn -/ import data.set.intervals.ord_connected import order.antisymmetrization /-! # The covering relation This file defines the covering relation in an order. `b` is said to cover `a` if `a < b` and there is no element in between. We say that `b` weakly covers `a` if `a ≤ b` and there is no element between `a` and `b`. In a partial order this is equivalent to `a ⋖ b ∨ a = b`, in a preorder this is equivalent to `a ⋖ b ∨ (a ≤ b ∧ b ≤ a)` ## Notation * `a ⋖ b` means that `b` covers `a`. * `a ⩿ b` means that `b` weakly covers `a`. -/ open set order_dual variables {α β : Type*} section weakly_covers section preorder variables [preorder α] [preorder β] {a b c : α} /-- `wcovby a b` means that `a = b` or `b` covers `a`. This means that `a ≤ b` and there is no element in between. -/ def wcovby (a b : α) : Prop := a ≤ b ∧ ∀ ⦃c⦄, a < c → ¬ c < b infix ` ⩿ `:50 := wcovby lemma wcovby.le (h : a ⩿ b) : a ≤ b := h.1 lemma wcovby.refl (a : α) : a ⩿ a := ⟨le_rfl, λ c hc, hc.not_lt⟩ lemma wcovby.rfl : a ⩿ a := wcovby.refl a protected lemma eq.wcovby (h : a = b) : a ⩿ b := h ▸ wcovby.rfl lemma wcovby_of_le_of_le (h1 : a ≤ b) (h2 : b ≤ a) : a ⩿ b := ⟨h1, λ c hac hcb, (hac.trans hcb).not_le h2⟩ alias wcovby_of_le_of_le ← has_le.le.wcovby_of_le lemma antisymm_rel.wcovby (h : antisymm_rel (≤) a b) : a ⩿ b := wcovby_of_le_of_le h.1 h.2 lemma wcovby.wcovby_iff_le (hab : a ⩿ b) : b ⩿ a ↔ b ≤ a := ⟨λ h, h.le, λ h, h.wcovby_of_le hab.le⟩ lemma wcovby_of_eq_or_eq (hab : a ≤ b) (h : ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b) : a ⩿ b := ⟨hab, λ c ha hb, (h c ha.le hb.le).elim ha.ne' hb.ne⟩ lemma antisymm_rel.trans_wcovby (hab : antisymm_rel (≤) a b) (hbc : b ⩿ c) : a ⩿ c := ⟨hab.1.trans hbc.le, λ d had hdc, hbc.2 (hab.2.trans_lt had) hdc⟩ lemma wcovby_congr_left (hab : antisymm_rel (≤) a b) : a ⩿ c ↔ b ⩿ c := ⟨hab.symm.trans_wcovby, hab.trans_wcovby⟩ lemma wcovby.trans_antisymm_rel (hab : a ⩿ b) (hbc : antisymm_rel (≤) b c) : a ⩿ c := ⟨hab.le.trans hbc.1, λ d had hdc, hab.2 had $ hdc.trans_le hbc.2⟩ lemma wcovby_congr_right (hab : antisymm_rel (≤) a b) : c ⩿ a ↔ c ⩿ b := ⟨λ h, h.trans_antisymm_rel hab, λ h, h.trans_antisymm_rel hab.symm⟩ /-- If `a ≤ b`, then `b` does not cover `a` iff there's an element in between. -/ lemma not_wcovby_iff (h : a ≤ b) : ¬ a ⩿ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [wcovby, h, true_and, not_forall, exists_prop, not_not] instance wcovby.is_refl : is_refl α (⩿) := ⟨wcovby.refl⟩ lemma wcovby.Ioo_eq (h : a ⩿ b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x hx, h.2 hx.1 hx.2 lemma wcovby_iff_Ioo_eq : a ⩿ b ↔ a ≤ b ∧ Ioo a b = ∅ := and_congr_right' $ by simp [eq_empty_iff_forall_not_mem] lemma wcovby.of_image (f : α ↪o β) (h : f a ⩿ f b) : a ⩿ b := ⟨f.le_iff_le.mp h.le, λ c hac hcb, h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ lemma wcovby.image (f : α ↪o β) (hab : a ⩿ b) (h : (range f).ord_connected) : f a ⩿ f b := begin refine ⟨f.monotone hab.le, λ c ha hb, _⟩, obtain ⟨c, rfl⟩ := h.out (mem_range_self _) (mem_range_self _) ⟨ha.le, hb.le⟩, rw f.lt_iff_lt at ha hb, exact hab.2 ha hb, end lemma set.ord_connected.apply_wcovby_apply_iff (f : α ↪o β) (h : (range f).ord_connected) : f a ⩿ f b ↔ a ⩿ b := ⟨λ h2, h2.of_image f, λ hab, hab.image f h⟩ @[simp] lemma apply_wcovby_apply_iff {E : Type*} [order_iso_class E α β] (e : E) : e a ⩿ e b ↔ a ⩿ b := (ord_connected_range (e : α ≃o β)).apply_wcovby_apply_iff ((e : α ≃o β) : α ↪o β) @[simp] lemma to_dual_wcovby_to_dual_iff : to_dual b ⩿ to_dual a ↔ a ⩿ b := and_congr_right' $ forall_congr $ λ c, forall_swap @[simp] lemma of_dual_wcovby_of_dual_iff {a b : αᵒᵈ} : of_dual a ⩿ of_dual b ↔ b ⩿ a := and_congr_right' $ forall_congr $ λ c, forall_swap alias to_dual_wcovby_to_dual_iff ↔ _ wcovby.to_dual alias of_dual_wcovby_of_dual_iff ↔ _ wcovby.of_dual end preorder section partial_order variables [partial_order α] {a b c : α} lemma wcovby.eq_or_eq (h : a ⩿ b) (h2 : a ≤ c) (h3 : c ≤ b) : c = a ∨ c = b := begin rcases h2.eq_or_lt with h2|h2, { exact or.inl h2.symm }, rcases h3.eq_or_lt with h3|h3, { exact or.inr h3 }, exact (h.2 h2 h3).elim end /-- An `iff` version of `wcovby.eq_or_eq` and `wcovby_of_eq_or_eq`. -/ lemma wcovby_iff_le_and_eq_or_eq : a ⩿ b ↔ a ≤ b ∧ ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b := ⟨λ h, ⟨h.le, λ c, h.eq_or_eq⟩, and.rec wcovby_of_eq_or_eq⟩ lemma wcovby.le_and_le_iff (h : a ⩿ b) : a ≤ c ∧ c ≤ b ↔ c = a ∨ c = b := begin refine ⟨λ h2, h.eq_or_eq h2.1 h2.2, _⟩, rintro (rfl|rfl), exacts [⟨le_rfl, h.le⟩, ⟨h.le, le_rfl⟩] end lemma wcovby.Icc_eq (h : a ⩿ b) : Icc a b = {a, b} := by { ext c, exact h.le_and_le_iff } lemma wcovby.Ico_subset (h : a ⩿ b) : Ico a b ⊆ {a} := by rw [← Icc_diff_right, h.Icc_eq, diff_singleton_subset_iff, pair_comm] lemma wcovby.Ioc_subset (h : a ⩿ b) : Ioc a b ⊆ {b} := by rw [← Icc_diff_left, h.Icc_eq, diff_singleton_subset_iff] end partial_order section semilattice_sup variables [semilattice_sup α] {a b c : α} lemma wcovby.sup_eq (hac : a ⩿ c) (hbc : b ⩿ c) (hab : a ≠ b) : a ⊔ b = c := (sup_le hac.le hbc.le).eq_of_not_lt $ λ h, hab.lt_sup_or_lt_sup.elim (λ h', hac.2 h' h) (λ h', hbc.2 h' h) end semilattice_sup section semilattice_inf variables [semilattice_inf α] {a b c : α} lemma wcovby.inf_eq (hca : c ⩿ a) (hcb : c ⩿ b) (hab : a ≠ b) : a ⊓ b = c := (le_inf hca.le hcb.le).eq_of_not_gt $ λ h, hab.inf_lt_or_inf_lt.elim (hca.2 h) (hcb.2 h) end semilattice_inf end weakly_covers section has_lt variables [has_lt α] {a b : α} /-- `covby a b` means that `b` covers `a`: `a < b` and there is no element in between. -/ def covby (a b : α) : Prop := a < b ∧ ∀ ⦃c⦄, a < c → ¬ c < b infix ` ⋖ `:50 := covby lemma covby.lt (h : a ⋖ b) : a < b := h.1 /-- If `a < b`, then `b` does not cover `a` iff there's an element in between. -/ lemma not_covby_iff (h : a < b) : ¬a ⋖ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [covby, h, true_and, not_forall, exists_prop, not_not] alias not_covby_iff ↔ exists_lt_lt_of_not_covby _ alias exists_lt_lt_of_not_covby ← has_lt.lt.exists_lt_lt /-- In a dense order, nothing covers anything. -/ lemma not_covby [densely_ordered α] : ¬ a ⋖ b := λ h, let ⟨c, hc⟩ := exists_between h.1 in h.2 hc.1 hc.2 lemma densely_ordered_iff_forall_not_covby : densely_ordered α ↔ ∀ a b : α, ¬ a ⋖ b := ⟨λ h a b, @not_covby _ _ _ _ h, λ h, ⟨λ a b hab, exists_lt_lt_of_not_covby hab $ h _ _⟩⟩ @[simp] lemma to_dual_covby_to_dual_iff : to_dual b ⋖ to_dual a ↔ a ⋖ b := and_congr_right' $ forall_congr $ λ c, forall_swap @[simp] lemma of_dual_covby_of_dual_iff {a b : αᵒᵈ} : of_dual a ⋖ of_dual b ↔ b ⋖ a := and_congr_right' $ forall_congr $ λ c, forall_swap alias to_dual_covby_to_dual_iff ↔ _ covby.to_dual alias of_dual_covby_of_dual_iff ↔ _ covby.of_dual end has_lt section preorder variables [preorder α] [preorder β] {a b c : α} lemma covby.le (h : a ⋖ b) : a ≤ b := h.1.le protected lemma covby.ne (h : a ⋖ b) : a ≠ b := h.lt.ne lemma covby.ne' (h : a ⋖ b) : b ≠ a := h.lt.ne' protected lemma covby.wcovby (h : a ⋖ b) : a ⩿ b := ⟨h.le, h.2⟩ lemma wcovby.covby_of_not_le (h : a ⩿ b) (h2 : ¬ b ≤ a) : a ⋖ b := ⟨h.le.lt_of_not_le h2, h.2⟩ lemma wcovby.covby_of_lt (h : a ⩿ b) (h2 : a < b) : a ⋖ b := ⟨h2, h.2⟩ lemma not_covby_of_lt_of_lt (h₁ : a < b) (h₂ : b < c) : ¬ a ⋖ c := (not_covby_iff (h₁.trans h₂)).2 ⟨b, h₁, h₂⟩ lemma covby_iff_wcovby_and_lt : a ⋖ b ↔ a ⩿ b ∧ a < b := ⟨λ h, ⟨h.wcovby, h.lt⟩, λ h, h.1.covby_of_lt h.2⟩ lemma covby_iff_wcovby_and_not_le : a ⋖ b ↔ a ⩿ b ∧ ¬ b ≤ a := ⟨λ h, ⟨h.wcovby, h.lt.not_le⟩, λ h, h.1.covby_of_not_le h.2⟩ lemma wcovby_iff_covby_or_le_and_le : a ⩿ b ↔ a ⋖ b ∨ (a ≤ b ∧ b ≤ a) := ⟨λ h, or_iff_not_imp_right.mpr $ λ h', h.covby_of_not_le $ λ hba, h' ⟨h.le, hba⟩, λ h', h'.elim (λ h, h.wcovby) (λ h, h.1.wcovby_of_le h.2)⟩ lemma antisymm_rel.trans_covby (hab : antisymm_rel (≤) a b) (hbc : b ⋖ c) : a ⋖ c := ⟨hab.1.trans_lt hbc.lt, λ d had hdc, hbc.2 (hab.2.trans_lt had) hdc⟩ lemma covby_congr_left (hab : antisymm_rel (≤) a b) : a ⋖ c ↔ b ⋖ c := ⟨hab.symm.trans_covby, hab.trans_covby⟩ lemma covby.trans_antisymm_rel (hab : a ⋖ b) (hbc : antisymm_rel (≤) b c) : a ⋖ c := ⟨hab.lt.trans_le hbc.1, λ d had hdb, hab.2 had $ hdb.trans_le hbc.2⟩ lemma covby_congr_right (hab : antisymm_rel (≤) a b) : c ⋖ a ↔ c ⋖ b := ⟨λ h, h.trans_antisymm_rel hab, λ h, h.trans_antisymm_rel hab.symm⟩ instance : is_nonstrict_strict_order α (⩿) (⋖) := ⟨λ a b, covby_iff_wcovby_and_not_le.trans $ and_congr_right $ λ h, h.wcovby_iff_le.not.symm⟩ instance covby.is_irrefl : is_irrefl α (⋖) := ⟨λ a ha, ha.ne rfl⟩ lemma covby.Ioo_eq (h : a ⋖ b) : Ioo a b = ∅ := h.wcovby.Ioo_eq lemma covby_iff_Ioo_eq : a ⋖ b ↔ a < b ∧ Ioo a b = ∅ := and_congr_right' $ by simp [eq_empty_iff_forall_not_mem] lemma covby.of_image (f : α ↪o β) (h : f a ⋖ f b) : a ⋖ b := ⟨f.lt_iff_lt.mp h.lt, λ c hac hcb, h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ lemma covby.image (f : α ↪o β) (hab : a ⋖ b) (h : (range f).ord_connected) : f a ⋖ f b := (hab.wcovby.image f h).covby_of_lt $ f.strict_mono hab.lt lemma set.ord_connected.apply_covby_apply_iff (f : α ↪o β) (h : (range f).ord_connected) : f a ⋖ f b ↔ a ⋖ b := ⟨covby.of_image f, λ hab, hab.image f h⟩ @[simp] lemma apply_covby_apply_iff {E : Type*} [order_iso_class E α β] (e : E) : e a ⋖ e b ↔ a ⋖ b := (ord_connected_range (e : α ≃o β)).apply_covby_apply_iff ((e : α ≃o β) : α ↪o β) lemma covby_of_eq_or_eq (hab : a < b) (h : ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b) : a ⋖ b := ⟨hab, λ c ha hb, (h c ha.le hb.le).elim ha.ne' hb.ne⟩ end preorder section partial_order variables [partial_order α] {a b c : α} lemma wcovby.covby_of_ne (h : a ⩿ b) (h2 : a ≠ b) : a ⋖ b := ⟨h.le.lt_of_ne h2, h.2⟩ lemma covby_iff_wcovby_and_ne : a ⋖ b ↔ a ⩿ b ∧ a ≠ b := ⟨λ h, ⟨h.wcovby, h.ne⟩, λ h, h.1.covby_of_ne h.2⟩ lemma wcovby_iff_covby_or_eq : a ⩿ b ↔ a ⋖ b ∨ a = b := by rw [le_antisymm_iff, wcovby_iff_covby_or_le_and_le] lemma covby.eq_or_eq (h : a ⋖ b) (h2 : a ≤ c) (h3 : c ≤ b) : c = a ∨ c = b := h.wcovby.eq_or_eq h2 h3 /-- An `iff` version of `covby.eq_or_eq` and `covby_of_eq_or_eq`. -/ lemma covby_iff_lt_and_eq_or_eq : a ⋖ b ↔ a < b ∧ ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b := ⟨λ h, ⟨h.lt, λ c, h.eq_or_eq⟩, and.rec covby_of_eq_or_eq⟩ lemma covby.Ico_eq (h : a ⋖ b) : Ico a b = {a} := by rw [←Ioo_union_left h.lt, h.Ioo_eq, empty_union] lemma covby.Ioc_eq (h : a ⋖ b) : Ioc a b = {b} := by rw [←Ioo_union_right h.lt, h.Ioo_eq, empty_union] lemma covby.Icc_eq (h : a ⋖ b) : Icc a b = {a, b} := h.wcovby.Icc_eq end partial_order section linear_order variables [linear_order α] {a b c : α} lemma covby.Ioi_eq (h : a ⋖ b) : Ioi a = Ici b := by rw [← Ioo_union_Ici_eq_Ioi h.lt, h.Ioo_eq, empty_union] lemma covby.Iio_eq (h : a ⋖ b) : Iio b = Iic a := by rw [← Iic_union_Ioo_eq_Iio h.lt, h.Ioo_eq, union_empty] lemma wcovby.le_of_lt (hab : a ⩿ b) (hcb : c < b) : c ≤ a := not_lt.1 $ λ hac, hab.2 hac hcb lemma wcovby.ge_of_gt (hab : a ⩿ b) (hac : a < c) : b ≤ c := not_lt.1 $ hab.2 hac lemma covby.le_of_lt (hab : a ⋖ b) : c < b → c ≤ a := hab.wcovby.le_of_lt lemma covby.ge_of_gt (hab : a ⋖ b) : a < c → b ≤ c := hab.wcovby.ge_of_gt lemma covby.unique_left (ha : a ⋖ c) (hb : b ⋖ c) : a = b := (hb.le_of_lt ha.lt).antisymm $ ha.le_of_lt hb.lt lemma covby.unique_right (hb : a ⋖ b) (hc : a ⋖ c) : b = c := (hb.ge_of_gt hc.lt).antisymm $ hc.ge_of_gt hb.lt /-- If `a`, `b`, `c` are consecutive and `a < x < c` then `x = b`. -/ lemma covby.eq_of_between {x : α} (hab : a ⋖ b) (hbc : b ⋖ c) (hax : a < x) (hxc : x < c) : x = b := le_antisymm (le_of_not_lt $ λ h, hbc.2 h hxc) (le_of_not_lt $ hab.2 hax) end linear_order namespace set lemma wcovby_insert (x : α) (s : set α) : s ⩿ insert x s := begin refine wcovby_of_eq_or_eq (subset_insert x s) (λ t hst h2t, _), by_cases h : x ∈ t, { exact or.inr (subset_antisymm h2t $ insert_subset.mpr ⟨h, hst⟩) }, { refine or.inl (subset_antisymm _ hst), rwa [← diff_singleton_eq_self h, diff_singleton_subset_iff] } end lemma covby_insert {x : α} {s : set α} (hx : x ∉ s) : s ⋖ insert x s := (wcovby_insert x s).covby_of_lt $ ssubset_insert hx end set namespace prod variables [partial_order α] [partial_order β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} @[simp] lemma swap_wcovby_swap : x.swap ⩿ y.swap ↔ x ⩿ y := apply_wcovby_apply_iff (order_iso.prod_comm : α × β ≃o β × α) @[simp] lemma swap_covby_swap : x.swap ⋖ y.swap ↔ x ⋖ y := apply_covby_apply_iff (order_iso.prod_comm : α × β ≃o β × α) lemma fst_eq_or_snd_eq_of_wcovby : x ⩿ y → x.1 = y.1 ∨ x.2 = y.2 := begin refine λ h, of_not_not (λ hab, _), push_neg at hab, exact h.2 (mk_lt_mk.2 $ or.inl ⟨hab.1.lt_of_le h.1.1, le_rfl⟩) (mk_lt_mk.2 $ or.inr ⟨le_rfl, hab.2.lt_of_le h.1.2⟩), end lemma _root_.wcovby.fst (h : x ⩿ y) : x.1 ⩿ y.1 := ⟨h.1.1, λ c h₁ h₂, h.2 (mk_lt_mk_iff_left.2 h₁) ⟨⟨h₂.le, h.1.2⟩, λ hc, h₂.not_le hc.1⟩⟩ lemma _root_.wcovby.snd (h : x ⩿ y) : x.2 ⩿ y.2 := ⟨h.1.2, λ c h₁ h₂, h.2 (mk_lt_mk_iff_right.2 h₁) ⟨⟨h.1.1, h₂.le⟩, λ hc, h₂.not_le hc.2⟩⟩ lemma mk_wcovby_mk_iff_left : (a₁, b) ⩿ (a₂, b) ↔ a₁ ⩿ a₂ := begin refine ⟨wcovby.fst, and.imp mk_le_mk_iff_left.2 $ λ h c h₁ h₂, _⟩, have : c.2 = b:= h₂.le.2.antisymm h₁.le.2, rw [←@prod.mk.eta _ _ c, this, mk_lt_mk_iff_left] at h₁ h₂, exact h h₁ h₂, end lemma mk_wcovby_mk_iff_right : (a, b₁) ⩿ (a, b₂) ↔ b₁ ⩿ b₂ := swap_wcovby_swap.trans mk_wcovby_mk_iff_left lemma mk_covby_mk_iff_left : (a₁, b) ⋖ (a₂, b) ↔ a₁ ⋖ a₂ := by simp_rw [covby_iff_wcovby_and_lt, mk_wcovby_mk_iff_left, mk_lt_mk_iff_left] lemma mk_covby_mk_iff_right : (a, b₁) ⋖ (a, b₂) ↔ b₁ ⋖ b₂ := by simp_rw [covby_iff_wcovby_and_lt, mk_wcovby_mk_iff_right, mk_lt_mk_iff_right] lemma mk_wcovby_mk_iff : (a₁, b₁) ⩿ (a₂, b₂) ↔ a₁ ⩿ a₂ ∧ b₁ = b₂ ∨ b₁ ⩿ b₂ ∧ a₁ = a₂ := begin refine ⟨λ h, _, _⟩, { obtain rfl | rfl : a₁ = a₂ ∨ b₁ = b₂ := fst_eq_or_snd_eq_of_wcovby h, { exact or.inr ⟨mk_wcovby_mk_iff_right.1 h, rfl⟩ }, { exact or.inl ⟨mk_wcovby_mk_iff_left.1 h, rfl⟩ } }, { rintro (⟨h, rfl⟩ | ⟨h, rfl⟩), { exact mk_wcovby_mk_iff_left.2 h }, { exact mk_wcovby_mk_iff_right.2 h } } end lemma mk_covby_mk_iff : (a₁, b₁) ⋖ (a₂, b₂) ↔ a₁ ⋖ a₂ ∧ b₁ = b₂ ∨ b₁ ⋖ b₂ ∧ a₁ = a₂ := begin refine ⟨λ h, _, _⟩, { obtain rfl | rfl : a₁ = a₂ ∨ b₁ = b₂ := fst_eq_or_snd_eq_of_wcovby h.wcovby, { exact or.inr ⟨mk_covby_mk_iff_right.1 h, rfl⟩ }, { exact or.inl ⟨mk_covby_mk_iff_left.1 h, rfl⟩ } }, { rintro (⟨h, rfl⟩ | ⟨h, rfl⟩), { exact mk_covby_mk_iff_left.2 h }, { exact mk_covby_mk_iff_right.2 h } } end lemma wcovby_iff : x ⩿ y ↔ x.1 ⩿ y.1 ∧ x.2 = y.2 ∨ x.2 ⩿ y.2 ∧ x.1 = y.1 := by { cases x, cases y, exact mk_wcovby_mk_iff } lemma covby_iff : x ⋖ y ↔ x.1 ⋖ y.1 ∧ x.2 = y.2 ∨ x.2 ⋖ y.2 ∧ x.1 = y.1 := by { cases x, cases y, exact mk_covby_mk_iff } end prod
57dd93bc5ce7b3d175b485a310501e0411eb4ec6
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/unification_hints.lean
bbf15fb89450d955c5484a77ff74cf07b65e42ff
[ "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
792
lean
open list nat namespace toy constants (A : Type.{1}) (f h : A → A) (x y z : A) attribute [irreducible] noncomputable definition g (x y : A) : A := f z @[unify] noncomputable definition toy_hint (x y : A) : unification_hint := { pattern := g x y ≟ f z, constraints := [] } open tactic set_option trace.type_context.unification_hint true definition ex1 (a : A) (H : g x y = a) : f z = a := by do {trace_state, assumption} #print ex1 end toy namespace add constants (n : ℕ) @[unify] definition add_zero_hint (m n : ℕ) [has_add ℕ] [has_one ℕ] [has_zero ℕ] : unification_hint := { pattern := m + 1 ≟ succ n, constraints := [m ≟ n] } attribute [irreducible] add open tactic definition ex2 (H : n + 1 = 0) : succ n = 0 := by assumption #print ex2 end add
e83261693609634c73db9fbf949bc6329bd3955e
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/check_constants.lean
6c679a8ead2728e47206118704a7d776ad532cde
[ "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
14,772
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `abs run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `add_comm_group run_cmd script_check_id `add_comm_semigroup run_cmd script_check_id `add_group run_cmd script_check_id `add_monoid run_cmd script_check_id `and run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `and.cases_on run_cmd script_check_id `auto_param run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `combinator.K run_cmd script_check_id `caching_user_attribute run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `classical.prop_decidable run_cmd script_check_id `classical.type_decidable_eq run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `distrib run_cmd script_check_id `dite run_cmd script_check_id `id run_cmd script_check_id `empty run_cmd script_check_id `Exists run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_true_intro run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `format run_cmd script_check_id `false run_cmd script_check_id `false_of_true_iff_false run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `false.rec run_cmd script_check_id `field run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `funext run_cmd script_check_id `ge run_cmd script_check_id `gt run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `has_andthen.andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.bind run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_div run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_mod.mod run_cmd script_check_id `has_mul run_cmd script_check_id `has_mul.mul run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_inv run_cmd script_check_id `has_inv.inv run_cmd script_check_id `has_le run_cmd script_check_id `has_le.le run_cmd script_check_id `has_lt run_cmd script_check_id `has_lt.lt run_cmd script_check_id `has_neg run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_to_string run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `has_coe_t run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `id_locked run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.has_add run_cmd script_check_id `int.has_mul run_cmd script_check_id `int.has_sub run_cmd script_check_id `int.has_div run_cmd script_check_id `int.has_le run_cmd script_check_id `int.has_lt run_cmd script_check_id `int.has_neg run_cmd script_check_id `int.has_mod run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `int.decidable_linear_ordered_comm_group run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io run_cmd script_check_id `io.interface run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `ite run_cmd script_check_id `left_distrib run_cmd script_check_id `left_comm run_cmd script_check_id `le_refl run_cmd script_check_id `linear_ordered_ring run_cmd script_check_id `linear_ordered_semiring run_cmd script_check_id `list run_cmd script_check_id `list.nil run_cmd script_check_id `list.cons run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monoid run_cmd script_check_id `mul_one run_cmd script_check_id `mul_zero run_cmd script_check_id `mul_zero_class run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.of_num run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.add run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `norm_num.add1 run_cmd script_check_id `norm_num.add1_bit0 run_cmd script_check_id `norm_num.add1_bit1_helper run_cmd script_check_id `norm_num.add1_one run_cmd script_check_id `norm_num.add1_zero run_cmd script_check_id `norm_num.add_div_helper run_cmd script_check_id `norm_num.bin_add_zero run_cmd script_check_id `norm_num.bin_zero_add run_cmd script_check_id `norm_num.bit0_add_bit0_helper run_cmd script_check_id `norm_num.bit0_add_bit1_helper run_cmd script_check_id `norm_num.bit0_add_one run_cmd script_check_id `norm_num.bit1_add_bit0_helper run_cmd script_check_id `norm_num.bit1_add_bit1_helper run_cmd script_check_id `norm_num.bit1_add_one_helper run_cmd script_check_id `norm_num.div_add_helper run_cmd script_check_id `norm_num.div_eq_div_helper run_cmd script_check_id `norm_num.div_helper run_cmd script_check_id `norm_num.div_mul_helper run_cmd script_check_id `norm_num.mk_cong run_cmd script_check_id `norm_num.mul_bit0_helper run_cmd script_check_id `norm_num.mul_bit1_helper run_cmd script_check_id `norm_num.mul_div_helper run_cmd script_check_id `norm_num.neg_add_neg_helper run_cmd script_check_id `norm_num.neg_add_pos_helper1 run_cmd script_check_id `norm_num.neg_add_pos_helper2 run_cmd script_check_id `norm_num.neg_mul_neg_helper run_cmd script_check_id `norm_num.neg_mul_pos_helper run_cmd script_check_id `norm_num.neg_neg_helper run_cmd script_check_id `norm_num.neg_zero_helper run_cmd script_check_id `norm_num.nonneg_bit0_helper run_cmd script_check_id `norm_num.nonneg_bit1_helper run_cmd script_check_id `norm_num.nonzero_of_div_helper run_cmd script_check_id `norm_num.nonzero_of_neg_helper run_cmd script_check_id `norm_num.nonzero_of_pos_helper run_cmd script_check_id `norm_num.one_add_bit0 run_cmd script_check_id `norm_num.one_add_bit1_helper run_cmd script_check_id `norm_num.one_add_one run_cmd script_check_id `norm_num.pos_add_neg_helper run_cmd script_check_id `norm_num.pos_bit0_helper run_cmd script_check_id `norm_num.pos_bit1_helper run_cmd script_check_id `norm_num.pos_mul_neg_helper run_cmd script_check_id `norm_num.sub_nat_zero_helper run_cmd script_check_id `norm_num.sub_nat_pos_helper run_cmd script_check_id `norm_num.subst_into_div run_cmd script_check_id `norm_num.subst_into_prod run_cmd script_check_id `norm_num.subst_into_subtr run_cmd script_check_id `norm_num.subst_into_sum run_cmd script_check_id `not run_cmd script_check_id `not_of_iff_false run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `num run_cmd script_check_id `num.pos run_cmd script_check_id `num.zero run_cmd script_check_id `of_eq_true run_cmd script_check_id `of_iff_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `inout_param run_cmd script_check_id `punit run_cmd script_check_id `punit.star run_cmd script_check_id `pos_num.bit0 run_cmd script_check_id `pos_num.bit1 run_cmd script_check_id `pos_num.one run_cmd script_check_id `prod.mk run_cmd script_check_id `pprod run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.snd run_cmd script_check_id `propext run_cmd script_check_id `to_pexpr run_cmd script_check_id `quot.mk run_cmd script_check_id `quot.lift run_cmd script_check_id `real run_cmd script_check_id `real.of_int run_cmd script_check_id `real.to_int run_cmd script_check_id `real.is_int run_cmd script_check_id `real.has_neg run_cmd script_check_id `real.has_div run_cmd script_check_id `real.has_add run_cmd script_check_id `real.has_mul run_cmd script_check_id `real.has_sub run_cmd script_check_id `real.has_lt run_cmd script_check_id `real.has_le run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `rfl run_cmd script_check_id `right_distrib run_cmd script_check_id `ring run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `semiring run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.snd run_cmd script_check_id `singleton run_cmd script_check_id `sizeof run_cmd script_check_id `smt.array run_cmd script_check_id `smt.select run_cmd script_check_id `smt.store run_cmd script_check_id `smt.prove run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.str run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.val run_cmd script_check_id `subtype.rec run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `tactic run_cmd script_check_id `tactic.try run_cmd script_check_id `tactic.triv run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `to_string run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.cases_on run_cmd script_check_id `unit.star run_cmd script_check_id `unsafe_monad_from_pure_bind run_cmd script_check_id `user_attribute run_cmd script_check_id `vm_monitor run_cmd script_check_id `weak_order run_cmd script_check_id `well_founded run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `xor run_cmd script_check_id `zero_le_one run_cmd script_check_id `zero_lt_one run_cmd script_check_id `zero_mul
41d69664a34fc0212c39135d956e6c2a7c094b09
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/monotonicity/interactive.lean
c7ddbbbed9bb205282644cb1e5c994894d0e764e
[ "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
23,573
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.traversable.derive import control.traversable.lemmas import data.dlist import tactic.monotonicity.basic variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function | assoc_comm : expr elab → expr elab → mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function → tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }}" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr → expr → expr → tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr → tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr → tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr → list expr → tactic (list expr × list expr × list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr → list expr → tactic (list expr × list expr × list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr × list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse l₂,reverse r₂,reverse suf) meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr → option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr → list expr → expr → expr → tactic (expr × list expr × list expr) | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) := same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁ | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁) meta def same_function : expr → expr → tactic (expr × list expr × list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr × expr × list expr × mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ ¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- ¬ a (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs, return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx) | `(%%e₀ → %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%e₀ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel e₀) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr → expr → expr | none e := e | (some e₀) e₁ := f.mk_app [e₀,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr → option expr → expr | e none := e | e₀ (some e₁) := f.mk_app [e₀,e₁] meta def mk_fun_app : mono_function → expr → expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove x+(y₀+z) R x+(y₁+z); if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/ | assoc : expr × expr → expr × expr → mono_law /- `congr r` gives the rule to prove `x = y → f x = f y` -/ | congr : expr → mono_law | other : expr → mono_law meta def mono_law.to_tactic_format : mono_law → tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := do x₀ ← pp x₀, x₁ ← pp x₁, y₀ ← pp y₀, y₁ ← pp y₁, return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f x₀ x₁) := if (x₀ <|> x₁).is_some then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (λ i, bin_op f x (bin_op f i y)) , mk_rel ctx (λ i, bin_op f i y)) ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y) , mk_rel ctx (λ i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [ simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)], match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name → tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ → %%x₀), r₀ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> r₀ <*> r₁) meta def find_rule (ls : list name) : mono_law → tactic (list expr) | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := (match_chaining_rules ls x₀ x₁) <|> (match_chaining_rules ls y₀ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (λ v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ λ _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α | [] := [] | (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit := do t ← target, xs ← xs.mmap (λ x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (λ ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" $ list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg), let msg := foldl compose "" lmms, fail format!("ambiguous match: {msg}\n\n" ++ "Tip: try asserting a side condition to distinguish between the lemmas") end meta def mono_aux (dir : parse side) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≤ w` and `y < z` or - right: `x < w` and `y ≤ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?` To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊢ k + 3 + x ≤ k + 4 + x mono, -- apply add_le_add, refl -- ⊢ k + 3 ≤ k + 4 mono }, { -- ⊢ -y ≤ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) : tactic unit := do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var), hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr), when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip), if many.is_some then repeat $ mono_aux dir else mono_aux dir, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ λ asms, do try `[simp only [sub_eq_add_neg]], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (λ rule, do t₀ ← mk_meta_var `(Prop), v₀ ← mk_meta_var t₀, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁), solve_mvar v₀ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit → tactic unit → tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : ℕ) | many meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly' n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := rep_arity.many <$ tk "*" <|> rep_arity.exactly <$> (tk "^" *> small_nat) <|> pure rep_arity.one /-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a monotonic function `f` to `x ≺ y`. `ac_mono*` unwraps monotonic functions until it can't. `ac_mono^k`, for some literal number `k` applies monotonicity `k` times. `ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and uses `h` to solve the remaining goal. Can be combined with `*` or `^k`: `ac_mono* := h` `ac_mono : p` asserts `p` and uses it to discharge the goal result unwrapping a series of monotonic functions. Can be combined with * or ^k: `ac_mono* : p` In the case where `f` is an associative or commutative operator, `ac_mono` will consider any possible permutation of its arguments and use the one the minimizes the difference between the left-hand side and the right-hand side. To use it, first import `tactic.monotonicity`. `ac_mono` can be used as follows: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end ``` As with `mono*`, `ac_mono*` solves the goal in one go and so does `ac_mono* := h₁`. The latter syntax becomes especially interesting in the following example: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by ac_mono* := h₁. ``` By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to stop earlier than it would normally would. -/ meta def ac_mono (rep : parse arity) : parse assert_or_rule? → opt_param mono_cfg { mono_cfg . } → tactic unit | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none | (some (inl h)) opt := do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine) | (some (inr t)) opt := do h ← i_to_expr t >>= assert `h, tactic.swap, focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h) /- TODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining gaol if the provided rule does not solve it completely. -/ add_tactic_doc { name := "ac_mono", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_mono], tags := ["monotonicity"] } attribute [mono] and.imp or.imp end tactic.interactive
fc109d3f03980f81e34cb3cc46463f2246c0d4a9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/multiset/powerset.lean
7c486c46bd5a550a9acdcea478f92dffbfbea3c9
[ "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
9,263
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.basic /-! # The powerset of a multiset -/ namespace multiset open list variables {α : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _ @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm /-- The power set of a multiset. -/ def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = {0} := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map singleton ≤ powerset s := quotient.induction_on s $ λ l, begin simp only [powerset_coe, quot_mk_to_coe, coe_le, coe_map], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_tsub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = {0} := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a ::ₘ s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm end multiset
55f3273aa9824fb255a583fb01175f9b5e9c7624
a7602958ab456501ff85db8cf5553f7bcab201d7
/Assignment1/homework.lean
098e344590fe306e8cda001754241650f34ee2b1
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,201
lean
-- Assignment 1 -- Dom Farolino, farolidm@mail.uc.edu -- Math Logic variables A B C: Prop -- Exercise 1 section example: ¬ (A ∧ B) → (A → ¬ B) := assume h1: ¬ (A ∧ B), assume ha: A, assume hb: B, have hab: (A ∧ B), from and.intro ha hb, show false, from h1 hab end -- Exercise 2 section example: (A → C) ∧ (B → ¬ C) → ¬ (A ∧ B) := assume h1: (A → C) ∧ (B → ¬ C), assume h2: (A ∧ B), have hc: C, from (and.left h1) (and.left h2), have hnc: ¬ C, from (and.right h1) (and.right h2), show false, from hnc hc end -- Could also write E2 as this: section example: (A → C) ∧ (B → ¬ C) → ¬ (A ∧ B) := assume h1: (A → C) ∧ (B → ¬ C), assume h2: (A ∧ B), show false, from (show ¬ C, from -- The show is not actually required here (and.right h1) (and.right h2)) (show C, from -- ^ see above comment (and.left h1) (and.left h2)) end -- Exercise 3 section example: (A ∧ B) → ((A → C) → ¬ (B → ¬ C)) := assume h1: (A ∧ B), assume h2: (A → C), assume h3: (B → ¬ C), have hc: C, from h2 (and.left h1), have hnc: ¬ C, from h3 (and.right h1), show false, from hnc hc end
aba9a5e38efbd06898e159719f3db3bdae9ed347
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/analysis/convex/integral.lean
41844302c5bc14f02aa8c5b638a854606bd27a67
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,714
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.convex.basic import measure_theory.integral.set_integral /-! # Jensen's inequality for integrals In this file we prove four theorems: * `convex.smul_integral_mem`: if `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. * `convex.integral_mem`: if `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. * `convex_on.map_smul_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_center_mass_le` for a finite sum version of this lemma. * `convex_on.map_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_sum_le` for a finite sum version of this lemma. ## Tags convex, integral, center mass, Jensen's inequality -/ open measure_theory set filter open_locale topological_space big_operators variables {α E : Type*} [measurable_space α] {μ : measure α} [normed_group E] [normed_space ℝ E] [complete_space E] [topological_space.second_countable_topology E] [measurable_space E] [borel_space E] private lemma convex.smul_integral_mem_of_measurable [finite_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hfm : measurable f) : (μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|⟨y₀, h₀⟩ }, { refine (hμ _).elim, simpa using hfs }, rw ← hsc.closure_eq at hfs, have hc : integrable (λ _, y₀) μ := integrable_const _, set F : ℕ → simple_func α E := simple_func.approx_on f hfm s y₀ h₀, have : tendsto (λ n, (F n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ), { simp only [simple_func.integral_eq_integral _ (simple_func.integrable_approx_on hfm hfi h₀ hc _)], exact tendsto_integral_of_L1 _ hfi (eventually_of_forall $ simple_func.integrable_approx_on hfm hfi h₀ hc) (simple_func.tendsto_approx_on_L1_nnnorm hfm h₀ hfs (hfi.sub hc).2) }, refine hsc.mem_of_tendsto (tendsto_const_nhds.smul this) (eventually_of_forall $ λ n, _), have : ∑ y in (F n).range, (μ ((F n) ⁻¹' {y})).to_real = (μ univ).to_real, by rw [← (F n).sum_range_measure_preimage_singleton, @ennreal.to_real_sum _ _ (λ y, μ ((F n) ⁻¹' {y})) (λ _ _, (measure_lt_top _ _))], rw [← this, simple_func.integral], refine hs.center_mass_mem (λ _ _, ennreal.to_real_nonneg) _ _, { rw [this, ennreal.to_real_pos_iff, pos_iff_ne_zero, ne.def, measure.measure_univ_eq_zero], exact ⟨hμ, measure_ne_top _ _⟩ }, { simp only [simple_func.mem_range], rintros _ ⟨x, rfl⟩, exact simple_func.approx_on_mem hfm h₀ n x } end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.smul_integral_mem [finite_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : (μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s := begin have : ∀ᵐ (x : α) ∂μ, hfi.ae_measurable.mk f x ∈ s, { filter_upwards [hfs, hfi.ae_measurable.ae_eq_mk], assume a ha h, rwa ← h }, convert convex.smul_integral_mem_of_measurable hs hsc hμ this (hfi.congr hfi.ae_measurable.ae_eq_mk) (hfi.ae_measurable.measurable_mk) using 2, apply integral_congr_ae, exact hfi.ae_measurable.ae_eq_mk end /-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/ lemma convex.integral_mem [probability_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s) {f : α → E} (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ∫ x, f x ∂μ ∈ s := by simpa [measure_univ] using hs.smul_integral_mem hsc (probability_measure.ne_zero μ) hf hfi /-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_smul_integral_le [finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g ((μ univ).to_real⁻¹ • ∫ x, f x ∂μ) ≤ (μ univ).to_real⁻¹ • ∫ x, g (f x) ∂μ := begin set t := {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2}, have ht_conv : convex t := hg.convex_epigraph, have ht_closed : is_closed t := (hsc.preimage continuous_fst).is_closed_le (hgc.comp continuous_on_fst (subset.refl _)) continuous_on_snd, have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ t := hfs.mono (λ x hx, ⟨hx, le_rfl⟩), simpa [integral_pair hfi hgi] using (ht_conv.smul_integral_mem ht_closed hμ ht_mem (hfi.prod_mk hgi)).2 end /-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_sum_le` for a finite sum version of this lemma. -/ lemma convex_on.map_integral_le [probability_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ := by simpa [measure_univ] using hg.map_smul_integral_le hgc hsc (probability_measure.ne_zero μ) hfs hfi hgi
55c7ee444deba97f3b2c13ce1594989af0c1d959
8c95816d6379a6864848d68ce735a5700c1cbbc3
/src/smt2/default.lean
7d6095b53880b6fa19f88e99c6b59717d153d790
[ "Apache-2.0" ]
permissive
aqjune/smt2_interface
f00ed0a4317d7c9112deb0806c8e89e6512a901e
598848a7a6fa47520fadcfe1b16891053a296084
refs/heads/master
1,631,518,664,718
1,524,489,340,000
1,524,489,340,000
115,204,811
0
0
null
1,514,043,428,000
1,514,043,427,000
null
UTF-8
Lean
false
false
12,869
lean
import system.io import .solvers.z3 import .syntax import .builder import .tactic import .attributes import .lol import init.data.option.basic declare_trace smt2 open tactic open smt2.builder open native meta structure smt2_state : Type := (ctxt : lol.context) (type_map : rb_map expr lol.type) meta def smt2_state.initial : smt2_state := ⟨ lol.context.empty, rb_map.mk _ _ ⟩ @[reducible] meta def smt2_m (α : Type) := state_t smt2_state tactic α meta instance tactic_to_smt2_m (α : Type) : has_coe (tactic α) (smt2_m α) := ⟨ fun tc, state_t.mk (fun s, do res ← tc, return (res, s)) ⟩ namespace smt2 meta def trace_smt2 (msg : string) : smt2_m unit := tactic.when_tracing `smt2 (tactic.trace msg) meta def fail {α : Type} (msg : string) : smt2_m α := tactic.fail $ "smt2_tactic: " ++ msg meta def mangle_name (n : name) : string := "lean_" ++ n^.to_string_with_sep "-" meta def insert_type (n : string) (ty : expr) (lty : lol.type) : smt2_m unit := do st ← get, smt2.builder.put ⟨ st.ctxt.declare_type n lty, st.type_map.insert ty lty ⟩ meta def fn_type : expr → (list expr × expr) | (expr.pi _ _ ty rest) := let (args, rt) := fn_type rest in (ty :: args, rt) | rt := ([], rt) -- Currently we only support first order fn types meta def compile_arrow_type (ty : expr) (cb : expr → smt2_m lol.type) : smt2_m lol.type := let (args, rt) := fn_type ty in lol.type.fn <$> monad.mapm cb args <*> cb rt meta def compile_type : expr → smt2_m lol.type := fun ty, do st ← get, match st.type_map.find ty with | some lty := return lty | none := do lty ← match ty with | `(int) := pure $ lol.type.int | `(nat) := pure $ lol.type.refinement lol.type.int (fun x, lol.term.lte (lol.term.int 0) (lol.term.var x)) | `(Prop) := pure $ lol.type.bool | _ := if ty.is_arrow then compile_arrow_type ty compile_type else if ty.is_constant then do insert_type (mangle_name ty.const_name) ty (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)), return $ (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)) else fail $ "unsupported type: " ++ to_string ty end, -- insert_type ty lty, return lty end meta def add_decl (n : name) (ty : expr) : smt2_m unit := do st ← get, ct ← compile_type ty, let d := lol.decl.fn (mangle_name n) ct none, smt2.builder.put { st with ctxt := st.ctxt.declare d } -- meta def ensure_constant (e : expr) (n : name) : smt2_m lol.decl := -- do ty ← infer_type e, -- let (arg_tys, ret_ty) := fn_type ty, -- let mangled_name := mangle_name n, -- arg_sorts ← monad.mapm compile_type arg_tys, -- ret_sort ← compile_type ret_ty, -- -- ensure_constant_core e (return $ (mangled_name, arg_sorts, ret_sort)), -- return $ lol.decl.fn mangled_name arg_sorts ret_sort -- meta def formula_type_from_arrow (n : name) (e : expr) : smt2_m formula_type := -- do (lol.decl.fn _ arg_sorts ret_sort) ← ensure_constant e n, -- return $ formula_type.fn n arg_sorts ret_sort -- /-- The goal of this function is to categorize the set of formulas in the hypotheses, -- and goal. We want to narrow down from the full term language of Lean to a fragment -- of formula's we suppose. The below code makes some assumptions: -- A local constant of the form `(P : Prop)`, must be reflected as declaration -- in SMT2 that is `(declare-const P Bool)`. -- An occurence of a proof of `P`, `(p : P)`, must be transformed into -- `(assert P)`. If P is a formula, not an atom, we must transform P into a corresponding -- SMT2 formula and `(assert P)`. -- -/ meta def extract_coe_args (args : list expr) : smt2_m (expr × expr × expr) := match args with | (source :: target :: inst :: e :: []) := return (source, target, e) | _ := fail "internal tactic error expected `coe` to have exactly 4 arguments" end meta def reflect_coercion (source target e : expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term := if source = `(nat) ∧ target = `(int) then callback e else fail $ "unsupported coercion between " ++ "`" ++ to_string source ++ "` and `" ++ to_string target ++ "`" meta def reflect_application (fn : expr) (args : list expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term := if fn.is_constant then if fn.const_name = `coe then do (source, target, e) ← extract_coe_args args, reflect_coercion source target e callback else do ty ← infer_type fn, let mangled := (mangle_name fn.const_name), add_decl fn.const_name ty, lol.term.apply mangled <$> monad.mapm callback args else if fn.is_local_constant then lol.term.apply (mangle_name fn.local_uniq_name) <$> monad.mapm callback args else fail $ "unsupported head symbol `" ++ to_string fn ++ "`" -- meta def is_supported_head_symbol (e : expr) : bool := true meta def is_supported_numeric_ty (ty : expr) : bool := (ty = `(int) ∨ ty = `(nat)) -- /-- This function is the meat of the tactic, it takes a propositional formula in Lean, and transforms -- it into a corresponding term in SMT2. -/ meta def reflect_arith_formula (reflect_base : expr → smt2_m lol.term) : expr → smt2_m lol.term | `(%%a + %%b) := lol.term.add <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a - %%b) := lol.term.sub <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a * %%b) := lol.term.mul <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a / %%b) := lol.term.div <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a % %%b) := lol.term.mod <$> reflect_arith_formula a <*> reflect_arith_formula b | `(- %%a) := lol.term.neg <$> reflect_arith_formula a -- /- Constants -/ | `(has_zero.zero _) := lol.term.int <$> eval_expr int `(has_zero.zero int) | `(has_one.one _) := lol.term.int <$> eval_expr int `(has_one.one int) | `(bit0 %%Bits) := do ty ← infer_type Bits, if is_supported_numeric_ty ty then lol.term.int <$> eval_expr int `(bit0 %%Bits : int) else if (ty = `(nat)) then lol.term.int <$> int.of_nat <$> eval_expr nat `(bit0 %%Bits : nat) else fail $ "unknown numeric literal: " ++ (to_string ```(bit0 %%Bits : int)) | `(bit1 %%Bits) := do ty ← infer_type Bits, if is_supported_numeric_ty ty then lol.term.int <$> eval_expr int `(bit1 %%Bits : int) else if (ty = `(nat)) then lol.term.int <$> (int.of_nat <$> eval_expr nat `(bit1 %%Bits : nat)) else fail $ "unknown numeric literal: " ++ (to_string `(bit1 %%Bits : int)) | a := if a.is_local_constant then return $ lol.term.var (mangle_name a.local_uniq_name) else if a.is_constant then return $ lol.term.var (mangle_name a.const_name) else if a.is_app then reflect_application (a.get_app_fn) (a.get_app_args) reflect_base else fail $ "unsupported arithmetic formula: " ++ to_string a -- /-- Check if the type is an `int` or logically a subtype of an `int` like nat. -/ meta def is_int (e : expr) : tactic bool := do ty ← infer_type e, return $ (ty = `(int)) || (ty = `(nat)) meta def unsupported_ordering_on {α : Type} (elem : expr) : tactic α := do ty ← infer_type elem, tactic.fail $ "unable to translate orderings for values of type: " ++ to_string ty meta def reflect_ordering (reflect_arith : expr → smt2_m lol.term) (R : lol.term → lol.term → lol.term) (P Q : expr) : smt2_m lol.term := do is ← is_int P, -- NB: P and Q should have the same type. if is then R <$> (reflect_arith P) <*> (reflect_arith Q) else unsupported_ordering_on P meta def supported_pi_binder (ty : expr) : bool := match ty with | `(int) := tt | `(nat) := tt | `(Prop) := tt | _ := if ty.is_constant then tt else ff end meta def add_assertion (t : lol.term) : smt2_m unit := do st ← get, smt2.builder.put { st with ctxt := st.ctxt.assert t } meta def compile_pi (e : expr) (cb : expr → smt2_m lol.term) : smt2_m lol.term := if supported_pi_binder e.binding_domain then do loc ← tactic.mk_local' e.binding_name e.binding_info e.binding_domain, lol.term.forallq (mangle_name $ loc.local_uniq_name) <$> (compile_type $ e.binding_domain) <*> (cb (expr.instantiate_var (e.binding_body) loc)) else fail $ "arbitrary Π types are not supported, unable to translate term: `" ++ to_string e ++ "`" meta def reflect_prop_formula' : expr → smt2_m lol.term | `(¬ %%P) := lol.term.not <$> (reflect_prop_formula' P) | `(%%P = %% Q) := lol.term.equals <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ∧ %%Q) := lol.term.and <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ∨ %%Q) := lol.term.or <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ↔ %%Q) := lol.term.iff <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P < %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lt P Q | `(%%P <= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lte P Q | `(%%P > %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gt P Q | `(%%P >= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gte P Q | `(true) := return $ lol.term.true | `(false) := return $ lol.term.false | e := do ty ← infer_type e, if e.is_local_constant then pure $ lol.term.var (mangle_name e.local_uniq_name) else if e.is_arrow then lol.term.implies <$> (reflect_prop_formula' e.binding_domain) <*> (reflect_prop_formula' e.binding_body ) else if e.is_pi then compile_pi e reflect_prop_formula' else if is_supported_numeric_ty ty then reflect_arith_formula reflect_prop_formula' e else if e.is_app then reflect_application (e.get_app_fn) (e.get_app_args) reflect_prop_formula' else tactic.fail $ "unsupported propositional formula : " ++ to_string e meta def reflect_prop_formula (e : expr) : smt2_m unit := reflect_prop_formula' e >>= add_assertion -- meta def warn_unable_to_trans_local (e : expr) : smt2_m (builder unit) := do -- trace_smt2 $ "unable to translate local variable: " ++ to_string e, -- return $ return () meta def is_builtin_type : expr → bool | `(int) := tt | `(Prop) := tt | `(nat) := tt | _ := ff meta def unsupported_formula (e : expr) : smt2_m unit := fail $ "unsupported formula: " ++ to_string e meta def compile_local (e : expr) : smt2_m unit := do ty ← infer_type e, prop_sorted ← is_prop ty, if e.is_local_constant then if is_builtin_type ty then add_decl e.local_uniq_name ty else if ty.is_arrow then add_decl e.local_uniq_name ty else if prop_sorted then reflect_prop_formula ty else unsupported_formula ty else if e.is_constant then if is_builtin_type ty ∨ ty.is_arrow then add_decl e.const_name ty else if prop_sorted then reflect_prop_formula ty else unsupported_formula ty else if (ty = `(Prop)) then reflect_prop_formula e else unsupported_formula e meta def reflect_attr_decl (n : name) : smt2_m unit := do exp ← mk_const n, compile_local exp /- Reflect the environment consisting of declarations with the `smt2` attribute. -/ meta def reflect_environment : smt2_m unit := do decls ← attribute.get_instances `smt2, bs ← monad.mapm reflect_attr_decl decls.reverse, return () meta def reflect_context : smt2_m unit := do ls ← local_context, bs ← monad.mapm (fun e, compile_local e) ls, return () meta def reflect_goal : smt2_m unit := do tgt ← target, -- SMT solvers are looking for satisfiabiltiy, so we must negate to check validity. reflect_prop_formula `(_root_.not %%tgt), return () meta def reflect : smt2_m (builder unit) := do reflect_environment, reflect_context, reflect_goal, st ← get, return $ (lol.to_builder (lol.smt2_compiler_state.mk (rb_map.mk _ _) st.ctxt []) lol.compile >> check_sat) end smt2 universe u @[smt2] lemma int_of_nat_is_pos : forall (n : nat), 0 <= int.of_nat n := begin intros, trivial end axiom proof_by_z3 (A : Sort u) : A meta def z3 (log_file : option string := none) : tactic unit := do (builder, _) ← smt2.reflect.run smt2_state.initial, resp ← unsafe_run_io (smt2 builder log_file), match resp with | smt2.response.sat := fail "z3 was unable to prove the goal" | smt2.response.unknown := fail "z3 was unable to prove the goal" | smt2.response.other str := fail $ "z3 communication error, unexpected response:\n\n" ++ str ++ "\n" | smt2.response.unsat := do tgt ← target, sry ← to_expr $ ``(proof_by_z3 %%tgt), exact sry end
721b201cc591366fb4d80dbee1f290ab1165a151
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/ring_theory/polynomial/basic.lean
cd39846b9169bcaece5436593b7023c7e0f22c70
[ "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
38,898
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.basic import data.mv_polynomial.comm_ring import data.mv_polynomial.equiv import data.polynomial.field_division import ring_theory.principal_ideal_domain import ring_theory.polynomial.content /-! # Ring-theoretic supplement of data.polynomial. ## Main results * `mv_polynomial.integral_domain`: If a ring is an integral domain, then so is its polynomial ring over finitely many variables. * `polynomial.is_noetherian_ring`: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. * `polynomial.wf_dvd_monoid`: If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring. * `polynomial.unique_factorization_monoid`: If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring. -/ noncomputable theory open_locale classical big_operators universes u v w namespace polynomial instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩ variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, exact (degree_X_pow_le _).trans (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/ def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) := { to_fun := λ p n, (↑p : polynomial F).coeff n, inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i), (degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt (degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩, map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl }, map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl }, left_inv := begin rintro ⟨p, hp⟩, ext1, simp only [submodule.coe_mk], by_cases hp0 : p = 0, { subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] }, rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp, conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] }, end, right_inv := begin intro f, ext i, simp only [finset_sum_coeff, submodule.coe_mk], rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl], { rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] }, { intro h, exact (h (finset.mem_univ _)).elim } end } local attribute [instance] subset.ring /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl section local attribute [instance] algebra.of_is_subring subring.domain subset.comm_ring @[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p := ext $ λ n, by rw [coeff_map, algebra.is_subring_algebra_map_apply, coeff_restriction] end @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction := by { dsimp only [eval₂_eq_sum], refl, } section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl @[simp] theorem map_to_subring : (p.to_subring T hp).map (is_subring.subtype T) = p := ext $ λ n, coeff_map _ _ end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M] namespace ideal open polynomial /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/ lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R) (hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I := sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n)) /-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : polynomial R} : f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw ← sum_monomial_eq f, refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _), simp [single_eq_C_mul_X], rw mul_comm, exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem (hf n)) } end lemma quotient_map_C_eq_zero {I : ideal R} : ∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 := begin intros a ha, rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem], exact mem_map_of_mem ha, end lemma eval₂_C_mk_eq_zero {I : ideal R} : ∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 := begin intros a ha, rw ← sum_monomial_eq a, dsimp, rw eval₂_sum, refine finset.sum_eq_zero (λ n hn, _), dsimp, rw eval₂_monomial (C.comp (quotient.mk I)) X, refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n), erw coeff_C, by_cases h : m = 0, { simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) }, { simp [h] } end /-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is isomorphic to the quotient of `polynomial R` by the ideal `map C I`, where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/ def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) : polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient := { to_fun := eval₂_ring_hom (quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero) ((quotient.mk (map C I : ideal (polynomial R)) X)), inv_fun := quotient.lift (map C I : ideal (polynomial R)) (eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero, map_mul' := λ f g, by simp, map_add' := λ f g, by simp, left_inv := begin intro f, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { rintros n ⟨x⟩, simp [monomial_eq_smul_X, C_mul'] } end, right_inv := begin rintro ⟨f⟩, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { intros n a, simp [monomial_eq_smul_X, ← C_mul' a (X ^ n)] }, end, } /-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/ lemma is_integral_domain_map_C_quotient {P : ideal R} (H : is_prime P) : is_integral_domain (quotient (map C P : ideal (polynomial R))) := ring_equiv.is_integral_domain (polynomial (quotient P)) (integral_domain.to_is_integral_domain (polynomial (quotient P))) (polynomial_quotient_equiv_quotient_polynomial P).symm /-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/ lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) : is_prime (map C P : ideal (polynomial R)) := (quotient.is_integral_domain_iff_prime (map C P : ideal (polynomial R))).mp (is_integral_domain_map_C_quotient H) /-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`. If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`. In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`. This theorem shows `I'` will not contain any non-zero constant polynomials -/ lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R)) (x : ((quotient.mk I).comp C).range) (hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) : x = 0 := begin let i := ((quotient.mk I).comp C).range_restrict, have hi' : (polynomial.map_ring_hom i).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], rw [ring_hom.mem_ker, coe_map_ring_hom] at hf, replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf, simp only [coeff_map, coeff_zero] at hf, rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf }, obtain ⟨x, hx'⟩ := x, obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx', refine subtype.eq _, simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe], suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)), { obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i) (polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this, refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1, rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero_iff_eq, coe_map_ring_hom, map_C] }, exact hx, end /-- `polynomial R` is never a field for any ring `R`. -/ lemma polynomial_not_is_field : ¬ is_field (polynomial R) := begin by_contradiction hR, by_cases hR' : ∃ (x y : R), x ≠ y, { haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy, obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero, by_cases hp0 : p = 0, { replace hp := congr_arg degree hp, rw [hp0, mul_zero, degree_zero, degree_one] at hp, contradiction }, { have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0, rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this, exact hp0 this } }, { push_neg at hR', exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) } end /-- The only constant in a maximal ideal over a field is `0`. -/ lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R) (I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 := begin refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)), obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0, convert I.smul_mem (C y) hx, rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one], end /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal namespace polynomial @[priority 100] instance {R : Type*} [integral_domain R] [wf_dvd_monoid R] : wf_dvd_monoid (polynomial R) := { well_founded_dvd_not_unit := begin classical, refine rel_hom.well_founded ⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩ (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) _inst_5.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } end polynomial /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R), let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := wf_dvd_monoid.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf lemma linear_independent_powers_iff_eval₂ (f : M →ₗ[R] M) (v : M) : linear_independent R (λ n : ℕ, (f ^ n) v) ↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 := begin rw linear_independent_iff, simp only [finsupp.total_apply, aeval_endomorphism], refl end lemma disjoint_ker_aeval_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : disjoint (aeval f p).ker (aeval f q).ker := begin intros v hv, rcases hpq with ⟨p', q', hpq'⟩, simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1, linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2] using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm, end lemma sup_aeval_range_eq_top_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).range ⊔ (aeval f q).range = ⊤ := begin rw eq_top_iff, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, use aeval f (p * p') v, use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, use aeval f (q * q') v, use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add] using congr_arg (λ p : polynomial R, aeval f p v) hpq' end lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} : (aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker := begin intros v hv, rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩, have h_eval_x : aeval f (p * q) x = 0, { rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] }, have h_eval_y : aeval f (p * q) y = 0, { rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] }, rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero], end lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker := begin apply le_antisymm sup_ker_aeval_le_ker_aeval_mul, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, have h_eval₂_qpp' := calc aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v : by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], have h_eval₂_pqq' := calc aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v : by rw [←mul_assoc, mul_comm] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq', refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq', aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩, rw [add_comm, mul_comm p p', mul_comm q q'], simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq' end end polynomial namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (rename_equiv R fin_zero_equiv'.symm).to_ring_equiv) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (rename_equiv R e.symm).to_ring_equiv is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxilliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (rename_equiv R e).to_ring_equiv /-- Auxilliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p * rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0, { apply rename_injective _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ] (ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) : ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p := begin refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _, rw [mv_polynomial.eval₂_eq', ϕ.map_sum], congr, ext, simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow], end lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) : (ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 := begin simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem], exact ideal.mem_map_of_mem hi end /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself, multivariate version. -/ lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R) (hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I := begin rw as_sum p, suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I, { exact submodule.sum_mem I this }, intros m hm, rw [← mul_one (coeff m p), ← C_mul_monomial], suffices : C (coeff m p) ∈ I, { exact ideal.mul_mem_right I (monomial m 1) this }, simpa [ideal.mem_comap] using hcoe m end /-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} : f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [ne.symm h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw as_sum f, suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact submodule.sum_mem _ this }, intros m hm, rw [← mul_one (coeff m f), ← C_mul_monomial], suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact ideal.mul_mem_right _ _ this }, apply ideal.mem_map_of_mem _, exact hf m } end lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R} (ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) : eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 := begin rw as_sum a, rw [coe_eval₂_hom, eval₂_sum], refine finset.sum_eq_zero (λ n hn, _), simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp], refine mul_eq_zero_of_left _ _, suffices : coeff n a ∈ I, { rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this, simp only [this, C_0] }, exact mem_map_C_iff.1 ha n end /-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an `R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/ def quotient_equiv_quotient_mv_polynomial (I : ideal R) : mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient := { to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi)) (λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)), inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R)) (eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha), map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := begin intro f, apply induction_on f, { rintro ⟨r⟩, rw [coe_eval₂_hom, eval₂_C], simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] }, { simp_intros p q hp hq, rw [hp, hq] }, { simp_intros p i hp, simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply induction_on f, { intros r, simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, ring_hom.coe_comp, eval₂_hom_C] }, { simp_intros p q hp hq, rw [hp, hq] }, { simp_intros p i hp, simp only [hp] } end, commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) } end mv_polynomial namespace polynomial open unique_factorization_monoid variables {D : Type u} [integral_domain D] [unique_factorization_monoid D] @[priority 100] instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) := begin haveI := arbitrary (normalization_monoid D), haveI := to_gcd_monoid D, exact ufm_of_gcd_of_wf_dvd_monoid end end polynomial
e9acf3c04307eb31d56bea1b4881e16f66ee0486
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/concrete_category/unbundled_hom.lean
ba9dab684813121c22cf2b7e1aed309f909d2718
[ "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,191
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.concrete_category.bundled_hom /-! # Category instances for structures that use unbundled homs This file provides basic infrastructure to define concrete categories using unbundled homs (see `class unbundled_hom`), and define forgetful functors between them (see `unbundled_hom.mk_has_forget₂`). -/ universes v u namespace category_theory /-- A class for unbundled homs used to define a category. `hom` must take two types `α`, `β` and instances of the corresponding structures, and return a predicate on `α → β`. -/ class unbundled_hom {c : Type u → Type u} (hom : Π {α β}, c α → c β → (α → β) → Prop) := (hom_id [] : ∀ {α} (ia : c α), hom ia ia id) (hom_comp [] : ∀ {α β γ} {Iα : c α} {Iβ : c β} {Iγ : c γ} {g : β → γ} {f : α → β} (hg : hom Iβ Iγ g) (hf : hom Iα Iβ f), hom Iα Iγ (g ∘ f)) namespace unbundled_hom variables (c : Type u → Type u) (hom : Π ⦃α β⦄, c α → c β → (α → β) → Prop) [𝒞 : unbundled_hom hom] include 𝒞 instance bundled_hom : bundled_hom (λ α β (Iα : c α) (Iβ : c β), subtype (hom Iα Iβ)) := { to_fun := λ _ _ _ _, subtype.val, id := λ α Iα, ⟨id, hom_id hom Iα⟩, id_to_fun := by intros; refl, comp := λ _ _ _ _ _ _ g f, ⟨g.1 ∘ f.1, hom_comp c g.2 f.2⟩, comp_to_fun := by intros; refl, hom_ext := by intros; apply subtype.eq } section has_forget₂ variables {c hom} {c' : Type u → Type u} {hom' : Π ⦃α β⦄, c' α → c' β → (α → β) → Prop} [𝒞' : unbundled_hom hom'] include 𝒞' variables (obj : Π ⦃α⦄, c α → c' α) (map : ∀ ⦃α β Iα Iβ f⦄, @hom α β Iα Iβ f → hom' (obj Iα) (obj Iβ) f) /-- A custom constructor for forgetful functor between concrete categories defined using `unbundled_hom`. -/ def mk_has_forget₂ : has_forget₂ (bundled c) (bundled c') := bundled_hom.mk_has_forget₂ obj (λ X Y f, ⟨f.val, map f.property⟩) (λ _ _ _, rfl) end has_forget₂ end unbundled_hom end category_theory
cb018535d39c33351fdcbc37fc3782765a407593
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/prop819/strict_complex_iso.lean
821616f14d2bfa37a7da4375a23db40543f1a87a
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,018
lean
import for_mathlib.SemiNormedGroup import algebra.homology.additive namespace SemiNormedGroup protected class strict_iso {A B : SemiNormedGroup} (f : A ≅ B) := (strict_hom' : ∀ a : A, ∥f.hom a∥₊ = ∥a∥₊) @[simp] lemma strict_iso_hom {A B : SemiNormedGroup} (f : A ≅ B) [strict_iso f] (a : A) : ∥f.hom a∥₊ = ∥a∥₊ := strict_iso.strict_hom' _ @[simp] lemma strict_iso_inv {A B : SemiNormedGroup} (f : A ≅ B) [strict_iso f] (b : B) : ∥f.inv b∥₊ = ∥b∥₊ := begin have : b = f.hom (f.inv b), { change b = (f.inv ≫ f.hom) b, simp }, conv_rhs {rw this}, rw strict_iso_hom, end end SemiNormedGroup structure strict_iso (C D : cochain_complex SemiNormedGroup ℕ) := (iso : C ≅ D) [is_strict : ∀ i : ℕ, SemiNormedGroup.strict_iso $ (homological_complex.eval _ _ i).map_iso iso] instance (C D : cochain_complex SemiNormedGroup ℕ) (f : strict_iso C D) (n : ℕ) : SemiNormedGroup.strict_iso ((homological_complex.eval _ _ n).map_iso f.iso) := f.is_strict _
24141aa2b9b79acff0d8d4a61eb496b23d3b96be
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/nat/basic.lean
fa059febea6ee125b6cdb58da6979a9a5de46861
[ "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
69,886
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.group.hom_instances import algebra.order_functions import algebra.ordered_ring import algebra.group_power.order /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_one_add, nat.right_distrib, nat.one_mul] } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance 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 _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := ⟨n.succ_pos⟩ instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := ⟨lt_trans zero_lt_one h.1⟩ end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul _ _ n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] /-! ### `sub` -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := decidable.mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact decidable.mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by { rw [add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt]; simp }) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨ λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans decidable.le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (_root_.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases eq_zero_or_pos b with rfl|hb, { simp }, rcases eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw nat.sub_eq_zero_of_le H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := by simp | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [nat.add_sub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-! ### `pow` -/ -- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`, -- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long. -- So, we leave a version in the `nat` namespace as well. -- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.) protected theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i := canonically_ordered_semiring.pow_le_pow_of_le_left H theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j | 0 h := by rw eq_zero_of_le_zero h; apply le_refl | (succ j) h := h.lt_or_eq_dec.elim (λhl, by rw [pow_succ', ← nat.mul_one (x^i)]; exact nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H) (λe, by rw e; refl) theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : 0 < i) : x^i < y^i := begin cases i with i, { exact absurd h (not_lt_zero _) }, rw [pow_succ', pow_succ'], exact nat.mul_lt_mul' (nat.pow_le_pow_of_le_left (le_of_lt H) _) H (pow_pos (lt_of_le_of_lt (zero_le _) H) _) end theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j := begin have xpos := lt_of_succ_lt H, refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h), rw [← nat.mul_one (x^i), pow_succ'], exact nat.mul_lt_mul_of_pos_left H (pow_pos xpos _) end -- TODO: Generalize? lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices 1*p^n < p*p^n, by simpa [pow_succ], nat.mul_lt_mul_of_pos_right h (pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma lt_two_pow (n : ℕ) : n < 2^n := lt_pow_self dec_trivial n lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n := by { rw ←one_pow n, exact nat.pow_le_pow_of_le_left h n } lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m) lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n := by { rw ←one_pow n, exact pow_lt_pow_of_lt_left h₁ h₀ } lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) := one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (λ (n : ℕ), x^n) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (λ (n : ℕ), x^n) := strict_mono.injective (pow_right_strict_mono k) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma mul_lt_mul_pow_succ {n a q : ℕ} (a0 : 0 < a) (q1 : 1 < q) : n * q < a * q ^ (n + 1) := begin rw [pow_succ', ← mul_assoc, mul_lt_mul_right (zero_lt_one.trans q1)], exact lt_mul_of_one_le_of_lt' (nat.succ_le_iff.mpr a0) (nat.lt_pow_self q1 n), end end nat lemma strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) : strict_mono (λ m, (f m) ^ n) := (nat.pow_left_strict_mono hn).comp hf namespace nat lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) theorem sq_sub_sq (a b : ℕ) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by { rw [sq, sq], exact nat.mul_self_sub_mul_self_eq a b } alias nat.sq_sub_sq ← nat.pow_two_sub_pow_two /-! ### `pow` and `mod` / `dvd` -/ theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w m : ℕ) : m % (b^succ w) = b * (m/b % b^w) + m % b := begin apply nat.strong_induction_on m, clear m, intros p IH, cases lt_or_ge p (b^succ w) with h₁ h₁, -- base case: p < b^succ w { have h₂ : p / b < b^w, { rw [div_lt_iff_lt_mul p _ b_pos], simpa [pow_succ'] using h₁ }, rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂], simp [div_add_mod] }, -- step: p ≥ b^succ w { -- Generate condition for induction hypothesis have h₂ : p - b^succ w < p, { apply sub_lt_of_pos_le _ _ (pow_pos b_pos _) h₁ }, -- Apply induction rw [mod_eq_sub_mod h₁, IH _ h₂], -- Normalize goal and h1 simp only [pow_succ], simp only [ge, pow_succ] at h₁, -- Pull subtraction outside mod and div rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁], -- Cancel subtraction inside mod b^w have p_b_ge : b^w ≤ p / b, { rw [le_div_iff_mul_le _ _ b_pos, mul_comm], exact h₁ }, rw [eq.symm (mod_eq_sub_mod p_b_ge)] } end lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l | (x+1) w := begin split, { intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, }, { intro a, cases x with x, { simp only [one_pow], }, { have le := (pow_le_iff_le_right (le_add_left _ _)).mp a, use (x+2)^(l-k), rw [←pow_add, add_comm k, nat.sub_add_cancel le], } } end /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l := by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w] lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have succ p * (succ p)^k ∣ succ p * 1, by simpa [pow_succ] using h, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_left (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma pow_div {x m n : ℕ} (h : n ≤ m) (hx : 0 < x) : x ^ m / x ^ n = x ^ (m - n) := by rw [nat.div_eq_iff_eq_mul_left (pow_pos hx n) (pow_dvd_pow _ h), pow_sub_mul_pow _ h] /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-- Two natural numbers are equal if and only if the have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr (dvd_refl _)) ((h _).mp (dvd_refl _)), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if the have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp (dvd_refl _)) ((h _).mpr (dvd_refl _)), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### `shiftl` and `shiftr` -/ lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 := (nat.mul_one _).symm | (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k), by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm, mul_comm 2] lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n | 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul] | (k+1) := begin change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k), rw bit1_val, change 2 * (shiftl' tt m k + 1) = _, rw [shiftl'_tt_eq_mul_pow, mul_left_comm, mul_comm 2], end lemma one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (nat.one_mul _) @[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (nat.zero_mul _) lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 := (nat.div_one _).symm | (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $ by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (nat.zero_div _) theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := by simp [size] @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := show size (bit1 0) = 1, by rw [size_bit1, size_zero] @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n), { simp }, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, simp }, { intros b m IH n h, by_cases e : bit b m = 0, { simp [e] }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, decidable.iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact decidable.not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (le_of_lt_succ h').lt_or_eq_dec.elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
d96a99b73cae1f4cbf13af002444f06f350fbb59
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/subtype.lean
51042c3eac46a9b39ed448b14681a7bbfbb46b98
[ "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
5,334
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import tactic.lint import tactic.ext import tactic.simps open function namespace subtype variables {α : Sort*} {β : Sort*} {γ : Sort*} {p : α → Prop} {q : α → Prop} /-- See Note [custom simps projection] -/ def simps.val (x : subtype p) : α := x initialize_simps_projections subtype (val → coe) /-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x` instead of `x.1`. A similar result is `subtype.mem` in `data.set.basic`. -/ lemma prop (x : subtype p) : p x := x.2 @[simp] lemma val_eq_coe {x : subtype p} : x.1 = ↑x := rfl @[simp] protected theorem «forall» {q : {a // p a} → Prop} : (∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ /-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q` when using `subtype.forall` from right to left. -/ protected theorem forall' {q : ∀x, p x → Prop} : (∀ x h, q x h) ↔ (∀ x : {a // p a}, q x x.2) := (@subtype.forall _ _ (λ x, q x.1 x.2)).symm @[simp] protected theorem «exists» {q : {a // p a} → Prop} : (∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ @[ext] protected lemma ext : ∀ {a1 a2 : {x // p x}}, (a1 : α) = (a2 : α) → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl lemma ext_iff {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = (a2 : α) := ⟨congr_arg _, subtype.ext⟩ lemma heq_iff_coe_eq (h : ∀ x, p x ↔ q x) {a1 : {x // p x}} {a2 : {x // q x}} : a1 == a2 ↔ (a1 : α) = (a2 : α) := eq.rec (λ a2', heq_iff_eq.trans ext_iff) (funext $ λ x, propext (h x)) a2 lemma ext_val {a1 a2 : {x // p x}} : a1.1 = a2.1 → a1 = a2 := subtype.ext lemma ext_iff_val {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.1 = a2.1 := ext_iff @[simp] theorem coe_eta (a : {a // p a}) (h : p a) : mk ↑a h = a := subtype.ext rfl @[simp] theorem coe_mk (a h) : (@mk α p a h : α) = a := rfl @[simp, nolint simp_nf] -- built-in reduction doesn't always work theorem mk_eq_mk {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := ⟨λ H, by injection H, λ H, by congr; assumption⟩ theorem coe_injective : injective (coe : subtype p → α) := λ a b, subtype.ext theorem val_injective : injective (@val _ p) := coe_injective /-- Restrict a (dependent) function to a subtype -/ def restrict {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) : β x.1 := f x lemma restrict_apply {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) : restrict f p x = f x.1 := by refl lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict f p = f ∘ coe := by refl lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) : injective (restrict f p) := h.comp coe_injective /-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/ @[simps] def coind {α β} (f : α → β) {p : β → Prop} (h : ∀a, p (f a)) : α → subtype p := λ a, ⟨f a, h a⟩ theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀a, p (f a)) (hf : injective f) : injective (coind f h) := λ x y hxy, hf $ by apply congr_arg subtype.val hxy /-- Restriction of a function to a function on subtypes. -/ @[simps] def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) : subtype p → subtype q := λ x, ⟨f x, h x x.prop⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀a, p a → q (f a)) (hf : injective f) : injective (map f h) := coind_injective _ $ hf.comp coe_injective instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) := ⟨λ s t, (s : α) ≈ (t : α)⟩ theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} : s ≈ t ↔ (s : α) ≈ (t : α) := iff.rfl variables [setoid α] protected theorem refl (s : subtype p) : s ≈ s := setoid.refl ↑s protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s := setoid.symm h protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) := mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _) instance (p : α → Prop) : setoid (subtype p) := setoid.mk (≈) (equivalence p) end subtype namespace subtype /-! Some facts about sets, which require that `α` is a type. -/ variables {α : Type*} {β : Type*} {γ : Type*} {p : α → Prop} @[simp] lemma coe_prop {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.prop lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property end subtype
3b7c306e1b159dc5cf0d88c2d19773bf7610e629
67190c9aacc0cac64fb4463d93e84c696a5be896
/Classes/2019-10-03.lean
f888ff85e09e03a76957928ba85df7c1ec153aff
[]
no_license
lucasresck/Discrete-Mathematics
ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738
0a08081c5f393e5765259d3f1253c3a6dd043dac
refs/heads/master
1,596,627,857,734
1,573,411,500,000
1,573,411,500,000
212,489,764
0
0
null
null
null
null
UTF-8
Lean
false
false
944
lean
constant U : Type constant p : U → U → Prop constants A B C : U → Prop theorem ex1 : (∃ x, ∀ y, p x y) → (∀ y, ∃ x, p x y) := begin intros h1, intros a, cases h1 with b h2, existsi b, have h3, from h2 a, assumption end theorem ex2 (h1 : ∀ x, A x ∨ B x) (h2 : ∀ y, ¬ A y) : ∀ x, B x := begin intro a, cases h1 a, have h3, from h2 a, contradiction, assumption end constants even odd : U → Prop constant s : U → U theorem ex3 (h1 : ∀ x, even x ∨ odd x) (h2 : ∀ x, odd x → even (s x)) : ∀ x, even x ∨ even (s x) := begin intro a, cases h1 a, exact (or.inl h), --have h3, from h2 a h, exact (or.inr $ h2 a h) end theorem ex4 : (∃ x, A x) ∨ (∃ x, B x) → (∃ x, A x ∨ B x) := begin intro h, cases h, cases h, existsi h_w, exact (or.inl h_h), cases h, existsi h_w, exact (or.inr h_h), end
14dc2aed8679c7aba59cb73741116cc14fc8199c
ef6b7797dbbd7b1dfff69894d190a965b101c5ff
/src/euclid_props.lean
6a75eeb44ccabf59d131cc3013c91d107eaf005b
[]
no_license
utensil-star/leanteach2020
43d57f1b23eded178e2049a0957b7ec38fd4e1a7
93326a5e5b0efeba30d9dc9ee85d52b1029cb24d
refs/heads/master
1,666,413,811,198
1,592,598,394,000
1,592,598,394,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,056
lean
import .euclid import tactic -- Redo the local notation -------------------------- local infix ` ≃ `:55 := congruent -- typed as \ equiv local infix `⬝`:56 := Segment.mk -- typed as \ cdot -- Lemma needed for Proposition 1 lemma hypothesis1_about_circles_radius (s : Segment) : let c₁ : Circle := ⟨s.p1, s.p2⟩ in let c₂ : Circle := ⟨s.p2, s.p1⟩ in radius c₁ + radius c₂ >= distance c₁.center c₂.center := begin intros, show distance s.p1 s.p2 ≤ radius c₁ + radius c₂, calc distance s.p1 s.p2 ≤ distance s.p1 s.p2 + distance s.p1 s.p2 : by {simp, apply distance_not_neg} ... = radius c₁ + distance s.p1 s.p2 : by refl ... = radius c₁ + distance s.p2 s.p1 : by simp ... = radius c₁ + radius c₂ : by refl, end -- Another lemma needed for Proposition 1 lemma hypothesis2_about_circles_radius (s : Segment) : let c₁ : Circle := ⟨s.p1, s.p2⟩ in let c₂ : Circle := ⟨s.p2, s.p1⟩ in abs (radius c₁ - radius c₂) <= distance c₁.center c₂.center := begin intros, show abs (radius c₁ - radius c₂) ≤ distance s.p1 s.p2, calc abs (radius c₁ - radius c₂) = abs (distance s.p1 s.p2 - radius c₂) : by refl ... = abs (distance s.p1 s.p2 - distance s.p2 s.p1) : by refl ... = abs (distance s.p1 s.p2 - distance s.p1 s.p2) : by simp ... = 0 : by simp ... ≤ distance s.p1 s.p2 : by apply distance_not_neg, end -- # Proposition 1 ------------------ lemma construct_equilateral (s : Segment) : ∃ (tri: Triangle), s.p1 = tri.p1 ∧ s.p2 = tri.p2 ∧ is_equilateral tri := begin set c₁ : Circle := ⟨s.p1, s.p2⟩, set c₂ : Circle := ⟨s.p2, s.p1⟩, have h₁ := (hypothesis1_about_circles_radius s), have h₂ := hypothesis2_about_circles_radius s, set p : Point := circles_intersect c₁ c₂ h₁ h₂, have hp₁ : p ∈ circumference c₁, from (circles_intersect' c₁ c₂ h₁ h₂).1, have hp₂ : p ∈ circumference c₂, from (circles_intersect' c₁ c₂ h₁ h₂).2, use ⟨s.p1, s.p2, p⟩, --- Cleaning up the context --- tidy; unfold circumference radius_segment at hp₁ hp₂; unfold sides_of_triangle; dsimp * at *, --- Cleaning done --- {calc s.p1 ⬝ s.p2 ≃ s.p2 ⬝ s.p1 : by symmetry ... ≃ s.p2 ⬝ p : by assumption}, {calc s.p2 ⬝ p ≃ s.p2 ⬝ s.p1 : by {apply cong_symm, assumption} ... ≃ s.p1 ⬝ s.p2 : by apply segment_symm ... ≃ s.p1 ⬝ p : by assumption ... ≃ p ⬝ s.p1 : by symmetry}, end lemma ray_cut_length (r : Ray) (s : Segment) (h : r.base ≠ r.ext) : ∃ p : Point, p ∈ points_of_ray r h ∧ r.base ⬝ p ≃ s := sorry -- lemma ray_circle_intersect (AB : Ray) (ne : AB.base ≠ AB.ext) (C : Circle) (center : C.center = AB.base): -- ∃ (p : Point), (p ∈ circumference C) ∧ (p ∈ points_of_ray AB ne) := -- begin -- have h := extend (Segment.mk AB.base AB.ext Segment.mk AB.ext ) CD? ne, -- end -- Lemma needed for proposition 2 lemma ray_circle_intersect (AB : Ray) (ne : AB.base ≠ AB.ext) (C : Circle) (p : Point) : circle_interior p C → p ∈ points_of_ray AB ne → ∃ x : Point, x ∈ points_of_ray AB ne ∧ x ∈ circumference C := sorry -- Use *have* for introducing new facts. Follow it up with a proof of -- said fact. -- have x_pos : x > 0, ..... -- Use *let* for introducing new terms (of a given type). Follow it up -- with a definition of the term. -- Ex: let x : ℕ := 5 -- Use *set* is similar to *let*, but it additionally replaces every term -- in the context with the new definition. -- Ex: set x : ℕ := 5, -> replace x with 5 everywhere -- Lemma needed for Proposition 2 lemma equilateral_triangle_nonzero_side_1 (abc : Triangle) : abc.p1 ≠ abc.p2 → is_equilateral abc → abc.p2 ≠ abc.p3 := begin rintros ne_a_b ⟨h₁, h₂⟩ eq_b_c, change (sides_of_triangle abc).fst with abc.p1⬝abc.p2 at h₁, change (sides_of_triangle abc).snd.fst with abc.p2⬝abc.p3 at h₁ h₂, change (sides_of_triangle abc).snd.snd with abc.p3⬝abc.p1 at h₁ h₂, have cong_cc_bc : abc.p3⬝abc.p3 = abc.p2⬝abc.p3, by simp [eq_b_c], have eq_a_b : abc.p1 = abc.p2, { apply zero_segment (abc.p1 ⬝ abc.p2) abc.p3, rwa cong_cc_bc}, finish, end lemma equilateral_triangle_nonzero_side_2 (abc : Triangle) : abc.p1 ≠ abc.p2 → is_equilateral abc → abc.p3 ≠ abc.p1 := begin rintros ne_a_b ⟨h₁, h₂⟩ eq_b_c, set sides := sides_of_triangle abc, have h₃ := cong_trans sides.1 sides.2.1 sides.2.2 h₁ h₂, have eq_1_3 : abc.p1 ⬝ abc.p3 ≃ abc.p3 ⬝ abc.p1, by apply segment_symm, have cong_cc_bc : abc.p3⬝abc.p3 = abc.p1⬝abc.p3, by simp [eq_b_c], have eq_a_b : abc.p1 = abc.p2, { apply zero_segment (abc.p1 ⬝ abc.p2) abc.p3, rw cong_cc_bc, set a := abc.p1 ⬝ abc.p2, set b := abc.p3 ⬝ abc.p1, set c := abc.p1 ⬝ abc.p3, have a_cong : a ≃ b, by tidy, have b_cong : b ≃ c, by symmetry, have abc_trans : a ≃ c, by apply cong_trans a b c a_cong b_cong, assumption}, finish, end lemma radius_non_zero (c : Circle) : c.center ≠ c.outer → 0 < radius c := begin simp only [radius, radius_segment], apply distance_pos, end lemma radii_equal (c : Circle) (a b : Point) : a ∈ circumference c → b ∈ circumference c → c.center⬝a ≃ c.center⬝b := begin intros h₁ h₂, have eq_a_rad : c.center⬝a ≃ radius_segment c, { simp [circumference] at h₁, apply cong_symm, assumption}, have eq_b_rad : radius_segment c ≃ c.center⬝b, by tidy, refine cong_trans (c.center⬝a) (radius_segment c) (c.center⬝b) _ _, repeat {finish}, end --Proposition 2 lemma placeline (bc : Segment) (a : Point) : a ≠ bc.p1 → bc.p1 ≠ bc.p2 → ∃ (s : Segment), (a = s.p1) ∧ bc ≃ s := begin intros ne_a_b ne_b_c, set ab : Segment := a⬝bc.p1, choose abd h using construct_equilateral ab, rcases h with ⟨h₁, h₂, h₃⟩, set da : Ray := ⟨abd.p3, a⟩, set db : Ray := ⟨abd.p3, ab.p2⟩, set circ : Circle := ⟨bc.p1, bc.p2⟩, have ne_d_b : db.base ≠ db.ext, { change db.base with abd.p3, symmetry, have x : db.ext = abd.p2, by assumption, rw x, apply equilateral_triangle_nonzero_side_1, rw [← h₁, ← h₂], repeat {assumption}}, have ne_d_a : da.base ≠ da.ext, { change da.base with abd.p3, have x : da.ext = abd.p1, by assumption, have ne : abd.p1 ≠ abd.p2, by finish, rw x, apply equilateral_triangle_nonzero_side_2 abd ne, assumption}, have b_in_circ : circle_interior bc.p1 circ, { simp [circle_interior, radius], apply distance_pos, assumption}, have b_in_bc : db.ext ∈ points_of_ray db ne_d_b, { sorry}, rcases ray_circle_intersect db ne_d_b circ bc.p1 b_in_circ b_in_bc with ⟨g, g_in_ray, g_in_circum⟩, have ne_d_g : abd.p3 ≠ g, { sorry}, set c₁ : Circle := ⟨abd.p3, g⟩, have d_in_c₁ : circle_interior abd.p3 c₁, { change c₁.center with abd.p3, have dist_0 : distance c₁.center abd.p3 = 0, by tidy, rw [circle_interior, dist_0], apply radius_non_zero, assumption}, have d_in_da : da.base ∈ points_of_ray da ne_d_a, { sorry}, rcases ray_circle_intersect da ne_d_a c₁ abd.p3 d_in_c₁ d_in_da with ⟨l, l_in_ray, l_in_circum⟩, have bc_eq_bg : distance bc.p1 g = distance bc.p1 bc.p2, { sorry}, have al_eq_bg : distance a l = distance bc.p1 bc.p2, { sorry}, set al := a ⬝ l, set dl := da.base ⬝ l, set dg := da.base ⬝ g, set bg := bc.p1 ⬝ g, have cong_bc_bg : bc ≃ bg, set circum := circumference circ, set rad := radius_segment circ, --have dl_eq_rad : rad ≃ bc, by tidy, --have dg_eq_rad : dg ≃ rad, by tidy?, --have pls_work_trans := cong_trans bg rad dl dg_eq_rad dl_eq_rad, --apply cong_symm, --apply_assumption sorry, have dl_eq_dg : dl ≃ dg, { set circum := circumference c₁, set rad := radius_segment c₁, have dl_eq_rad : rad ≃ dl, by assumption, change dg with rad, apply cong_symm, assumption}, have cong_bg_al : bg ≃ al, { sorry}, use al, simp only [true_and, eq_self_iff_true], apply cong_trans bc bg al cong_bc_bg cong_bg_al, end #exit -- # Proposition 3 lemma prop3 (AB C : Segment) (greater : length AB > length C): ∃ (s : Segment), (length s = length C) ∧ (s.p1 = AB.p1) ∧ (between AB.p1 s.p2 AB.p2) := begin sorry end -- # Proposition 4 ------------------ -- If two triangles have two sides equal to two sides respectively, -- and have the angles contained by the equal straight lines equal, -- then they also have the base equal to the base, the triangle equals -- the triangle, and the remaining angles equal the remaining angles -- respectively, namely those opposite the equal sides. -- SAS congruency. lemma prop4 (t1 t2 : Triangle) (dif1 : distinct t1.p1 t1.p2 t1.p3) (dif2 : distinct t2.p1 t2.p2 t2.p3): let sides1 := (sides_of_triangle t1) in let sides2 := (sides_of_triangle t2) in let angles1 := (angles_of_triangle t1 dif1) in let angles2 := (angles_of_triangle t2 dif2) in (sides1.1 = sides2.1) → (sides1.2.1 = sides2.2.1) → (angles1.1 ≃ angles2.1) → (sides1.2.2 = sides2.2.2) ∧ (angles1.nth 1 = angles2.nth 1) ∧ (angles1.nth 2 = angles2.nth 2) := begin sorry end -- # Proposition 5 -- # Proposition 7 -- # Proposition 8 -- # Proposition 10 -- # Proposition 11 -- # Proposition 13 -- # Proposition 14 -- # Proposition 15 -- # Proposition 16 -- # Proposition 18 -- # Proposition 19 -- # Proposition 20 -- # Proposition 22 -- # Proposition 26 -- # Proposition 29 -- # Proposition 31 -- # Proposition 34 -- # Proposition 37 -- # Proposition 41 -- # Proposition 46 -- # Proposition 47 -- # Proposition 48
3589c36d72d0f82a0a72cd7a0170aa16e22d26b1
5c47d5f6f51310e594c57486e051666894b008a1
/CategoryTheory/Limits.lean
842143b53683d58171d635f8d39ba094e601bf6e
[ "Apache-2.0" ]
permissive
adrianmartir/category-theory-lean4
100ed364c07441b30d1483949152c39060563ccf
fa786c12114b7fad3f6c9e831d8ef2120a46bd05
refs/heads/main
1,687,620,544,571
1,626,958,787,000
1,626,958,787,000
372,252,151
1
0
null
null
null
null
UTF-8
Lean
false
false
937
lean
import CategoryTheory.Category namespace Category_theory open CategoryTheory open Category variable (J : HomStruct) [Category J] variable {C : HomStruct} [Category C] def const (c: C.obj) : Functor J C := { obj := (fun _ => c), map := (fun _ => id' c), map_id := rfl, map_comp := by intros simp } def constf : Functor C (FunctorCat J C) := { obj := @const J _ C _ map := fun f => { app := fun _ => f, naturality := by intros simp [const] } map_id := by intros apply nat_ext simp [id', idTrans] apply funext intros simp [const] map_comp := by intros apply nat_ext simp [comp, vComp] } -- Should be the constant Functor composed with the yoneda embedding -- https://github.com/leanprover-community/mathlib/blob/4ddbdc1b476032fb56a9b8ccc4a55c81f6523ec8/src/Category_theory/limits/cones.lean -- def cone : Functor Cᵒᵖ (Type v) := nat_trans (const )
15995d59a1d7d5f9a22c1d262edeb426f016cbe6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/convex/extreme.lean
c27c474fdd252f961e5defe88019a059351ca96c
[ "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,842
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import linear_algebra.affine_space.independent import algebra.big_operators.basic import analysis.convex.topology /-! # Extreme sets This file defines extreme sets and extreme points for sets in a real vector space. An extreme set of `A` is a subset of `A` that is as far as it can get in any outward direction: If point `x` is in it and point `y ∈ A`, then the line passing through `x` and `y` leaves `A` at `x`. This is an analytic notion of "being on the side of". It is weaker than being exposed (see `is_exposed.is_extreme`). ## Main declarations * `is_extreme A B`: States that `B` is an extreme set of `A` (in the literature, `A` is often implicit). * `set.extreme_points A`: Set of extreme points of `A` (corresponding to extreme singletons). * `convex.mem_extreme_points_iff_convex_remove`: A useful equivalent condition to being an extreme point: `x` is an extreme point iff `A \ {x}` is convex. ## Implementation notes The exact definition of extremeness has been carefully chosen so as to make as many lemmas unconditional. In practice, `A` is often assumed to be a convex set. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO * define convex independence, intrinsic frontier and prove lemmas related to extreme sets and points. * generalise to Locally Convex Topological Vector Spaces™ More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine open set variables {E : Type*} [add_comm_group E] [module ℝ E] {x : E} {A B C : set E} /-- A set `B` is an extreme subset of `A` if `B ⊆ A` and all points of `B` only belong to open segments whose ends are in `B`. -/ def is_extreme (A B : set E) : Prop := B ⊆ A ∧ ∀ x₁ x₂ ∈ A, ∀ x ∈ B, x ∈ open_segment x₁ x₂ → x₁ ∈ B ∧ x₂ ∈ B namespace is_extreme @[refl] lemma refl (A : set E) : is_extreme A A := ⟨subset.refl _, λ x₁ x₂ hx₁A hx₂A x hxA hx, ⟨hx₁A, hx₂A⟩⟩ @[trans] lemma trans (hAB : is_extreme A B) (hBC : is_extreme B C) : is_extreme A C := begin use subset.trans hBC.1 hAB.1, rintro x₁ x₂ hx₁A hx₂A x hxC hx, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x (hBC.1 hxC) hx, exact hBC.2 x₁ x₂ hx₁B hx₂B x hxC hx, end lemma antisymm : anti_symmetric (is_extreme : set E → set E → Prop) := λ A B hAB hBA, subset.antisymm hBA.1 hAB.1 instance : is_partial_order (set E) is_extreme := { refl := refl, trans := λ A B C, trans, antisymm := antisymm } lemma convex_diff (hA : convex A) (hAB : is_extreme A B) : convex (A \ B) := convex_iff_open_segment_subset.2 (λ x₁ x₂ ⟨hx₁A, hx₁B⟩ ⟨hx₂A, hx₂B⟩ x hx, ⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx).1⟩) lemma inter (hAB : is_extreme A B) (hAC : is_extreme A C) : is_extreme A (B ∩ C) := begin use subset.trans (inter_subset_left _ _) hAB.1, rintro x₁ x₂ hx₁A hx₂A x ⟨hxB, hxC⟩ hx, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx, obtain ⟨hx₁C, hx₂C⟩ := hAC.2 x₁ x₂ hx₁A hx₂A x hxC hx, exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩, end lemma Inter {ι : Type*} [nonempty ι] {F : ι → set E} (hAF : ∀ i : ι, is_extreme A (F i)) : is_extreme A (⋂ i : ι, F i) := begin obtain i := classical.arbitrary ι, use Inter_subset_of_subset i (hAF i).1, rintro x₁ x₂ hx₁A hx₂A x hxF hx, simp_rw mem_Inter at ⊢ hxF, have h := λ i, (hAF i).2 x₁ x₂ hx₁A hx₂A x (hxF i) hx, exact ⟨λ i, (h i).1, λ i, (h i).2⟩, end lemma bInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme A B) : is_extreme A (⋂ B ∈ F, B) := begin obtain ⟨B, hB⟩ := hF, use subset.trans (bInter_subset_of_mem hB) (hAF B hB).1, rintro x₁ x₂ hx₁A hx₂A x hxF hx, rw mem_bInter_iff at ⊢ hxF, rw mem_bInter_iff, have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma sInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme A B) : is_extreme A (⋂₀ F) := begin obtain ⟨B, hB⟩ := hF, use subset.trans (sInter_subset_of_mem hB) (hAF B hB).1, rintro x₁ x₂ hx₁A hx₂A x hxF hx, simp_rw mem_sInter at ⊢ hxF, have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma mono (hAC : is_extreme A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_extreme B C := ⟨hCB, λ x₁ x₂ hx₁B hx₂B x hxC hx, hAC.2 x₁ x₂ (hBA hx₁B) (hBA hx₂B) x hxC hx⟩ end is_extreme /-- A point `x` is an extreme point of a set `A` if `x` belongs to no open segment with ends in `A`, except for the obvious `open_segment x x`. -/ def set.extreme_points (A : set E) : set E := {x ∈ A | ∀ (x₁ x₂ ∈ A), x ∈ open_segment x₁ x₂ → x₁ = x ∧ x₂ = x} lemma extreme_points_def : x ∈ A.extreme_points ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ open_segment x₁ x₂ → x₁ = x ∧ x₂ = x := iff.rfl /-- A useful restatement using `segment`: `x` is an extreme point iff the only (closed) segments that contain it are those with `x` as one of their endpoints. -/ lemma mem_extreme_points_iff_forall_segment : x ∈ A.extreme_points ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment x₁ x₂ → x₁ = x ∨ x₂ = x := begin split, { rintro ⟨hxA, hAx⟩, use hxA, rintro x₁ x₂ hx₁ hx₂ hx, by_contra, push_neg at h, exact h.1 (hAx _ _ hx₁ hx₂ (mem_open_segment_of_ne_left_right h.1 h.2 hx)).1 }, rintro ⟨hxA, hAx⟩, use hxA, rintro x₁ x₂ hx₁ hx₂ hx, obtain rfl | rfl := hAx x₁ x₂ hx₁ hx₂ (open_segment_subset_segment _ _ hx), { exact ⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩ }, exact ⟨right_mem_open_segment_iff.1 hx, rfl⟩, end /-- x is an extreme point to A iff {x} is an extreme set of A. -/ lemma mem_extreme_points_iff_extreme_singleton : x ∈ A.extreme_points ↔ is_extreme A {x} := begin split, { rintro ⟨hxA, hAx⟩, use singleton_subset_iff.2 hxA, rintro x₁ x₂ hx₁A hx₂A y (rfl : y = x), exact hAx x₁ x₂ hx₁A hx₂A }, exact λ hx, ⟨singleton_subset_iff.1 hx.1, λ x₁ x₂ hx₁ hx₂, hx.2 x₁ x₂ hx₁ hx₂ x rfl⟩, end lemma extreme_points_subset : A.extreme_points ⊆ A := λ x hx, hx.1 @[simp] lemma extreme_points_empty : (∅ : set E).extreme_points = ∅ := subset_empty_iff.1 extreme_points_subset @[simp] lemma extreme_points_singleton : ({x} : set E).extreme_points = {x} := extreme_points_subset.antisymm $ singleton_subset_iff.2 ⟨mem_singleton x, λ x₁ x₂ hx₁ hx₂ _, ⟨hx₁, hx₂⟩⟩ lemma convex.mem_extreme_points_iff_convex_remove (hA : convex A) : x ∈ A.extreme_points ↔ x ∈ A ∧ convex (A \ {x}) := begin use λ hx, ⟨hx.1, (mem_extreme_points_iff_extreme_singleton.1 hx).convex_diff hA⟩, rintro ⟨hxA, hAx⟩, refine mem_extreme_points_iff_forall_segment.2 ⟨hxA, λ x₁ x₂ hx₁ hx₂ hx, _⟩, rw convex_iff_segment_subset at hAx, by_contra, push_neg at h, exact (hAx ⟨hx₁, λ hx₁, h.1 (mem_singleton_iff.2 hx₁)⟩ ⟨hx₂, λ hx₂, h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl, end lemma convex.mem_extreme_points_iff_mem_diff_convex_hull_remove (hA : convex A) : x ∈ A.extreme_points ↔ x ∈ A \ convex_hull (A \ {x}) := by rw [hA.mem_extreme_points_iff_convex_remove, hA.convex_remove_iff_not_mem_convex_hull_remove, mem_diff] lemma inter_extreme_points_subset_extreme_points_of_subset (hBA : B ⊆ A) : B ∩ A.extreme_points ⊆ B.extreme_points := λ x ⟨hxB, hxA⟩, ⟨hxB, λ x₁ x₂ hx₁ hx₂ hx, hxA.2 x₁ x₂ (hBA hx₁) (hBA hx₂) hx⟩ namespace is_extreme lemma extreme_points_subset_extreme_points (hAB : is_extreme A B) : B.extreme_points ⊆ A.extreme_points := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (hAB.trans (mem_extreme_points_iff_extreme_singleton.1 hx)) lemma extreme_points_eq (hAB : is_extreme A B) : B.extreme_points = B ∩ A.extreme_points := subset.antisymm (λ x hx, ⟨hx.1, hAB.extreme_points_subset_extreme_points hx⟩) (inter_extreme_points_subset_extreme_points_of_subset hAB.1) end is_extreme lemma extreme_points_convex_hull_subset : (convex_hull A).extreme_points ⊆ A := begin rintro x hx, rw (convex_convex_hull _).mem_extreme_points_iff_convex_remove at hx, by_contra, exact (convex_hull_min (subset_diff.2 ⟨subset_convex_hull _, disjoint_singleton_right.2 h⟩) hx.2 hx.1).2 rfl, end
9d0c9b21ce876a5ae51af951ba9110507b420e34
367134ba5a65885e863bdc4507601606690974c1
/src/measure_theory/group.lean
5018e461c019d4ef672f1e1ce4a66e55a7e2a5ff
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
8,303
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.integration /-! # Measures on Groups We develop some properties of measures on (topological) groups * We define properties on measures: left and right invariant measures. * We define the measure `μ.inv : A ↦ μ(A⁻¹)` and show that it is right invariant iff `μ` is left invariant. -/ noncomputable theory open_locale ennreal open has_inv set function measure_theory.measure namespace measure_theory variables {G : Type*} section variables [measurable_space G] [has_mul G] /-- A measure `μ` on a topological group is left invariant if the measure of left translations of a set are equal to the measure of the set itself. To left translate sets we use preimage under left multiplication, since preimages are nicer to work with than images. -/ @[to_additive "A measure on a topological group is left invariant if the measure of left translations of a set are equal to the measure of the set itself. To left translate sets we use preimage under left addition, since preimages are nicer to work with than images."] def is_mul_left_invariant (μ : set G → ℝ≥0∞) : Prop := ∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, g * h) ⁻¹' A) = μ A /-- A measure `μ` on a topological group is right invariant if the measure of right translations of a set are equal to the measure of the set itself. To right translate sets we use preimage under right multiplication, since preimages are nicer to work with than images. -/ @[to_additive "A measure on a topological group is right invariant if the measure of right translations of a set are equal to the measure of the set itself. To right translate sets we use preimage under right addition, since preimages are nicer to work with than images."] def is_mul_right_invariant (μ : set G → ℝ≥0∞) : Prop := ∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, h * g) ⁻¹' A) = μ A end namespace measure variables [measurable_space G] @[to_additive] lemma map_mul_left_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G] {μ : measure G} : (∀ g, measure.map ((*) g) μ = μ) ↔ is_mul_left_invariant μ := begin apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A, apply forall_congr, intro hA, rw [map_apply (measurable_mul_left g) hA] end @[to_additive] lemma map_mul_right_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G] {μ : measure G} : (∀ g, measure.map (λ h, h * g) μ = μ) ↔ is_mul_right_invariant μ := begin apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A, apply forall_congr, intro hA, rw [map_apply (measurable_mul_right g) hA] end /-- The measure `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/ @[to_additive "The measure `A ↦ μ (- A)`, where `- A` is the pointwise negation of `A`."] protected def inv [has_inv G] (μ : measure G) : measure G := measure.map inv μ variables [group G] [topological_space G] [topological_group G] [borel_space G] @[to_additive] lemma inv_apply (μ : measure G) {s : set G} (hs : measurable_set s) : μ.inv s = μ s⁻¹ := measure.map_apply measurable_inv hs @[simp, to_additive] protected lemma inv_inv (μ : measure G) : μ.inv.inv = μ := begin ext1 s hs, rw [μ.inv.inv_apply hs, μ.inv_apply, set.inv_inv], exact measurable_inv hs end variables {μ : measure G} @[to_additive] lemma regular.inv [t2_space G] (hμ : μ.regular) : μ.inv.regular := hμ.map (homeomorph.inv G) end measure section inv variables [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} @[simp, to_additive] lemma regular_inv_iff [t2_space G] : μ.inv.regular ↔ μ.regular := by { refine ⟨λ h, _, measure.regular.inv⟩, rw ←μ.inv_inv, exact measure.regular.inv h } @[to_additive] lemma is_mul_left_invariant.inv (h : is_mul_left_invariant μ) : is_mul_right_invariant μ.inv := begin intros g A hA, rw [μ.inv_apply (measurable_mul_right g hA), μ.inv_apply hA], convert h g⁻¹ (measurable_inv hA) using 2, simp only [←preimage_comp, ← inv_preimage], apply preimage_congr, intro h, simp only [mul_inv_rev, comp_app, inv_inv] end @[to_additive] lemma is_mul_right_invariant.inv (h : is_mul_right_invariant μ) : is_mul_left_invariant μ.inv := begin intros g A hA, rw [μ.inv_apply (measurable_mul_left g hA), μ.inv_apply hA], convert h g⁻¹ (measurable_inv hA) using 2, simp only [←preimage_comp, ← inv_preimage], apply preimage_congr, intro h, simp only [mul_inv_rev, comp_app, inv_inv] end @[simp, to_additive] lemma is_mul_right_invariant_inv : is_mul_right_invariant μ.inv ↔ is_mul_left_invariant μ := ⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩ @[simp, to_additive] lemma is_mul_left_invariant_inv : is_mul_left_invariant μ.inv ↔ is_mul_right_invariant μ := ⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩ end inv variables [measurable_space G] [topological_space G] [borel_space G] {μ : measure G} section group variables [group G] [topological_group G] /-! Properties of regular left invariant measures -/ @[to_additive measure_theory.measure.is_add_left_invariant.null_iff_empty] lemma is_mul_left_invariant.null_iff_empty (hμ : μ.regular) (h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ := begin obtain ⟨K, hK, h2K⟩ := hμ.exists_compact_not_null.mpr h3μ, refine ⟨λ h, _, λ h, by simp [h]⟩, apply classical.by_contradiction, -- `by_contradiction` is very slow refine mt (λ h2s, _) h2K, rw [← ne.def, ne_empty_iff_nonempty] at h2s, cases h2s with y hy, obtain ⟨t, -, h1t, h2t⟩ := hK.elim_finite_subcover_image (show ∀ x ∈ @univ G, is_open ((λ y, x * y) ⁻¹' s), from λ x _, (continuous_mul_left x).is_open_preimage _ hs) _, { rw [← nonpos_iff_eq_zero], refine (measure_mono h2t).trans _, refine (measure_bUnion_le h1t.countable _).trans_eq _, simp_rw [h2μ _ hs.measurable_set], rw [h, tsum_zero] }, { intros x _, simp_rw [mem_Union, mem_preimage], use [y * x⁻¹, mem_univ _], rwa [inv_mul_cancel_right] } end @[to_additive measure_theory.measure.is_add_left_invariant.null_iff] lemma is_mul_left_invariant.null_iff (hμ : regular μ) (h2μ : is_mul_left_invariant μ) {s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ ∨ μ = 0 := begin by_cases h3μ : μ = 0, { simp [h3μ] }, simp only [h3μ, or_false], exact h2μ.null_iff_empty hμ h3μ hs, end @[to_additive measure_theory.measure.is_add_left_invariant.measure_ne_zero_iff_nonempty] lemma is_mul_left_invariant.measure_ne_zero_iff_nonempty (hμ : regular μ) (h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : μ s ≠ 0 ↔ s.nonempty := by simp_rw [← ne_empty_iff_nonempty, ne.def, h2μ.null_iff_empty hμ h3μ hs] /-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function `f` is 0 iff `f` is 0. -/ -- @[to_additive] (fails for now) lemma lintegral_eq_zero_of_is_mul_left_invariant (hμ : regular μ) (h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {f : G → ℝ≥0∞} (hf : continuous f) : ∫⁻ x, f x ∂μ = 0 ↔ f = 0 := begin split, swap, { rintro rfl, simp_rw [pi.zero_apply, lintegral_zero] }, intro h, contrapose h, simp_rw [funext_iff, not_forall, pi.zero_apply] at h, cases h with x hx, obtain ⟨r, h1r, h2r⟩ : ∃ r : ℝ≥0∞, 0 < r ∧ r < f x := exists_between (pos_iff_ne_zero.mpr hx), have h3r := hf.is_open_preimage (Ioi r) is_open_Ioi, let s := Ioi r, rw [← ne.def, ← pos_iff_ne_zero], have : 0 < r * μ (f ⁻¹' Ioi r), { rw ennreal.mul_pos, refine ⟨h1r, _⟩, rw [pos_iff_ne_zero, h2μ.measure_ne_zero_iff_nonempty hμ h3μ h3r], exact ⟨x, h2r⟩ }, refine this.trans_le _, rw [← set_lintegral_const, ← lintegral_indicator _ h3r.measurable_set], apply lintegral_mono, refine indicator_le (λ y, le_of_lt), end end group end measure_theory
1b80c98f3f1e024a7f89c8264da286490bdfe403
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Lean/Elab/Term.lean
921896caab36c0dc02fcc0ffd8ca25acb126b0a3
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,659
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.Sorry import Init.Lean.Structure import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.AppBuilder import Init.Lean.Meta.SynthInstance import Init.Lean.Meta.Tactic.Util import Init.Lean.Hygiene import Init.Lean.Util.RecDepth import Init.Lean.Elab.Log import Init.Lean.Elab.Alias import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Level namespace Lean namespace Elab namespace Term structure Context extends Meta.Context := (fileName : String) (fileMap : FileMap) (cmdPos : String.Pos) (currNamespace : Name) (declName? : Option Name := none) (levelNames : List Name := []) (openDecls : List OpenDecl := []) (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) (errToSorry : Bool := true) /- If `macroStackAtErr == true`, we include it in error messages. -/ (macroStackAtErr : Bool := true) /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind -- typeclass instance search | typeClass -- Similar to typeClass, but error messages are different, -- we use "type mismatch" or "application type mismatch" (when `f?` is some) instead of "failed to synthesize" | coe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (macroStack : MacroStack) -- type defaulting (currently: defaulting numeric literals to `Nat`) | withDefault (defaultVal : Expr) structure SyntheticMVarDecl := (mvarId : MVarId) (ref : Syntax) (kind : SyntheticMVarKind) structure State extends Meta.State := (syntheticMVars : List SyntheticMVarDecl := []) (messages : MessageLog := {}) (instImplicitIdx : Nat := 1) (anonymousIdx : Nat := 1) (nextMacroScope : Nat := firstFrontendMacroScope + 1) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩ /- The Term elaborator monad has a special kind of exception `Exception.postpone` which is used by an elaboration function to notify the main driver that it should be tried later. Remark: `Exception.postpone` is used only when `mayPostpone == true` in the `Context`. -/ inductive Exception | ex : Elab.Exception → Exception | postpone : Exception instance Exception.inhabited : Inhabited Exception := ⟨Exception.postpone⟩ instance Exception.hasToString : HasToString Exception := ⟨fun ex => match ex with | Exception.postpone => "postponed" | Exception.ex ex => toString ex⟩ /- Term elaborator Monad. In principle, we could track statically which methods may postpone or not by having adding a Boolean parameter `mayPostpone` to `TermElabM`. This would be useful to ensure that `Exception.postpone` does not leak to `CommandElabM`, but we abandoned this design because it adds unnecessary complexity. -/ abbrev TermElabM := ReaderT Context (EStateM Exception State) abbrev TermElab := Syntax → Option Expr → TermElabM Expr instance TermElabM.inhabited {α} : Inhabited (TermElabM α) := ⟨throw $ Exception.postpone⟩ abbrev TermElabResult := EStateM.Result Message State Expr instance TermElabResult.inhabited : Inhabited TermElabResult := ⟨EStateM.Result.ok (arbitrary _) (arbitrary _)⟩ /-- Execute `x`, save resulting expression and new state. If `x` fails, then it also stores exception and new state. Remark: we do not capture `Exception.postpone`. -/ @[inline] def observing (x : TermElabM Expr) : TermElabM TermElabResult := fun ctx s => match x ctx s with | EStateM.Result.error (Exception.ex (Elab.Exception.error errMsg)) newS => EStateM.Result.ok (EStateM.Result.error errMsg newS) s | EStateM.Result.error Exception.postpone _ => EStateM.Result.error Exception.postpone s | EStateM.Result.error ex newS => EStateM.Result.error ex newS | EStateM.Result.ok e newS => EStateM.Result.ok (EStateM.Result.ok e newS) s /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult) : TermElabM Expr := match result with | EStateM.Result.ok e s => do set s; pure e | EStateM.Result.error errMsg s => do set s; throw (Exception.ex (Elab.Exception.error errMsg)) def getEnv : TermElabM Environment := do s ← get; pure s.env def getMCtx : TermElabM MetavarContext := do s ← get; pure s.mctx def getLCtx : TermElabM LocalContext := do ctx ← read; pure ctx.lctx def getLocalInsts : TermElabM LocalInstances := do ctx ← read; pure ctx.localInstances def getOptions : TermElabM Options := do ctx ← read; pure ctx.config.opts def setEnv (env : Environment) : TermElabM Unit := modify $ fun s => { env := env, .. s } def setMCtx (mctx : MetavarContext) : TermElabM Unit := modify $ fun s => { mctx := mctx, .. s } def addContext (msg : MessageData) : TermElabM MessageData := do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; pure (MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msg) instance monadLog : MonadLog TermElabM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } /-- Throws an error with the given `msgData` and extracting position information from `ref`. If `ref` does not contain position information, then use `cmdPos` -/ def throwError {α} (ref : Syntax) (msgData : MessageData) : TermElabM α := do ctx ← read; let ref := getBetterRef ref ctx.macroStack; let msgData := if ctx.macroStackAtErr then addMacroStack msgData ctx.macroStack else msgData; msg ← mkMessage msgData MessageSeverity.error ref; throw (Exception.ex (Elab.Exception.error msg)) def throwUnsupportedSyntax {α} : TermElabM α := throw (Exception.ex Elab.Exception.unsupportedSyntax) @[inline] def withIncRecDepth {α} (ref : Syntax) (x : TermElabM α) : TermElabM α := do ctx ← read; when (ctx.currRecDepth == ctx.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x protected def getCurrMacroScope : TermElabM MacroScope := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : TermElabM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : TermElabM α) : TermElabM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance monadQuotation : MonadQuotation TermElabM := { getCurrMacroScope := Term.getCurrMacroScope, getMainModule := Term.getMainModule, withFreshMacroScope := @Term.withFreshMacroScope } unsafe def mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[init mkTermElabAttribute] constant termElabAttribute : KeyedDeclsAttribute TermElab := arbitrary _ /-- 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 | fieldIdx (i : Nat) | fieldName (name : String) | getOp (idx : Syntax) instance LVal.hasToString : HasToString LVal := ⟨fun p => match p with | LVal.fieldIdx i => toString i | LVal.fieldName n => n | LVal.getOp idx => "[" ++ toString idx ++ "]"⟩ def getDeclName? : TermElabM (Option Name) := do ctx ← read; pure ctx.declName? def getCurrNamespace : TermElabM Name := do ctx ← read; pure ctx.currNamespace def getOpenDecls : TermElabM (List OpenDecl) := do ctx ← read; pure ctx.openDecls def getTraceState : TermElabM TraceState := do s ← get; pure s.traceState def setTraceState (traceState : TraceState) : TermElabM Unit := modify $ fun s => { traceState := traceState, .. s } def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := do mctx ← getMCtx; pure $ mctx.isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := do mctx ← getMCtx; pure $ mctx.getDecl mvarId def assignExprMVar (mvarId : MVarId) (val : Expr) : TermElabM Unit := modify $ fun s => { mctx := s.mctx.assignExpr mvarId val, .. s } def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : TermElabM Unit := do ctx ← read; s ← get; logInfo ref $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } $ MessageData.tagged cls msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : TermElabM Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls ref (msg ()) def logDbgTrace (msg : MessageData) : TermElabM Unit := do trace `Elab.debug Syntax.missing $ fun _ => msg /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do s ← get; when s.messages.hasErrors $ throwError Syntax.missing "Error(s)" @[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := trace cls Syntax.missing msg def dbgTrace {α} [HasToString α] (a : α) : TermElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () /-- Auxiliary function for `liftMetaM` -/ private def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) /-- Auxiliary function for `liftMetaM` -/ private def fromMetaException (ctx : Context) (ref : Syntax) (ex : Meta.Exception) : Exception := Exception.ex $ Elab.Exception.error $ mkMessageAux ctx ref ex.toMessageData MessageSeverity.error /-- Auxiliary function for `liftMetaM` -/ private def fromMetaState (ref : Syntax) (ctx : Context) (s : State) (newS : Meta.State) (oldTraceState : TraceState) : State := let traces := newS.traceState.traces; let messages := traces.foldl (fun (messages : MessageLog) trace => messages.add (mkMessageAux ctx ref trace MessageSeverity.information)) s.messages; { toState := { traceState := oldTraceState, .. newS }, messages := messages, .. s } @[inline] def liftMetaM {α} (ref : Syntax) (x : MetaM α) : TermElabM α := fun ctx s => let oldTraceState := s.traceState; match x ctx.toContext { traceState := {}, .. s.toState } with | EStateM.Result.ok a newS => EStateM.Result.ok a (fromMetaState ref ctx s newS oldTraceState) | EStateM.Result.error ex newS => EStateM.Result.error (fromMetaException ctx ref ex) (fromMetaState ref ctx s newS oldTraceState) def ppGoal (ref : Syntax) (mvarId : MVarId) : TermElabM Format := liftMetaM ref $ Meta.ppGoal mvarId def isType (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isType e def isTypeFormer (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isTypeFormer e def isDefEqNoConstantApprox (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.approxDefEq $ Meta.isDefEq t s def isDefEq (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.fullApproxDefEq $ Meta.isDefEq t s def inferType (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.inferType e def whnf (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnf e def whnfForall (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfForall e def whnfCore (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfCore e def unfoldDefinition? (ref : Syntax) (e : Expr) : TermElabM (Option Expr) := liftMetaM ref $ Meta.unfoldDefinition? e def instantiateMVars (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.instantiateMVars e def isClass (ref : Syntax) (t : Expr) : TermElabM (Option Name) := liftMetaM ref $ Meta.isClass t def mkFreshLevelMVar (ref : Syntax) : TermElabM Level := liftMetaM ref $ Meta.mkFreshLevelMVar def mkFreshExprMVar (ref : Syntax) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := match type? with | some type => liftMetaM ref $ Meta.mkFreshExprMVar type userName? kind | none => liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; type ← Meta.mkFreshExprMVar (mkSort u); Meta.mkFreshExprMVar type userName? kind def mkFreshTypeMVar (ref : Syntax) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; Meta.mkFreshExprMVar (mkSort u) userName? kind def getLevel (ref : Syntax) (type : Expr) : TermElabM Level := liftMetaM ref $ Meta.getLevel type def mkForall (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkForall xs e def mkForallUsedOnly (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM (Expr × Nat) := liftMetaM ref $ Meta.mkForallUsedOnly xs e def mkLambda (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkLambda xs e def mkLet (ref : Syntax) (x : Expr) (e : Expr) : TermElabM Expr := mkLambda ref #[x] e def trySynthInstance (ref : Syntax) (type : Expr) : TermElabM (LOption Expr) := liftMetaM ref $ Meta.trySynthInstance type def mkAppM (ref : Syntax) (constName : Name) (args : Array Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkAppM constName args def mkExpectedTypeHint (ref : Syntax) (e : Expr) (expectedType : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkExpectedTypeHint e expectedType def decLevel? (ref : Syntax) (u : Level) : TermElabM (Option Level) := liftMetaM ref $ Meta.decLevel? u def decLevel (ref : Syntax) (u : Level) : TermElabM Level := do u? ← decLevel? ref u; match u? with | some u => pure u | none => throwError ref ("invalid universe level, " ++ u ++ " is not greater than 0") /- This function is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (ref : Syntax) (type : Expr) : TermElabM Level := do u ← getLevel ref type; decLevel ref u @[inline] def savingMCtx {α} (x : TermElabM α) : TermElabM α := do mctx ← getMCtx; finally x (modify $ fun s => { mctx := mctx, .. s }) def liftLevelM {α} (x : LevelElabM α) : TermElabM α := fun ctx s => match (x { .. ctx }).run { .. s } with | EStateM.Result.ok a newS => EStateM.Result.ok a { mctx := newS.mctx, ngen := newS.ngen, .. s } | EStateM.Result.error ex newS => EStateM.Result.error (Exception.ex ex) s def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx @[inline] def withConfig {α} (f : Meta.Config → Meta.Config) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { config := f ctx.config, .. ctx }) x @[inline] def withTransparency {α} (mode : Meta.TransparencyMode) (x : TermElabM α) : TermElabM α := withConfig (fun config => { transparency := mode, .. config }) x @[inline] def withReducible {α} (x : TermElabM α) : TermElabM α := withTransparency Meta.TransparencyMode.reducible x /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) 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 (ref : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := modify $ fun s => { syntheticMVars := { mvarId := mvarId, ref := ref, kind := kind } :: s.syntheticMVars, .. s } /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ @[inline] def withoutPostponing {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { mayPostpone := false, .. ctx }) 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. -/ def levelMVarToParam (e : Expr) : TermElabM Expr := do ctx ← read; mctx ← getMCtx; let r := mctx.levelMVarToParam (fun n => ctx.levelNames.elem n) e; modify $ fun s => { mctx := r.mctx, .. s }; pure r.expr /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshAnonymousName : TermElabM Name := do s ← get; let anonymousIdx := s.anonymousIdx; modify $ fun s => { anonymousIdx := s.anonymousIdx + 1, .. s}; pure $ (`_a).appendIndexAfter anonymousIdx /-- 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 `mkFreshAnonymousName`. -/ def mkFreshAnonymousIdent (ref : Syntax) : TermElabM Syntax := do n ← mkFreshAnonymousName; pure $ mkIdentFrom ref n /-- Auxiliary method for creating binder names for local instances. Users expect them to be named as `_inst_<idx>`. -/ def mkFreshInstanceName : TermElabM Name := do s ← get; let instIdx := s.instImplicitIdx; modify $ fun s => { instImplicitIdx := s.instImplicitIdx + 1, .. s}; pure $ (`_inst).appendIndexAfter instIdx private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Auxiliary function for expandind the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ private partial def expandCDot : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope $ do id ← `(a); modify $ fun s => s.push id; pure id else do args ← args.mapM expandCDot; pure $ Syntax.node k args | stx => pure stx /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := if hasCDot stx then do (newStx, binders) ← (expandCDot stx).run #[]; `(fun $binders* => $newStx) else pure none def mkFreshFVarId : TermElabM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, .. s }; pure id def withLocalDecl {α} (ref : Syntax) (n : Name) (binderInfo : BinderInfo) (type : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLocalDecl fvarId n type binderInfo; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar }, .. ctx }) $ k fvar | none => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ k fvar def withLetDecl {α} (ref : Syntax) (n : Name) (type : Expr) (val : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar }, .. ctx }) $ k fvar | none => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ k fvar def throwTypeMismatchError {α} (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; match f? with | none => let msg : MessageData := "type mismatch" ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType ++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType ++ extraMsg; throwError ref msg | some f => do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; throwError ref $ Meta.Exception.mkAppTypeMismatchMessage f e { env := env, mctx := mctx, lctx := lctx, opts := opts } ++ extraMsg @[inline] def withoutMacroStackAtErr {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { macroStackAtErr := false, .. ctx }) 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 (ref : Syntax) (instMVar : MVarId) : TermElabM Bool := do instMVarDecl ← getMVarDecl instMVar; let type := instMVarDecl.type; type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => do condM (isExprMVarAssigned instMVar) (do oldVal ← instantiateMVars ref (mkMVar instMVar); unlessM (isDefEq ref oldVal val) $ throwError ref $ "synthesized type class instance is not definitionally equal to expression " ++ "inferred by typing rules, synthesized" ++ indentExpr val ++ Format.line ++ "inferred" ++ indentExpr oldVal) (assignExprMVar instMVar val); pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /-- 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 β] : β ``` -/ def tryCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := condM (isDefEq ref expectedType eType) (pure e) $ do u ← getLevel ref eType; v ← getLevel ref expectedType; let coeTInstType := mkAppN (mkConst `CoeT [u, v]) #[eType, e, expectedType]; mvar ← mkFreshExprMVar ref coeTInstType MetavarKind.synthetic; let eNew := mkAppN (mkConst `coe [u, v]) #[eType, expectedType, e, mvar]; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ do unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId (SyntheticMVarKind.coe expectedType eType e f?); pure eNew) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwTypeMismatchError ref expectedType eType e f? errMsg.data | _ => throwTypeMismatchError ref expectedType eType e f?) private def isTypeApp? (ref : Syntax) (type : Expr) : TermElabM (Option (Expr × Expr)) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => pure (some (m, α)) | _ => pure none structure IsMonadResult := (m : Expr) (α : Expr) (inst : Expr) private def isMonad? (ref : Syntax) (type : Expr) : TermElabM (Option IsMonadResult) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => catch (do monadType ← mkAppM ref `Monad #[m]; result ← trySynthInstance ref monadType; match result with | LOption.some inst => pure (some { m := m, α := α, inst := inst }) | _ => pure none) (fun _ => pure none) | _ => pure none def synthesizeInst (ref : Syntax) (type : Expr) : TermElabM Expr := do type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => pure val | LOption.undef => throwError ref ("failed to synthesize instance" ++ indentExpr type) | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if the head of `α` nor ‵β` is not a metavariable. -/ private def tryPureCoe? (ref : Syntax) (m β α a : Expr) : TermElabM (Option Expr) := if β.getAppFn.isMVar || α.getAppFn.isMVar then pure none else catch (do aNew ← tryCoe ref β α a none; aNew ← liftMetaM ref $ Meta.mkPure m aNew; pure $ some aNew) (fun _ => pure none) /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β` where `n` is a Monad, 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 `α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we rely on `tryCoe`, and the instances ``` instance coeMethod {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] : Coe (m α) (m β) instance pureCoeDepProp {m : Type → Type v} [HasPure m] {p : Prop} [Decidable p] : CoeDep (m Prop) (pure p) (m Bool) ``` 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 : HasMonadLiftT m n] {α : Type u_1}, m α → n α ``` 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} [HasMonadLiftT 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} [HasLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[HasLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ def tryLiftAndCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do eType ← instantiateMVars ref eType; some ⟨n, β, monadInst⟩ ← isMonad? ref expectedType | tryCoe ref expectedType eType e f?; β ← instantiateMVars ref β; eNew? ← tryPureCoe? ref n β eType e; match eNew? with | some eNew => pure eNew | none => do some (m, α) ← isTypeApp? ref eType | tryCoe ref expectedType eType e f?; condM (isDefEq ref m n) (tryCoe ref expectedType eType e f?) $ catch (do -- Construct lift from `m` to `n` hasMonadLiftType ← mkAppM ref `HasMonadLiftT #[m, n]; hasMonadLiftVal ← synthesizeInst ref hasMonadLiftType; u_1 ← getDecLevel ref α; u_2 ← getDecLevel ref eType; u_3 ← getDecLevel ref expectedType; let eNew := mkAppN (Lean.mkConst `liftM [u_1, u_2, u_3]) #[m, n, hasMonadLiftVal, α, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 2 worked (do u ← getLevel ref α; v ← getLevel ref β; let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst `CoeT [u, v]) #[α, mkBVar 0, β]; coeTInstVal ← synthesizeInst ref coeTInstType; let eNew := mkAppN (Lean.mkConst `liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, hasMonadLiftVal, coeTInstVal, monadInst, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 3 worked (throwTypeMismatchError ref expectedType eType e f?))) (fun _ => throwTypeMismatchError ref expectedType eType e f?) /-- 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 (ref : Syntax) (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) : TermElabM Expr := match expectedType? with | none => pure e | some expectedType => /- Recall that constant approximation is used to solve constraint of the form ``` ?m t =?= s ``` where `t` is an arbitrary term, by assigning `?m := fun _ => s` This approximation when not used carefully produces bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, not first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure 0; f () ``` with expected type `StateT Nat Id Nat`. In this example, the following unification contraint is generated. ``` ?m () (?n ()) =?= StateT Nat Id Nat ``` It is not a higher-order pattern, and first-order approximation fails. However, constant approximation solves it by assigning ``` ?m := fun _ => StateT Nat Id ?n := fun _ => Nat ``` Note that `f`s type is `(x : ?α) -> ?m x (?n x)`. The metavariables `?m` and `?n` may depend on `x`. The `isDefEqNoConstantApprox` fails to unify the expected and inferred types. Then, `tryLiftAndCoe` first tries the monadic extensions, and then falls back to `isDefEq` which enables all approximations. -/ condM (isDefEqNoConstantApprox ref eType expectedType) (pure e) (tryLiftAndCoe ref 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 (ref : Syntax) (expectedType? : Option Expr) (e : Expr) : TermElabM Expr := match expectedType? with | none => pure e | _ => do eType ← inferType ref e; ensureHasTypeAux ref expectedType? eType e private def exceptionToSorry (ref : Syntax) (errMsg : Message) (expectedType? : Option Expr) : TermElabM Expr := do expectedType : Expr ← match expectedType? with | none => mkFreshTypeMVar ref | some expectedType => pure expectedType; u ← getLevel ref expectedType; -- TODO: should be `(sorryAx.{$u} $expectedType true) when we support antiquotations at that place let syntheticSorry := mkApp2 (mkConst `sorryAx [u]) expectedType (mkConst `Bool.true); unless errMsg.data.hasSyntheticSorry $ logMessage errMsg; pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do ctx ← read; when ctx.mayPostpone $ throw Exception.postpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do when e.getAppFn.isMVar $ tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace `Elab.postpone stx $ fun _ => stx ++ " : " ++ expectedType?; mvar ← mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque; ctx ← read; registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed ctx.macroStack); pure mvar /- 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 : State) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List TermElab → TermElabM Expr | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (elabFn::elabFns) => catch (elabFn stx expectedType?) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => do ctx ← read; if ctx.errToSorry then exceptionToSorry stx errMsg expectedType? else throw ex | Exception.ex Elab.Exception.unsupportedSyntax => do set s; elabUsingElabFnsAux elabFns | Exception.postpone => if catchExPostpone then do /- 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. -/ set s; postponeElabTerm stx expectedType? else throw ex) def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do s ← get; let table := (termElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns | none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented") instance : MonadMacroAdapter TermElabM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax} private def isExplicit (stx : Syntax) : Bool := match_syntax stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == `Lean.Parser.Term.app && isExplicit (stx.getArg 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_syntax stx with | `(fun $binders* => $body) => binders.any $ fun b => b.isOfKind `Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. -/ def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then pure none else match expectedType? with | some expectedType => do expectedType ← whnfForall stx expectedType; match expectedType with | Expr.forallE _ _ _ c => pure $ if c.binderInfo.isExplicit then none else some expectedType | _ => pure $ none | _ => pure $ none def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (fvars : Array Expr) : TermElabM Expr := do body ← elabUsingElabFns stx expectedType catchExPostpone; -- body ← ensureHasType stx expectedType body; r ← mkLambda stx fvars body; trace `Elab.implicitForall stx $ fun _ => r; pure r partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) : Expr → Array Expr → TermElabM Expr | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope $ do n ← MonadQuotation.addMacroScope n; withLocalDecl stx n c.binderInfo d $ fun fvar => do type ← whnfForall stx (b.instantiate1 fvar); elabImplicitLambda type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | stx => withFreshMacroScope $ withIncRecDepth stx $ do trace `Elab.step stx $ fun _ => expectedType? ++ " " ++ stx; s ← get; stxNew? ← catch (do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => match ex with | Exception.ex Elab.Exception.unsupportedSyntax => pure none | _ => throw ex); match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabTermAux stxNew | _ => do implicit? ← if implicitLambda then useImplicitLambda? stx expectedType? else pure none; match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType #[] | none => elabUsingElabFns stx expectedType? catchExPostpone /-- 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. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := elabTermAux expectedType? catchExPostpone true stx def elabTermWithoutImplicitLambdas (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := do elabTermAux expectedType? catchExPostpone false stx /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do stx' ← exp stx; withMacroExpansion stx stx' $ elabTerm stx' expectedType? @[inline] def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts, .. ctx }) x def resetSynthInstanceCache : TermElabM Unit := modify $ fun s => { cache := { synthInstance := {}, .. s.cache }, .. s } @[inline] def resettingSynthInstanceCache {α} (x : TermElabM α) : TermElabM α := do s ← get; let savedSythInstance := s.cache.synthInstance; resetSynthInstanceCache; finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s }) @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : TermElabM α) : TermElabM α := if b then resettingSynthInstanceCache x else x /-- Execute `x` using the given metavariable's `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) (x : TermElabM α) : TermElabM α := do mvarDecl ← getMVarDecl mvarId; ctx ← read; let needReset := ctx.localInstances == mvarDecl.localInstances; withLCtx mvarDecl.lctx mvarDecl.localInstances $ resettingSynthInstanceCacheWhen needReset x def mkInstMVar (ref : Syntax) (type : Expr) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.synthetic; let mvarId := mvar.mvarId!; unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref 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 (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do β ← mkFreshTypeMVar ref; u ← getLevel ref α; v ← getLevel ref β; let coeSortInstType := mkAppN (Lean.mkConst `CoeSort [u, v]) #[α, β]; mvar ← mkFreshExprMVar ref coeSortInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ condM (synthesizeInstMVarCore ref mvarId) (pure $ mkAppN (Lean.mkConst `coeSort [u, v]) #[α, β, a, mvar]) (throwError ref "type expected")) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("type expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "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 (ref : Syntax) (e : Expr) : TermElabM Expr := condM (isType ref e) (pure e) (do eType ← inferType ref e; u ← mkFreshLevelMVar ref; condM (isDefEq ref eType (mkSort u)) (pure e) (tryCoeSort ref eType e)) /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do u ← mkFreshLevelMVar stx; type ← elabTerm stx (mkSort u); ensureType stx type def addDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; match env.addDecl decl with | Except.ok env => setEnv env | Except.error kex => do opts ← getOptions; throwError ref (kex.toMessageData opts) def compileDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; opts ← getOptions; match env.compileDecl opts decl with | Except.ok env => setEnv env | Except.error kex => throwError ref (kex.toMessageData opts) private partial def mkAuxNameAux (env : Environment) (base : Name) : Nat → Name | i => let candidate := base.appendIndexAfter i; if env.contains candidate then mkAuxNameAux (i+1) else candidate def mkAuxName (ref : Syntax) (suffix : Name) : TermElabM Name := do env ← getEnv; ctx ← read; match ctx.declName? with | none => throwError ref "auxiliary declaration cannot be created when declaration name is not available" | some declName => pure $ mkAuxNameAux env (declName ++ suffix) 1 /- ======================================= Builtin elaboration functions ======================================= -/ @[builtinTermElab «prop»] def elabProp : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «sort»] def elabSort : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «type»] def elabTypeStx : TermElab := fun _ _ => pure $ mkSort levelOne @[builtinTermElab «hole»] def elabHole : TermElab := fun stx expectedType? => mkFreshExprMVar stx expectedType? @[builtinTermElab «namedHole»] def elabNamedHole : TermElab := fun stx expectedType? => let name := stx.getIdAt 1; mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque name def mkTacticMVar (ref : Syntax) (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.syntheticOpaque `main; let mvarId := mvar.mvarId!; registerSyntheticMVar ref mvarId $ SyntheticMVarKind.tactic tacticCode; pure mvar @[builtinTermElab tacticBlock] def elabTacticBlock : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid tactic block, expected type has not been provided") @[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid 'by' tactic, expected type has not been provided") /-- Main loop for `mkPairs`. -/ private partial def mkPairsAux (elems : Array Syntax) : Nat → Syntax → MacroM Syntax | i, acc => if i > 0 then do let i := i - 1; let elem := elems.get! i; acc ← `(Prod.mk $elem $acc); mkPairsAux i acc else pure acc /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ def mkPairs (elems : Array Syntax) : MacroM Syntax := mkPairsAux elems (elems.size - 1) elems.back /-- Try to expand `·` notation, and if successful elaborate result. This method is used to elaborate the Lean parentheses notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ private def elabCDot (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do stx? ← liftMacroM $ expandCDot? stx; match stx? with | some stx' => withMacroExpansion stx stx' (elabTerm stx' expectedType?) | none => elabTerm stx expectedType? @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => let ref := stx; match_syntax ref with | `(()) => pure $ Lean.mkConst `Unit.unit | `(($e : $type)) => do type ← elabType type; e ← elabCDot e type; ensureHasType ref type e | `(($e)) => elabCDot e expectedType? | `(($e, $es*)) => do pairs ← liftMacroM $ mkPairs (#[e] ++ es.getEvenElems); withMacroExpansion stx pairs (elabTerm pairs expectedType?) | _ => throwError stx "unexpected parentheses notation" @[builtinTermElab «listLit»] def elabListLit : TermElab := fun stx expectedType? => do let openBkt := stx.getArg 0; let args := stx.getArg 1; let closeBkt := stx.getArg 2; let consId := mkTermIdFrom openBkt `List.cons; let nilId := mkTermIdFrom closeBkt `List.nil; let newStx := args.foldSepRevArgs (fun arg r => mkAppStx consId #[arg, r]) nilId; withMacroExpansion stx newStx $ elabTerm newStx expectedType? @[builtinTermElab «arrayLit»] def elabArrayLit : TermElab := fun stx expectedType? => do match_syntax stx with | `(#[$args*]) => do newStx ← `(List.toArray [$args*]); withMacroExpansion stx newStx (elabTerm newStx expectedType?) | _ => throwError stx "unexpected array literal syntax" private partial def resolveLocalNameAux (lctx : LocalContext) : Name → List String → Option (Expr × List String) | n, projs => match lctx.findFromUserName? n with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => resolveLocalNameAux pre (s::projs) | _ => none private def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do lctx ← getLCtx; pure $ resolveLocalNameAux lctx n [] /- Return true iff `stx` is a `Term.id`, and it is local variable. -/ def isLocalTermId? (stx : Syntax) (relaxed : Bool := false) : TermElabM (Option Expr) := match stx.isTermId? relaxed with | some (Syntax.ident _ _ val _, _) => do r? ← resolveLocalName val; match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none private def mkFreshLevelMVars (ref : Syntax) (num : Nat) : TermElabM (List Level) := num.foldM (fun _ us => do u ← mkFreshLevelMVar ref; pure $ u::us) [] /-- 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 (ref : Syntax) (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do env ← getEnv; match env.find? constName with | none => throwError ref ("unknown constant '" ++ constName ++ "'") | some cinfo => if explicitLevels.length > cinfo.lparams.length then throwError ref ("too many explicit universe levels") else do let numMissingLevels := cinfo.lparams.length - explicitLevels.length; us ← mkFreshLevelMVars ref numMissingLevels; pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (ref : Syntax) (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do env ← getEnv; candidates.foldlM (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. const ← mkConst ref constName explicitLevels; pure $ (const, projs) :: result) [] def resolveGlobalName (n : Name) : TermElabM (List (Name × List String)) := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; pure (Lean.Elab.resolveGlobalName env currNamespace openDecls n) def resolveName (ref : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do result? ← resolveLocalName n; match result? with | some (e, projs) => do unless explicitLevels.isEmpty $ throwError ref ("invalid use of explicit universe parameters, '" ++ toString e.fvarId! ++ "' is a local"); pure [(e, projs)] | none => let process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do { when candidates.isEmpty $ do { mainModule ← getMainModule; let view := extractMacroScopes n; throwError ref ("unknown identifier '" ++ view.format mainModule ++ "'") }; mkConsts ref candidates explicitLevels }; if preresolved.isEmpty then do r ← resolveGlobalName n; process r else process preresolved @[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ => throwError stx "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)" /- A raw literal is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. TODO: check whether we still need wrapper nodes around literals. -/ @[builtinTermElab strLit] def elabRawStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwError stx "ill-formed syntax" @[builtinTermElab str] def elabStr : TermElab := fun stx expectedType? => elabRawStrLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab numLit] def elabRawNumLit : TermElab := fun stx expectedType? => do let ref := stx; val ← match stx.isNatLit? with | some val => pure (mkNatLit val) | none => throwError stx "ill-formed syntax"; typeMVar ← mkFreshTypeMVar ref MetavarKind.synthetic; registerSyntheticMVar ref typeMVar.mvarId! (SyntheticMVarKind.withDefault (Lean.mkConst `Nat)); match expectedType? with | some expectedType => do isDefEq ref expectedType typeMVar; pure () | _ => pure (); u ← getLevel ref typeMVar; u ← decLevel ref u; mvar ← mkInstMVar ref (mkApp (Lean.mkConst `HasOfNat [u]) typeMVar); pure $ mkApp3 (Lean.mkConst `HasOfNat.ofNat [u]) typeMVar mvar val @[builtinTermElab num] def elabNum : TermElab := fun stx expectedType? => elabRawNumLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab charLit] def elabRawCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => pure $ mkApp (Lean.mkConst `Char.ofNat) (mkNatLit val.toNat) | none => throwError stx "ill-formed syntax" @[builtinTermElab char] def elabChar : TermElab := fun stx expectedType? => elabRawCharLit (stx.getArg 0) expectedType? @[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ => match (stx.getArg 0).isNameLit? with | some val => pure $ toExpr val | none => throwError stx "ill-formed syntax" instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (TermElabM α) := ⟨fun env opts x _ => do let ctx : Context := { config := { opts := opts }, fileName := "<TermElabM>", fileMap := arbitrary _, cmdPos := 0, currNamespace := Name.anonymous, currRecDepth := 0, maxRecDepth := getMaxRecDepth opts }; let showMessages (s : State) : IO Unit := do { s.messages.forM $ fun m => IO.println $ format m }; match x ctx { env := env } with | EStateM.Result.ok a s => do showMessages s; MetaHasEval.eval s.env opts a | EStateM.Result.error (Exception.ex (Elab.Exception.error err)) s => do showMessages s; throw (IO.userError (toString (format err))) | EStateM.Result.error (Exception.ex Elab.Exception.unsupportedSyntax) s => do showMessages s; throw (IO.userError "error: unsupported syntax") | EStateM.Result.error Exception.postpone s => do showMessages s; throw (IO.userError "error: elaborator postponed")⟩ end Term @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.postpone; registerTraceClass `Elab.coe; registerTraceClass `Elab.debug; pure () export Term (TermElabM) end Elab end Lean
414e445acd6b4842663e8ff0b833f840188f774c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/ring_theory/fractional_ideal.lean
5dd1f9b393e2ceed2c62506dee47684ea900f82c
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
14,200
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen Fractional ideals of an integral domain. -/ import ring_theory.algebra_operations import ring_theory.localization /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions * `is_fractional` defines which `R`-submodules of `localization R S` are fractional ideals * `fractional_ideal R S` is the type of fractional ideals in `localization R S` * `has_coe (ideal R) (fractional_ideal R S)` instance * `comm_semiring (fractional_ideal R S)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal R S)` instance * `has_div (fractional_ideal R (non_zero_divisors R))` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. We don't assume that `localization R S` is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making `localization R (non_zero_divisors R) = fraction_ring R` into a field since `R` is a domain. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization set_option class.instance_max_depth 75 universes u v w namespace ring section defs variables (R : Type u) [integral_domain R] (S : set R) [is_submonoid S] /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R (localization R S)) := ∃ a ≠ (0 : R), ∀ b ∈ I, is_integer R S (a • b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `R'` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ R'` is an `R`-submodule of `R'`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R (localization R S) // is_fractional R S I} end defs namespace fractional_ideal open set open submodule variables {R : Type u} [integral_domain R] {S : set R} [is_submonoid S] instance : has_mem (localization R S) (fractional_ideal R S) := ⟨λ x I, x ∈ I.1⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal R S} : I.1 = J.1 → I = J := subtype.ext.mpr lemma fractional_of_subset_one (I : submodule R (localization R S)) (h : I ≤ 1) : is_fractional R S I := begin use 1, use one_ne_zero, intros b hb, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, convert is_integer_coe R b', simp [b'_eq_b.symm] end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal R S) := ⟨ λ I, ⟨ ↑I, fractional_of_subset_one _ (image_subset _ (subset_univ _)) ⟩ ⟩ instance : has_zero (fractional_ideal R S) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : localization R S} : x ∈ (0 : fractional_ideal R S) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := (or_false _).mp x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, or.inl rfl, by simp [hx]⟩) ⟩ @[simp] lemma val_zero : (0 : fractional_ideal R S).1 = 0 := begin ext, split; intro h; convert submodule.zero _, { rw [mem_zero_iff.mp h] }, { exact (or_false _).mp h } end lemma nonzero_iff_val_nonzero {I : fractional_ideal R S} : I.1 ≠ 0 ↔ I ≠ 0 := ⟨ λ h h', h (by simp [h']), λ h h', h (ext (by simp [h'])) ⟩ instance : inhabited (fractional_ideal R S) := ⟨0⟩ instance : has_one (fractional_ideal R S) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : localization R S} : x ∈ (1 : fractional_ideal R S) ↔ ∃ x' : R, ↑x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : (x : localization R S) ∈ (1 : fractional_ideal R S) := mem_one_iff.mpr ⟨x, rfl⟩ section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal R S) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff {I J : fractional_ideal R S} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.refl _ lemma zero_le (I : fractional_ideal R S) : 0 ≤ I := begin intros x hx, convert submodule.zero _, simpa using hx end instance order_bot : order_bot (fractional_ideal R S) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal R S) = 0 := rfl lemma eq_zero_iff {I : fractional_ideal R S} : I = 0 ↔ (∀ x ∈ I, x = (0 : localization R S)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal R S) : is_fractional R S (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use mul_ne_zero haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, smul_add], apply is_integer_add, { rw [mul_comm, mul_smul], apply is_integer_smul _ (hI bI hbI) }, { rw [mul_smul], apply is_integer_smul _ (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal R S) : is_fractional R S (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal R S) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal R S) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal R S) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal R S) : I ⊔ J = I + J := rfl @[simp] lemma val_add (I J : fractional_ideal R S) : (I + J).1 = I.1 + J.1 := rfl lemma fractional_mul (I J : fractional_ideal R S) : is_fractional R S (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨I, aJ, haJ, hJ⟩, use aI * aJ, use mul_ne_zero haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [mul_smul, ←algebra.mul_smul_comm, ←hn', mul_comm], apply hI, exact submodule.smul _ _ hm }, { rw [smul_zero], apply is_integer_coe }, { intros x y hx hy, rw [smul_add], apply is_integer_add _ hx hy }, { intros r x hx, rw [←mul_smul, mul_comm, mul_smul], apply is_integer_smul _ hx }, end instance : has_mul (fractional_ideal R S) := ⟨λ I J, ⟨I.1 * J.1, fractional_mul I J⟩⟩ @[simp] lemma val_mul (I J : fractional_ideal R S) : (I * J).1 = I.1 * J.1 := rfl lemma mul_left_mono (I : fractional_ideal R S) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal R S) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) instance add_comm_monoid : add_comm_monoid (fractional_ideal R S) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, ..fractional_ideal.has_zero, ..fractional_ideal.has_add } instance comm_monoid : comm_monoid (fractional_ideal R S) := { mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, erw [←y'_eq_y, mul_comm, coe_mul_eq_smul], exact submodule.smul _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h (coe_mem_one _), simpa } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, erw [←x'_eq_x, coe_mul_eq_smul], exact submodule.smul _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul (coe_mem_one _) h, simpa } end, ..fractional_ideal.has_mul, ..fractional_ideal.has_one } instance comm_semiring : comm_semiring (fractional_ideal R S) := { mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.add_comm_monoid, ..fractional_ideal.comm_monoid } end semiring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in `localization R S`, i.e. that `localization R S` is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, so that `localization R (non_zero_divisors R) = fraction_ring R`, which is a field because `R` is a domain. -/ open_locale classical instance : zero_ne_one_class (fractional_ideal R (non_zero_divisors R)) := { zero_ne_one := λ h, have this : (1 : localization _ _) ∈ (0 : fractional_ideal R (non_zero_divisors R)) := by convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this), ..fractional_ideal.has_one, ..fractional_ideal.has_zero } lemma fractional_div_of_nonzero {I J : fractional_ideal R (non_zero_divisors R)} (h : J ≠ 0) : is_fractional R (non_zero_divisors R) (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply mul_ne_zero haI, intro y'_eq_zero, have : ↑aJ * y = 0 := by rw [coe_mul_eq_smul, ←hy', y'_eq_zero, localization.coe_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := fraction_ring.of.injective (trans aJ_zero (of_zero _ _).symm), contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [mul_smul], convert hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), rw [←hy', mul_coe_eq_smul] end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal R (non_zero_divisors R)) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ noncomputable instance : has_inv (fractional_ideal R (non_zero_divisors R)) := ⟨λ I, 1 / I⟩ lemma div_nonzero {I J : fractional_ideal R (non_zero_divisors R)} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h lemma inv_nonzero {I : fractional_ideal R (non_zero_divisors R)} (h : I ≠ 0) : I⁻¹ = ⟨(1 : fractional_ideal R _).val / I.1, fractional_div_of_nonzero h⟩ := div_nonzero h @[simp] lemma div_one {I : fractional_ideal R (non_zero_divisors R)} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal R _) _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw [mul_comm], convert submodule.smul _ y' h, simp [y_eq_y'.symm] } end /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R (non_zero_divisors R)) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0, { intro hI, apply @zero_ne_one (fractional_ideal R (non_zero_divisors R)), convert h, simp [hI] }, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, rw [div_nonzero hI], apply le_antisymm, { apply submodule.mul_le.mpr _, intros x hx y hy, rw [mul_comm], exact mem_div_iff_forall_mul_mem.mp hy x hx }, rw [←h], apply mul_left_mono I, apply submodule.le_div_iff.mpr _, intros y hy x hx, rw [mul_comm], exact submodule.mul_mem_mul hx hy end end quotient end fractional_ideal end ring
d7c37b9729d6e2a86a923ba9c6de044a91663587
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/box_integral/partition/measure.lean
886f829a265d60423193cb5c4fc547a743e1170d
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
4,092
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.additive import measure_theory.measure.lebesgue /-! # Box-additive functions defined by measures In this file we prove a few simple facts about rectangular boxes, partitions, and measures: - given a box `I : box ι`, its coercion to `set (ι → ℝ)` and `I.Icc` are measurable sets; - if `μ` is a locally finite measure, then `(I : set (ι → ℝ))` and `I.Icc` have finite measure; - if `μ` is a locally finite measure, then `λ J, (μ J).to_real` is a box additive function. For the last statement, we both prove it as a proposition and define a bundled `box_integral.box_additive` function. ### Tags rectangular box, measure -/ open set noncomputable theory open_locale ennreal big_operators classical box_integral variables {ι : Type*} namespace box_integral open measure_theory namespace box lemma measure_Icc_lt_top (I : box ι) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : μ I.Icc < ∞ := show μ (Icc I.lower I.upper) < ∞, from I.is_compact_Icc.measure_lt_top lemma measure_coe_lt_top (I : box ι) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : μ I < ∞ := (measure_mono $ coe_subset_Icc).trans_lt (I.measure_Icc_lt_top μ) variables [fintype ι] (I : box ι) lemma measurable_set_coe : measurable_set (I : set (ι → ℝ)) := begin rw [coe_eq_pi], haveI := fintype.to_encodable ι, exact measurable_set.univ_pi (λ i, measurable_set_Ioc) end lemma measurable_set_Icc : measurable_set I.Icc := measurable_set_Icc lemma measurable_set_Ioo : measurable_set I.Ioo := (measurable_set_pi (set.to_finite _).countable).2 $ or.inl $ λ i hi, measurable_set_Ioo lemma coe_ae_eq_Icc : (I : set (ι → ℝ)) =ᵐ[volume] I.Icc := by { rw coe_eq_pi, exact measure.univ_pi_Ioc_ae_eq_Icc } lemma Ioo_ae_eq_Icc : I.Ioo =ᵐ[volume] I.Icc := measure.univ_pi_Ioo_ae_eq_Icc end box lemma prepartition.measure_Union_to_real [fintype ι] {I : box ι} (π : prepartition I) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : (μ π.Union).to_real = ∑ J in π.boxes, (μ J).to_real := begin erw [← ennreal.to_real_sum, π.Union_def, measure_bUnion_finset π.pairwise_disjoint], exacts [λ J hJ, J.measurable_set_coe, λ J hJ, (J.measure_coe_lt_top μ).ne] end end box_integral open box_integral box_integral.box variables [fintype ι] namespace measure_theory namespace measure /-- If `μ` is a locally finite measure on `ℝⁿ`, then `λ J, (μ J).to_real` is a box-additive function. -/ @[simps] def to_box_additive (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : ι →ᵇᵃ[⊤] ℝ := { to_fun := λ J, (μ J).to_real, sum_partition_boxes' := λ J hJ π hπ, by rw [← π.measure_Union_to_real, hπ.Union_eq] } end measure end measure_theory namespace box_integral open measure_theory namespace box @[simp] lemma volume_apply (I : box ι) : (volume : measure (ι → ℝ)).to_box_additive I = ∏ i, (I.upper i - I.lower i) := by rw [measure.to_box_additive_apply, coe_eq_pi, real.volume_pi_Ioc_to_real I.lower_le_upper] lemma volume_face_mul {n} (i : fin (n + 1)) (I : box (fin (n + 1))) : (∏ j, ((I.face i).upper j - (I.face i).lower j)) * (I.upper i - I.lower i) = ∏ j, (I.upper j - I.lower j) := by simp only [face_lower, face_upper, (∘), fin.prod_univ_succ_above _ i, mul_comm] end box namespace box_additive_map /-- Box-additive map sending each box `I` to the continuous linear endomorphism `x ↦ (volume I).to_real • x`. -/ protected def volume {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] : ι →ᵇᵃ (E →L[ℝ] E) := (volume : measure (ι → ℝ)).to_box_additive.to_smul lemma volume_apply {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] (I : box ι) (x : E) : box_additive_map.volume I x = (∏ j, (I.upper j - I.lower j)) • x := congr_arg2 (•) I.volume_apply rfl end box_additive_map end box_integral
f9d6aa3c29f1b0f91f595a2e5dd94a1c655145db
d406927ab5617694ec9ea7001f101b7c9e3d9702
/counterexamples/cyclotomic_105.lean
d600a7098a3d503712110b624bcd13d51066cc91
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,700
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic /-! # Not all coefficients of cyclotomic polynomials are -1, 0, or 1 We show that not all coefficients of cyclotomic polynomials are equal to `0`, `-1` or `1`, in the theorem `not_forall_coeff_cyclotomic_neg_one_zero_one`. We prove this with the counterexample `coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2`. -/ open nat (proper_divisors) finset section computation instance nat.fact_prime_five : fact (nat.prime 5) := ⟨by norm_num⟩ instance nat.fact_prime_seven : fact (nat.prime 7) := ⟨by norm_num⟩ lemma proper_divisors_15 : nat.proper_divisors 15 = {1, 3, 5} := rfl lemma proper_divisors_21 : nat.proper_divisors 21 = {1, 3, 7} := rfl lemma proper_divisors_35 : nat.proper_divisors 35 = {1, 5, 7} := rfl lemma proper_divisors_105 : nat.proper_divisors 105 = {1, 3, 5, 7, 15, 21, 35} := rfl end computation open polynomial lemma cyclotomic_3 : cyclotomic 3 ℤ = 1 + X + X ^ 2 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_5 : cyclotomic 5 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_7 : cyclotomic 7 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 + X ^ 5 + X ^ 6 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_15 : cyclotomic 15 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 5 - X ^ 7 + X ^ 8 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_15, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5], ring, repeat { norm_num } end lemma cyclotomic_21 : cyclotomic 21 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 6 - X ^ 8 + X ^ 9 - X ^ 11 + X ^ 12 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_21, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_35 : cyclotomic 35 ℤ = 1 - X + X ^ 5 - X ^ 6 + X ^ 7 - X ^ 8 + X ^ 10 - X ^ 11 + X ^ 12 - X ^ 13 + X ^ 14 - X ^ 16 + X ^ 17 - X ^ 18 + X ^ 19 - X ^ 23 + X ^ 24 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_35, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_5, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_105 : cyclotomic 105 ℤ = 1 + X + X ^ 2 - X ^ 5 - X ^ 6 - 2 * X ^ 7 - X ^ 8 - X ^ 9 + X ^ 12 + X ^ 13 + X ^ 14 + X ^ 15 + X ^ 16 + X ^ 17 - X ^ 20 - X ^ 22 - X ^ 24 - X ^ 26 - X ^ 28 + X ^ 31 + X ^ 32 + X ^ 33 + X ^ 34 + X ^ 35 + X ^ 36 - X ^ 39 - X ^ 40 - 2 * X ^ 41 - X ^ 42 - X ^ 43 + X ^ 46 + X ^ 47 + X ^ 48 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw proper_divisors_105, repeat {rw finset.prod_insert _}, rw [finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5, cyclotomic_7, cyclotomic_15, cyclotomic_21, cyclotomic_35], ring, repeat { norm_num } end lemma coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2 := begin simp [cyclotomic_105, coeff_X_pow, coeff_one, coeff_X_of_ne_one, coeff_bit0_mul, coeff_bit1_mul] end lemma not_forall_coeff_cyclotomic_neg_one_zero_one : ¬∀ n i, coeff (cyclotomic n ℤ) i ∈ ({-1, 0, 1} : set ℤ) := begin intro h, specialize h 105 7, rw coeff_cyclotomic_105 at h, norm_num at h end
06b80cea8242180ed1ddd0e5bd4ade4b058d9185
9028d228ac200bbefe3a711342514dd4e4458bff
/src/measure_theory/set_integral.lean
1ea1ca3a474305b3c830e4248c02f0897c5ab6f5
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,712
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.bochner_integration import analysis.normed_space.indicator_function /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation `∫ a in s, f a` is `measure_theory.integral (s.indicator f)` ## TODO The file ends with over a hundred lines of commented out code. This is the old contents of this file using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be migrated to the new definition. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter variables {α β E F : Type*} [measurable_space α] section piecewise variables {μ : measure α} {s : set α} {f g : α → β} lemma piecewise_ae_eq_restrict (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict s] f := begin rw [ae_restrict_eq hs], exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right end lemma piecewise_ae_eq_restrict_compl (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict sᶜ] g := begin rw [ae_restrict_eq hs.compl], exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right end end piecewise section indicator_function variables [has_zero β] {μ : measure α} {s : set α} {f : α → β} lemma indicator_ae_eq_restrict (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs lemma indicator_ae_eq_restrict_compl (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 := piecewise_ae_eq_restrict_compl hs end indicator_function namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ⊤) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty (hf : measurable f) : integrable_on f ∅ μ := by simp [integrable_on, measurable.integrable_zero hf] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ⊤ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_finite_union (hf : measurable f) {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp [hf] }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union (hf : measurable f) {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union hf s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma integrable_indicator_iff (hf : measurable f) (hs : is_measurable s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp only [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, hf, hf.indicator hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : is_measurable s) : integrable (indicator s f) μ := (integrable_indicator_iff h.measurable hs).2 h /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin rcases hμ with ⟨s, hsl, hsμ⟩, rcases hf with ⟨C, hC⟩, simp only [eventually_map] at hC, rcases hC.exists_measurable_mem with ⟨t, htl, htm, hC⟩, refine ⟨t ∩ s, inter_mem_sets htl hsl, _⟩, refine ⟨hfm, has_finite_integral_restrict_of_bounded (lt_of_le_of_lt (measure_mono $ inter_subset_right _ _) hsμ) _⟩, exact C, suffices : ∀ᵐ x ∂μ.restrict t, ∥f x∥ ≤ C, from ae_mono (measure.restrict_mono (inter_subset_left _ _) (le_refl _)) this, rw [ae_restrict_eq htm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter hfm hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add [opens_measurable_space E] {f g : α → E} (h : univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0}) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, _, λ h, h.1.add h.2⟩, rw [← indicator_add_eq_left h], conv { congr, skip, rw [← indicator_add_eq_right h] }, rw [integrable_indicator_iff (hf.add' hg) (hf (is_measurable_singleton 0)).compl], rw [integrable_indicator_iff (hf.add' hg) (hg (is_measurable_singleton 0)).compl], exact ⟨hfg.integrable_on, hfg.integrable_on⟩ end /-- To prove something for an arbitrary measurable + integrable function in a second countable Borel normed group, it suffices to show that * the property holds for (multiples of) characteristic functions; * is closed under addition; * the set of functions in the `L¹` space for which the property holds is closed. * the property is closed under the almost-everywhere equal relation. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`). -/ @[elab_as_eliminator] lemma integrable.induction (P : (α → E) → Prop) (h_ind : ∀ (c : E) ⦃s⦄, is_measurable s → μ s < ⊤ → P (s.indicator (λ _, c))) (h_sum : ∀ ⦃f g : α → E⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → integrable f μ → integrable g μ → P f → P g → P (f + g)) (h_closed : is_closed {f : α →₁[μ] E | P f} ) (h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → integrable f μ → measurable g → P f → P g) : ∀ ⦃f : α → E⦄ (hf : integrable f μ), P f := begin have : ∀ (f : simple_func α E), integrable f μ → P f, { refine simple_func.induction _ _, { intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero, piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢, by_cases hc : c = 0, { subst hc, convert h_ind 0 is_measurable.empty (by simp) using 1, simp [const] }, apply h_ind c hs, have : (nnnorm c : ennreal) * μ s < ⊤, { have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ennreal)) (const α c) s, dsimp only at this, have h' := h.has_finite_integral, simpa [has_finite_integral, this, lintegral_indicator, hs] using h' }, exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) }, { intros f g hfg hf hg int_fg, rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg, refine h_sum hfg int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } }, have : ∀ (f : α →₁ₛ[μ] E), P f, { intro f, exact h_ae f.to_simple_func_eq_to_fun f.integrable (l1.measurable _) (this f.to_simple_func f.integrable) }, have : ∀ (f : α →₁[μ] E), P f := λ f, l1.simple_func.dense_range.induction_on f h_closed this, exact λ f hf, h_ae (l1.to_fun_of_fun f hf) (l1.integrable _) hf.measurable (this (l1.of_fun f hf)) end variables [complete_space E] [normed_space ℝ E] lemma integral_union (hst : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft] lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : is_measurable s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (disjoint_compl_right s) hs hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a measurable function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hfm : measurable f) (hs : is_measurable s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := have hfms : measurable (indicator s f) := hfm.indicator hs, if hfi : integrable_on f s μ then calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae hfms hfm (indicator_ae_eq_restrict hs)) (integral_congr_ae hfms measurable_const (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp else by { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hfm hs } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : is_measurable s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator measurable_const s_meas, ← set_integral_const] lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := by rw [measure.restrict_map hg hs, integral_map hg hf] lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ (ae_restrict_iff $ hfm.norm is_measurable_Iic).2 hC lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ⊤) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : 0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) := by { rw [integral_pos_iff_support_of_nonneg_ae hf hfi, measure.restrict_apply], exact hfi.1 (is_measurable_singleton 0).compl } end normed_group end measure_theory open measure_theory asymptotics metric variables [measurable_space E] [normed_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s, f x ∂μ = μ s • b + o(μ s)` as `s` tends to `l.lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : measurable f) (hμ : μ.finite_at_filter l) : is_o (λ s : set α, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real) (l.lift' powerset) := begin simp only [is_o_iff], intros ε ε₀, have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), refine hμ.eventually.mp ((h.integrable_at_filter_ae hfm hμ).eventually.mp (this.mono _)), simp only [mem_closed_ball, dist_eq_norm], intros s h_norm h_integrable hμs, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub measurable_const) end /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hfm : measurable f) (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs (integrable_on_empty hfm) (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hfm : measurable f) (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within hfm $ λ x hx, by haveI := hs.is_measurable.nhds_within_is_measurably_generated; exact (hf x hx).integrable_at_filter hfm (μ.finite_at_nhds_within _ _) /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs hf.measurable /-- A continuous function with compact closure of the support is integrable on the whole space. -/ lemma continuous.integrable_of_compact_closure_support [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure $ support f)) : integrable f μ := begin rw [← indicator_of_support_subset (@subset_closure _ _ (support f)), integrable_indicator_iff hf.measurable is_closed_closure.is_measurable], exact hf.integrable_on_compact hfc end /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure that and `f` is a measurable function that is continuous at a point `a`, then `∫ x in s, f x ∂μ = μ s • f a + o(μ s)` as `s` tends to `(𝓝 a).lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable f) : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • f a) (λ s, (μ s).to_real) ((𝓝 a).lift' powerset) := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. The first step is to prove that, given a function `φ : α → E` which is measurable and integrable, and a continuous linear map `L : E →L[ℝ] F`, the function `λ a, L(φ a)` is also measurable and integrable. Note we cannot write this as `L ∘ φ` since the type of `L` is not an actual function type. The next step is translate this to `l1`, replacing the function `φ` by a term with type `α →₁[μ] E` (an equivalence class of integrable functions). The corresponding "composition" is `L.comp_l1 φ : α →₁[μ] F`. This is then upgraded to a linear map `L.comp_l1ₗ : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F)` and a continuous linear map `L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F)`. Then we can prove the commutation result using continuity of all relevant operations and the result on simple functions. -/ variables {μ : measure α} [normed_space ℝ E] variables [normed_group F] [normed_space ℝ F] namespace continuous_linear_map lemma norm_comp_l1_apply_le [opens_measurable_space E] [second_countable_topology E] (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∀ᵐ a ∂μ, ∥L (φ a)∥ ≤ ∥L∥ * ∥φ a∥ := eventually_of_forall (λ a, L.le_op_norm (φ a)) variables [measurable_space F] [borel_space F] lemma integrable_comp [opens_measurable_space E] {φ : α → E} (L : E →L[ℝ] F) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp φ_int.measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a)) variables [borel_space E] [second_countable_topology E] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`. -/ def comp_l1 [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : α →₁[μ] F := l1.of_fun (λ a, L (φ a)) (L.integrable_comp φ.integrable) lemma comp_l1_apply [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∀ᵐ a ∂μ, (L.comp_l1 φ) a = L (φ a) := l1.to_fun_of_fun _ _ lemma integrable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : integrable (λ a, L (φ a)) μ := L.integrable_comp φ.integrable lemma measurable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : measurable (λ a, L (φ a)) := L.measurable.comp φ.measurable variables [second_countable_topology F] lemma integral_comp_l1 [complete_space F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, (L.comp_l1 φ) a ∂μ = ∫ a, L (φ a) ∂μ := by simp [comp_l1] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1ₗ (L : E →L[ℝ] F) : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F) := { to_fun := λ φ, L.comp_l1 φ, map_add' := begin intros f g, dsimp [comp_l1], rw [← l1.of_fun_add, l1.of_fun_eq_of_fun], apply (l1.add_to_fun f g).mono, intros a ha, simp only [ha, pi.add_apply, L.map_add] end, map_smul' := begin intros c f, dsimp [comp_l1], rw [← l1.of_fun_smul, l1.of_fun_eq_of_fun], apply (l1.smul_to_fun c f).mono, intros a ha, simp only [ha, pi.smul_apply, continuous_linear_map.map_smul] end } lemma norm_comp_l1_le (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∥L.comp_l1 φ∥ ≤ ∥L∥*∥φ∥ := begin erw l1.norm_of_fun_eq_integral_norm, calc ∫ a, ∥L (φ a)∥ ∂μ ≤ ∫ a, ∥L∥ *∥φ a∥ ∂μ : integral_mono_ae (L.integrable_comp_l1 φ).norm (φ.integrable_norm.const_mul $ ∥L∥) (L.norm_comp_l1_apply_le φ) ... = ∥L∥ * ∥φ∥ : by rw [integral_mul_left, φ.norm_eq_integral_norm] end /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1L (L : E →L[ℝ] F) : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F) := linear_map.mk_continuous L.comp_l1ₗ (∥L∥) (λ φ, L.norm_comp_l1_le φ) lemma norm_compl1L_le (L : E →L[ℝ] F) : ∥(L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F))∥ ≤ ∥L∥ := op_norm_le_bound _ (norm_nonneg _) (λ φ, L.norm_comp_l1_le φ) variables [complete_space F] lemma continuous_integral_comp_l1 (L : E →L[ℝ] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := begin rw ← funext L.integral_comp_l1, exact continuous_integral.comp L.comp_l1L.continuous end variables [complete_space E] lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul, ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_l1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int g_meas hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (L.measurable.comp g_meas) (L.measurable.comp f_int.measurable) (hfg.fun_comp L).symm }, { rw integral_congr_ae g_meas f_int.measurable hfg.symm } }, all_goals { assumption } end lemma integral_comp_l1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm φ.integrable end continuous_linear_map variables [borel_space E] [second_countable_topology E] [complete_space E] [measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F] lemma fst_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := ((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm lemma snd_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := ((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this) lemma integral_smul_const (f : α → ℝ) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := begin by_cases hf : integrable f μ, { exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf }, { by_cases hc : c = 0, { simp only [hc, integral_zero, smul_zero] }, rw [integral_undef hf, integral_undef, zero_smul], simp_rw [integrable_smul_const hc, hf, not_false_iff] } end end /- namespace integrable variables [measurable_space α] [measurable_space β] [normed_group E] protected lemma measure_mono end integrable end measure_theory section integral_on variables [measurable_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] {s t : set α} {f g : α → β} {μ : measure α} open set lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : is_measurable s) (h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ := integral_congr_ae hf hg $ _ lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ᵐ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ᵐ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact measurable.add hsm htm } end lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h } lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_on_nonneg_of_ae $ univ_mem_sets' hf lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h } lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_on_nonpos_of_ae $ univ_mem_sets' hf lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat ` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa has_sum.tsum_eq }, begin have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact is_countably_generated_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on -/
ba100e34b74e9d63c4d601b16f4308aee6754b33
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level08.lean
5dfc5f034569bb3929472bca482ed5bbed702775
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
127
lean
lemma succ_le_succ (a b : mynat) (h : a ≤ b) : succ a ≤ succ b := begin cases h with d hd, use d, rw hd, rwa succ_add, end
9d55ca17afd5643227ce23826d7a7a6b82e497d8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/multiplicity.lean
4dd44ab1700a81a327e2b06a4bcbf65207c05fd1
[ "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
11,874
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators.intervals import data.nat.bitwise import data.nat.log import data.nat.parity import ring_theory.int.basic /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `nat.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n/p + ... + n/p^b` for any `b` such that `n/p^(b + 1) = 0`. * `nat.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `nat.multiplicity_choose`: The multiplicity of `p` in `n.choose k` is the number of carries when `k` and`n - k` are added in base `p`. ## Other declarations * `nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `nat.prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p ≠ 1` and other trivialities, along with translating between `prime` and `nat.prime`. ## Tags Legendre, p-adic -/ open finset nat multiplicity open_locale big_operators nat namespace nat /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm : m ≠ 1) (hn : 0 < n) (hb : log m n < b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, begin rw [mem_filter, mem_Ico, mem_Ico, lt_succ_iff, ←@enat.coe_le_coe i, enat.coe_get, ←pow_dvd_iff_le_multiplicity, and.right_comm], refine (and_iff_left_of_imp (λ h, _)).symm, cases m, { rw [zero_pow, zero_dvd_iff] at h, exact (hn.ne' h.2).elim, { exact h.1 } }, exact ((pow_le_iff_le_log (succ_lt_succ $ nat.pos_of_ne_zero $ succ_ne_succ.1 hm) hn).1 $ le_of_dvd hn h.2).trans_lt hb, end namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := multiplicity.one_right (prime_iff.mp hp).not_unit lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul $ prime_iff.mp hp lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n • (multiplicity p m) := multiplicity.pow $ prime_iff.mp hp lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := multiplicity_self (prime_iff.mp hp).not_unit hp.ne_zero lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero (prime_iff.mp hp).not_unit n /-- **Legendre's Theorem** The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_factorial {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, log p n < b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) : by rw [factorial_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_factorial ((log_le_log_of_le $ le_succ _).trans_lt hb), ← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by { rw [sum_add_distrib, sum_boole], simp } ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl $ λ _ _, (succ_div _ _).symm /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ lemma multiplicity_factorial_mul_succ {n p : ℕ} (hp : p.prime) : multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 := begin have hp' := prime_iff.mp hp, have h0 : 2 ≤ p := hp.two_le, have h1 : 1 ≤ p * n + 1 := nat.le_add_left _ _, have h2 : p * n + 1 ≤ p * (n + 1), linarith, have h3 : p * n + 1 ≤ p * (n + 1) + 1, linarith, have hm : multiplicity p (p * n)! ≠ ⊤, { rw [ne.def, eq_top_iff_not_finite, not_not, finite_nat_iff], exact ⟨hp.ne_one, factorial_pos _⟩ }, revert hm, have h4 : ∀ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0, { intros m hm, apply multiplicity_eq_zero_of_not_dvd, rw [← exists_lt_and_lt_iff_not_dvd _ (pos_iff_ne_zero.mpr hp.ne_zero)], rw [mem_Ico] at hm, exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ }, simp_rw [← prod_Ico_id_eq_factorial, multiplicity.finset.prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc], intro h, rw [enat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp', hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm (1 : enat)] end /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ lemma multiplicity_factorial_mul {n p : ℕ} (hp : p.prime) : multiplicity p (p * n)! = multiplicity p n! + n := begin induction n with n ih, { simp }, { simp only [succ_eq_add_one, multiplicity.mul, hp, prime_iff.mp hp, ih, multiplicity_factorial_mul_succ, ←add_assoc, nat.cast_one, nat.cast_add, factorial_succ], congr' 1, rw [add_comm, add_assoc] } end /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : log p n < b) : p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] lemma multiplicity_factorial_le_div_pred {p : ℕ} (hp : p.prime) (n : ℕ) : multiplicity p n! ≤ (n/(p - 1) : ℕ) := begin rw [hp.multiplicity_factorial (lt_succ_self _), enat.coe_le_coe], exact nat.geom_sum_Ico_le hp.two_le _ _, end lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [add_sub_cancel_of_le hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (pow_pos hp.pos _)] ... = _ : by simp [sum_add_distrib, sum_boole] /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : log p n < b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k! * (n - k)!), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial ((log_le_log_of_le hkn).trans_lt hnb), hp.multiplicity_factorial (lt_of_le_of_lt (log_le_log_of_le sub_le_self') hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (lt_succ_of_le (log_le_log_of_le (le_of_not_gt hkn))), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (lt_succ_self _), ← nat.cast_add, enat.coe_le_coe], calc ((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [add_sub_cancel_of_le (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 n.succ).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 n.succ).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)] {contextual := tt}, begin rw [multiplicity_choose hp hkn (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 (lt_succ_of_le (log_le_log_of_le hkn)), ← nat.cast_add, enat.coe_le_coe, log_pow hp.one_lt, ← card_disjoint_union hdisj, filter_union_right], have filter_le_Ico := (Ico 1 n.succ).card_filter_le _, rwa card_Ico 1 n.succ at filter_le_Ico, end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime lemma multiplicity_two_factorial_lt : ∀ {n : ℕ} (h : n ≠ 0), multiplicity 2 n! < n := begin have h2 := prime_iff.mp prime_two, refine binary_rec _ _, { contradiction }, { intros b n ih h, by_cases hn : n = 0, { subst hn, simp at h, simp [h, one_right h2.not_unit, enat.zero_lt_one] }, have : multiplicity 2 (2 * n)! < (2 * n : ℕ), { rw [prime_two.multiplicity_factorial_mul], refine (enat.add_lt_add_right (ih hn) (enat.coe_ne_top _)).trans_le _, rw [two_mul], norm_cast }, cases b, { simpa [bit0_eq_two_mul n] }, { suffices : multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1, { simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, nat.bit1_eq_succ_bit0, bit0_eq_two_mul n] }, rw [multiplicity_eq_zero_of_not_dvd (two_not_dvd_two_mul_add_one n), zero_add], refine this.trans _, exact_mod_cast lt_succ_self _ }} end end nat
ec7b21bc65d4587caac9063eeadeca7be3841443
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/choice.hlean
e03e1b5b7280c57b59cbefe7cf06282293f4d7c6
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,545
hlean
import types.trunc types.bool open eq bool equiv sigma sigma.ops trunc is_trunc pi namespace choice universe variable u -- 3.8.1. The axiom of choice. definition AC [reducible] := Π (X : Type.{u}) (A : X -> Type.{u}) (P : Π x, A x -> Type.{u}), is_hset X -> (Π x, is_hset (A x)) -> (Π x a, is_hprop (P x a)) -> (Π x, ∥ Σ a, P x a ∥) -> ∥ Σ f, Π x, P x (f x) ∥ -- 3.8.3. Corresponds to the assertion that -- "the cartesian product of a family of nonempty sets is nonempty". definition AC_cart [reducible] := Π (X : Type.{u}) (A : X -> Type.{u}), is_hset X -> (Π x, is_hset (A x)) -> (Π x, ∥ A x ∥) -> ∥ Π x, A x ∥ -- A slight variant of AC with a modified (equivalent) codomain. definition AC' [reducible] := Π (X : Type.{u}) (A : X -> Type.{u}) (P : Π x, A x -> Type.{u}), is_hset X -> (Π x, is_hset (A x)) -> (Π x a, is_hprop (P x a)) -> (Π x, ∥ Σ a, P x a ∥) -> ∥ Π x, Σ a : A x, P x a ∥ -- The equivalence of AC and AC' follows from the equivalence of their codomains. definition AC_equiv_AC' : AC.{u} ≃ AC'.{u} := equiv_of_is_hprop (λ H X A P HX HA HP HI, trunc_functor _ (to_fun !sigma_pi_equiv_pi_sigma) (H X A P HX HA HP HI)) (λ H X A P HX HA HP HI, trunc_functor _ (to_inv !sigma_pi_equiv_pi_sigma) (H X A P HX HA HP HI)) -- AC_cart can be derived from AC' by setting P := λ _ _ , unit. definition AC_cart_of_AC' : AC'.{u} -> AC_cart.{u} := λ H X A HX HA HI, trunc_functor _ (λ H0 x, (H0 x).1) (H X A (λ x a, lift.{0 u} unit) HX HA (λ x a, !is_trunc_lift) (λ x, trunc_functor _ (λ a, ⟨a, lift.up.{0 u} unit.star⟩) (HI x))) -- And the converse, by setting A := λ x, Σ a, P x a. definition AC'_of_AC_cart : AC_cart.{u} -> AC'.{u} := by intro H X A P HX HA HP HI; apply H X (λ x, Σ a, P x a) HX (λ x, !is_trunc_sigma) HI -- Which is enough to show AC' ≃ AC_cart, since both are hprops. definition AC'_equiv_AC_cart : AC'.{u} ≃ AC_cart.{u} := equiv_of_is_hprop AC_cart_of_AC'.{u} AC'_of_AC_cart.{u} -- 3.8.2. AC ≃ AC_cart follows by transitivity. definition AC_equiv_AC_cart : AC.{u} ≃ AC_cart.{u} := equiv.trans AC_equiv_AC' AC'_equiv_AC_cart namespace example385 definition X : Type.{1} := Σ A : Type.{0}, ∥ A = bool ∥ definition x0 : X := ⟨bool, merely.intro _ rfl⟩ definition Y : X -> Type.{1} := λ x, x0 = x definition not_is_hset_X : ¬ is_hset X := begin intro H, apply not_is_hprop_bool_eq_bool, apply @is_trunc_equiv_closed (x0 = x0), apply equiv.symm !equiv_subtype end definition is_hset_x1 (x : X) : is_hset x.1 := by cases x; induction a_1; cases a_1; exact _ definition is_hset_Yx (x : X) : is_hset (Y x) := begin apply @is_trunc_equiv_closed _ _ _ !equiv_subtype, apply @is_trunc_equiv_closed _ _ _ (equiv.symm !eq_equiv_equiv), apply is_trunc_equiv; repeat (apply is_hset_x1) end definition trunc_Yx (x : X) : ∥ Y x ∥ := begin cases x, induction a_1, apply merely.intro, apply to_fun !equiv_subtype, rewrite a_1 end end example385 open example385 -- 3.8.5. There exists a type X and a family Y : X → U such that each Y(x) is a set, -- but such that (3.8.3) is false. definition X_must_be_hset : Σ (X : Type.{1}) (Y : X -> Type.{1}) (HA : Π x : X, is_hset (Y x)), ¬ ((Π x : X, ∥ Y x ∥) -> ∥ Π x : X, Y x ∥) := ⟨X, Y, is_hset_Yx, λ H, trunc.rec_on (H trunc_Yx) (λ H0, not_is_hset_X (@is_trunc_of_is_contr _ _ (is_contr.mk x0 H0)))⟩ end choice
52aac2345ca2567b519667f860edfb2ac1ee8988
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/analysis/normed_space/inner_product.lean
96b0b07c399aad194fcd5dd6a96680c958262b30
[ "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
81,241
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form import analysis.special_functions.pow import topology.metric_space.pi_Lp import data.complex.is_R_or_C /-! # Inner Product Space This file defines inner product spaces and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i` - We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that this an inner product space. - Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## TODO - Fix the section on the existence of minimizers and orthogonal projections to make sure that it also applies in the complex case. ## Tags inner product space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real open_locale big_operators classical variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- This instance generates the type-class problem `inner_product_space ?m E` when looking for `normed_group E`. However, since `?m` can only ever be `ℝ` or `ℂ`, this should not cause problems. -/ attribute [nolint dangerous_instance] inner_product_space.to_normed_group /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [semimodule 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_square (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_square], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_square, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [semimodule 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sqr_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := _root_.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ local postfix `⋆`:90 := complex.conj export inner_product_space (norm_sq_eq_inner) section basic_properties lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := begin rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], conv_rhs { rw ←inner_conj_sym, conv { congr, skip, rw ←inner_conj_sym } } end lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ def sesq_form_of_inner : sesq_form 𝕜 E conj_to_ring_equiv := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.map_sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.map_sum_left (sesq_form_of_inner) _ _ _ @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin have H : ⟪x, x⟫ = (re ⟪x, x⟫ : 𝕜) + im ⟪x, x⟫ * I, { rw re_add_im, }, rw [H, is_add_hom.map_add re ((re ⟪x, x⟫) : 𝕜) (((im ⟪x, x⟫) : 𝕜) * I)], rw [mul_re, I_re, mul_zero, I_im, zero_sub, tactic.ring.add_neg_eq_sub], rw [of_real_re, of_real_im, sub_zero, inner_self_nonneg_im], simp only [abs_of_real, add_zero, of_real_zero, zero_mul], exact (_root_.abs_of_nonneg inner_self_nonneg).symm, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_square (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_square (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_square ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_pow_two {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end /-- Expand the square -/ lemma norm_add_pow_two_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_pow_two {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end /-- Expand the square -/ lemma norm_sub_pow_two_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_sub_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_square], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [(inner_self_eq_norm_square _).symm], rw[←add_monoid_hom.map_add, parallelogram_law, two_mul, two_mul], simp only [add_monoid_hom.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by rw norm_add_mul_self; ring /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by rw norm_sub_mul_self; ring /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, exact h }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_square, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] end norm /-! ### Inner product space structure on product spaces -/ /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ (j : ι) (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw [←finset.sum_hom finset.univ conj], apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, apply_instance end, nonneg_im := begin intro x, unfold inner, rw[←finset.sum_hom finset.univ im], apply finset.sum_eq_zero, rintros z -, exact inner_self_nonneg_im, apply_instance end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by unfold inner; rw [mul_comm, mul_conj, of_real_re, norm_sq, norm_sq_eq_def], conj_sym := λ x y, by simp [mul_comm], nonneg_im := λ x, by rw[mul_im, conj_re, conj_im]; ring, add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, nonneg_im := λ x, rfl, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section deriv variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul, is_R_or_C.norm_eq_abs], exact abs_inner_le_norm x y, }⟩ } lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.times_cont_diff lemma times_cont_diff_at_inner {p : E × E} {n} : times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p := times_cont_diff_inner.times_cont_diff_at lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) := times_cont_diff_inner.differentiable le_rfl lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := differentiable_inner.continuous variables {G : Type*} [normed_group G] [normed_space ℝ G] {f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ} include 𝕜 lemma times_cont_diff_within_at.inner (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) : times_cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x := times_cont_diff_at_inner.comp_times_cont_diff_within_at x (hf.prod hg) lemma times_cont_diff_at.inner (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) : times_cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x := hf.inner hg lemma times_cont_diff_on.inner (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) : times_cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) : times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) := times_cont_diff_inner.comp (hf.prod hg) lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) : differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x := ((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg).has_fderiv_within_at).differentiable_within_at lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : differentiable_at ℝ (λ x, ⟪f x, g x⟫) x := (differentiable_inner _).comp x (hf.prod hg) lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) : differentiable_on ℝ (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) : differentiable ℝ (λ x, ⟪f x, g x⟫) := λ x, (hf x).inner (hg x) end deriv section pi_Lp local attribute [reducible] pi_Lp variables {ι : Type*} [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b := calc wp - wq = (u - wq) - (u - wp) : by rw [sub_sub_assoc_swap, add_sub_assoc, sub_add_sub_cancel'] ... = a - b : rfl, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace 𝕜 E) (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : subspace ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : subspace ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace 𝕜 E) {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : subspace ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {K : subspace 𝕜 E} (h : is_complete (K : set E)) (v : E) := (exists_norm_eq_infi_of_complete_subspace K h v).some /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection_fn h v ∈ K := (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn h v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem h v), exact (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : v = orthogonal_projection_fn h u := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : v - orthogonal_projection_fn h u ∈ K := submodule.sub_mem K hvm (orthogonal_projection_fn_mem h u), have huo : ⟪u - orthogonal_projection_fn h u, v - orthogonal_projection_fn h u⟫ = 0 := orthogonal_projection_fn_inner_eq_zero h u _ hvs, have huv : ⟪u - v, v - orthogonal_projection_fn h u⟫ = 0 := hvo _ hvs, have houv : ⟪(u - orthogonal_projection_fn h u) - (u - v), v - orthogonal_projection_fn h u⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end /-- The orthogonal projection onto a complete subspace. For most purposes, `orthogonal_projection`, which removes the `is_complete` hypothesis and is the identity map when the subspace is not complete, should be used instead. -/ def orthogonal_projection_of_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) : linear_map 𝕜 E E := { to_fun := orthogonal_projection_fn h, map_add' := λ x y, begin have hm : orthogonal_projection_fn h x + orthogonal_projection_fn h y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem h x) (orthogonal_projection_fn_mem h y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn h x + orthogonal_projection_fn h y), w⟫ = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, orthogonal_projection_fn_inner_eq_zero h _ w hw, add_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn h x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem h x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn h x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, mul_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end } /-- The orthogonal projection onto a subspace, which is expected to be complete. If the subspace is not complete, this uses the identity map instead. -/ def orthogonal_projection (K : submodule 𝕜 E) : linear_map 𝕜 E E := if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id /-- The definition of `orthogonal_projection` using `if`. -/ lemma orthogonal_projection_def (K : submodule 𝕜 E) : orthogonal_projection K = if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id := rfl @[simp] lemma orthogonal_projection_fn_eq {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection_fn h v = orthogonal_projection K v := by { rw [orthogonal_projection_def, dif_pos h], refl } /-- The orthogonal projection is in the given subspace. -/ lemma orthogonal_projection_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection K v ∈ K := begin rw ←orthogonal_projection_fn_eq h, exact orthogonal_projection_fn_mem h v end /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (K : submodule 𝕜 E) (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := begin simp_rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_inner_eq_zero h v }, { simp }, end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : v = orthogonal_projection K u := begin rw ←orthogonal_projection_fn_eq h, exact eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hvm hvo end /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal (K : submodule 𝕜 E) : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } /-- When a vector is in `K.orthogonal`. -/ lemma submodule.mem_orthogonal (K : submodule 𝕜 E) (v : E) : v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `K.orthogonal`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (K : submodule 𝕜 E) (v : E) : v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] /-- A vector in `K` is orthogonal to one in `K.orthogonal`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `K.orthogonal` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- `K` and `K.orthogonal` have trivial intersection. -/ lemma submodule.orthogonal_disjoint (K : submodule 𝕜 E) : disjoint K K.orthogonal := begin simp_rw [submodule.disjoint_def, submodule.mem_orthogonal], exact λ x hx ho, inner_self_eq_zero.1 (ho x hx) end variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂.orthogonal ≤ K₁.orthogonal := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `K` is contained in `K.orthogonal.orthogonal`. -/ lemma submodule.le_orthogonal_orthogonal (K : submodule 𝕜 E) : K ≤ K.orthogonal.orthogonal := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁.orthogonal ⊓ K₂.orthogonal = (K₁ ⊔ K₂).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i).orthogonal) = (supr K).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, submodule.orthogonal K) = (Sup s).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁.orthogonal ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁.orthogonal ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end /-- If `K` is complete, `K` and `K.orthogonal` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) : K ⊔ K.orthogonal = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `K.orthogonal` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) : is_compl K K.orthogonal := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E).orthogonal = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E).orthogonal = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end lemma submodule.eq_top_iff_orthogonal_eq_bot {K : submodule 𝕜 E} (hK : is_complete (K : set E)) : K = ⊤ ↔ K.orthogonal = ⊥ := begin refine ⟨by { rintro rfl, exact submodule.top_orthogonal_eq_bot }, _⟩, intro h, have : K ⊔ K.orthogonal = ⊤ := submodule.sup_orthogonal_of_is_complete hK, rwa [h, sup_comm, bot_sup_eq] at this, end open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : findim 𝕜 K₁ + findim 𝕜 (K₁.orthogonal ⊓ K₂ : submodule 𝕜 E) = findim 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁.orthogonal ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end end orthogonal
dd7b17550a34072e6aa1e29c29940d769a391b0b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/order/complete_lattice.lean
2988be0ae30981116be03985721029fb0a30077c
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,798
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded" supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ (∀ b, (∀ x ∈ s, x ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' begin simp only [Sup_le_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans hy'] end -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ (∀ b, (∀ x ∈ s, b ≤ x) → b ≤ a) := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj] class complete_lattice (α : Type*) extends bounded_lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α. /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_instert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) : a ≤ ⨆ i hi, f i hi := le_trans h (le_bsupr i hi) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b := ⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩ theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_sUnion {s : set (set α)} : Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have : f₁ ∘ pq.mpr = f₂ := funext f, rw [← this], refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm, refl end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) : (⨅ i hi, f i hi) ≤ a := le_trans (binfi_le i hi) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) β _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf (order_dual α) _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi (order_dual α) _ _ _ _ _ /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := @supr_range (order_dual α) _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', infi, range_comp, subtype.range_coe] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ /-! ### `supr` and `infi` under `Type` -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option (order_dual α) _ _ _ /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le (λ i, (le_refl _).trans (le_supr _ (i + k)))) (supr_le_supr (λ i, hf (nat.le_add_right i k))) @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i), from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. bounded_distrib_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _) end complete_lattice namespace complete_lattice variables [complete_lattice α] /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : independent s) @[simp] lemma independent_empty : independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem independent.mono {t : set α} (hst : t ⊆ s) : independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y := disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩) include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end end complete_lattice
cf06a138def93989bf033b4970534a07762c9acc
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/polynomial/scale_roots.lean
5a4f6e7c6ab6a3e695670a340589331309b0fd2b
[ "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
5,338
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.polynomial.basic import ring_theory.non_zero_divisors /-! # Scaling the roots of a polynomial This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it. -/ section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open polynomial open_locale big_operators /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := ∑ i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : ℕ) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := by simp [scale_roots, coeff_monomial] {contextual := tt} lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := begin intro h, have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R → ℕ → R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≤ p.support := by { intro, simpa using left_ne_zero_of_mul } lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [coeff_scale_roots, polynomial.mem_support_iff], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_eval₂_eq_zero {p : polynomial S} (f : S →+* R) {r : R} {s : S} (hr : eval₂ f r p = 0) : eval₂ f (f s * r) (scale_roots p s) = 0 := calc eval₂ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : by simp [eval₂_eq_sum, sum_def] ... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (λ i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel], exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * eval₂ f r p : by { simp [eval₂_eq_sum, sum_def] } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {p : polynomial A} {f : A →+* K} (hf : function.injective f) {r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : eval₂ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact @map_ne_zero_of_mem_non_zero_divisors _ _ _ _ _ _ hf ⟨s, hs⟩ end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs end scale_roots
e489a21db572992fd991edb85ad17612e3f3ff0d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/tooManyVarsAtInduction.lean
0afd2467316488fdf8886f4e7ae362f71a740397
[ "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
208
lean
theorem ex1 (n : Nat) : 0 + n = n := by induction n with | succ x ih₁ ih₂ ih₃ => admit | zero => rfl theorem ex2 (n : Nat) : 0 + n = n := by cases n with | succ x ih => admit | zero => rfl
d20831be14eb552f3491bbaddf25e6f7dcfefca5
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter5/5-4.lean
5845e8ba8a6998d841672dd349d04dfe73072fb2
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
966
lean
example (n : ℕ) : n + 1 = nat.succ n := begin show nat.succ n = nat.succ n, reflexivity end example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, split, show q, from hq, show p, from hp end example (p q r : Prop) : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) := begin intro h, cases h with hp hqr, show (p ∧ q) ∨ (p ∧ r), cases hqr with hq hr, have hpq : p ∧ q, from and.intro hp hq, left, exact hpq, have hpr : p ∧ r, from and.intro hp hr, right, exact hpr end example (p q r : Prop) : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) := begin intro h, cases h with hp hqr, show (p ∧ q) ∨ (p ∧ r), cases hqr with hq hr, have hpq : p ∧ q, split, repeat {assumption}, left, exact hpq, have hpr : p ∧ r, split, repeat {assumption}, right, exact hpr end example : ∃ x, x + 2 = 8 := begin let a : ℕ := 3 * 2, existsi a, reflexivity end
bac5266d00444213905113fc7106781b6adcedbb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/log/monotone.lean
8e248092cccd1dd17d834260ad251a3e299ee81f
[ "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,344
lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import analysis.special_functions.pow.real /-! # Logarithm Tonality > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we describe the tonality of the logarithm function when multiplied by functions of the form `x ^ a`. ## Tags logarithm, tonality -/ open set filter function open_locale topology noncomputable theory namespace real variables {x y : ℝ} lemma log_mul_self_monotone_on : monotone_on (λ x : ℝ, log x * x) {x | 1 ≤ x} := begin -- TODO: can be strengthened to exp (-1) ≤ x simp only [monotone_on, mem_set_of_eq], intros x hex y hey hxy, have x_pos : 0 < x := lt_of_lt_of_le zero_lt_one hex, have y_pos : 0 < y := lt_of_lt_of_le zero_lt_one hey, refine mul_le_mul ((log_le_log x_pos y_pos).mpr hxy) hxy (le_of_lt x_pos) _, rwa [le_log_iff_exp_le y_pos, real.exp_zero], end lemma log_div_self_antitone_on : antitone_on (λ x : ℝ, log x / x) {x | exp 1 ≤ x} := begin simp only [antitone_on, mem_set_of_eq], intros x hex y hey hxy, have x_pos : 0 < x := (exp_pos 1).trans_le hex, have y_pos : 0 < y := (exp_pos 1).trans_le hey, have hlogx : 1 ≤ log x := by rwa le_log_iff_exp_le x_pos, have hyx : 0 ≤ y / x - 1 := by rwa [le_sub_iff_add_le, le_div_iff x_pos, zero_add, one_mul], rw [div_le_iff y_pos, ←sub_le_sub_iff_right (log x)], calc log y - log x = log (y / x) : by rw [log_div (y_pos.ne') (x_pos.ne')] ... ≤ (y / x) - 1 : log_le_sub_one_of_pos (div_pos y_pos x_pos) ... ≤ log x * (y / x - 1) : le_mul_of_one_le_left hyx hlogx ... = log x / x * y - log x : by ring, end lemma log_div_self_rpow_antitone_on {a : ℝ} (ha : 0 < a) : antitone_on (λ x : ℝ, log x / x ^ a) {x | exp (1 / a) ≤ x} := begin simp only [antitone_on, mem_set_of_eq], intros x hex y hey hxy, have x_pos : 0 < x := lt_of_lt_of_le (exp_pos (1 / a)) hex, have y_pos : 0 < y := by linarith, have x_nonneg : 0 ≤ x := le_trans (le_of_lt (exp_pos (1 / a))) hex, have y_nonneg : 0 ≤ y := by linarith, nth_rewrite 0 ←rpow_one y, nth_rewrite 0 ←rpow_one x, rw [←div_self (ne_of_lt ha).symm, div_eq_mul_one_div a a, rpow_mul y_nonneg, rpow_mul x_nonneg, log_rpow (rpow_pos_of_pos y_pos a), log_rpow (rpow_pos_of_pos x_pos a), mul_div_assoc, mul_div_assoc, mul_le_mul_left (one_div_pos.mpr ha)], { refine log_div_self_antitone_on _ _ _, { simp only [set.mem_set_of_eq], convert rpow_le_rpow _ hex (le_of_lt ha), rw ←exp_mul, simp only [real.exp_eq_exp], field_simp [(ne_of_lt ha).symm], exact le_of_lt (exp_pos (1 / a)), }, { simp only [set.mem_set_of_eq], convert rpow_le_rpow _ (trans hex hxy) (le_of_lt ha), rw ←exp_mul, simp only [real.exp_eq_exp], field_simp [(ne_of_lt ha).symm], exact le_of_lt (exp_pos (1 / a)), }, exact rpow_le_rpow x_nonneg hxy (le_of_lt ha), }, end lemma log_div_sqrt_antitone_on : antitone_on (λ x : ℝ, log x / sqrt x) {x | exp 2 ≤ x} := begin simp_rw sqrt_eq_rpow, convert @log_div_self_rpow_antitone_on (1 / 2) (by norm_num), norm_num, end end real
3c2f3ab0f684ffcf64e8a1593220ac1d3246d56c
367134ba5a65885e863bdc4507601606690974c1
/src/data/ordmap/ordset.lean
5d1e42de124e593e60d078d88fd2c00bdcb2cdee
[ "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
64,264
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.ordmap.ordnode import algebra.ordered_ring import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {α : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≤ s) : ¬ s ≤ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) h₂) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≤ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode α → ℕ | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode α → Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized α l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized α (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized α t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ l x r, C l → C r → C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : ∀ {t : ordnode α}, sized t → size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, h₂, h₃⟩ := by rw [size, h₁, size_eq_real_size h₂, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node α s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : ∀ (t : ordnode α), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode α) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : ℕ) : Prop := l + r ≤ 1 ∨ (l ≤ delta * r ∧ r ≤ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := λ l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode α → Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced α) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := begin refine or_iff_not_imp_left.2 (λ h, _), refine ⟨_, h₂.resolve_left h⟩, cases H, { cases r₂, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := have l + r₂ ≤ 1 → balanced_sz l r₁, from λ H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (λ H, or.cases_on h₂ this (λ h₂, or.inr ⟨h₂, le_trans h₁ H.2⟩)) theorem balanced.dual : ∀ {t : ordnode α}, balanced t → balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode α → α → ordnode α → ordnode α | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode α → α → ordnode α → ordnode α | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l α l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : ∀ {t : ordnode α} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode α} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l α l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r α l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized α l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized α l) (hr : sized r) : size (@balance' α l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, all P t → all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, h₂, h₃⟩ := ⟨h₁.imp, H _ h₂, h₃.imp⟩ theorem any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, any P t → any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, λ h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, λ h, or.inr (or.inl h)⟩ theorem all_dual {P : α → Prop} : ∀ {t : ordnode α}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, λ ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : α → Prop} : ∀ {t}, all P t ↔ ∀ x, emem x t → P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : α → Prop} : ∀ {t}, any P t ↔ ∃ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : α} {t} : emem x t ↔ ∀ P, all P t → P x := ⟨λ h P al, all_iff_forall.1 al _ h, λ H, H _ $ all_iff_forall.2 $ λ _, id⟩ theorem all_node' {P l x r} : @all α P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all α P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all α P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all α P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all α P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all α P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all α P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all α P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : ∀ (t : ordnode α) (r : list α), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil α) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node α s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : α} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : ∀ t : ordnode α, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode α} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := and_iff_right_of_imp $ λ h, by rw [← length_to_list h₁, h, length_to_list h₂] /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : ∀ t (x : α), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : α) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : ∀ t : ordnode α, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode α) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : ∀ t : ordnode α, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : ∀ s l (x : α) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : ∀ s l (x : α) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : α → Prop} : ∀ t (x : α), all P t → P x → P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, h₂, h₃⟩ hx := find_min'_all _ _ h₁ h₂ @[elab_as_eliminator] theorem find_max'_all {P : α → Prop} : ∀ (x : α) t, P x → all P t → P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, h₂, h₃⟩ := find_max'_all _ _ h₂ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode α) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node α ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] (x : α) : ∀ t : ordnode α, dual (ordnode.insert x t) = @ordnode.insert (order_dual α) _ _ x (dual t) | nil := rfl | (node _ l y r) := begin rw [ordnode.insert, dual, ordnode.insert, order_dual.cmp_le_flip, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance α l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊢, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, have : rrs = 1 := sr.2.2.1, subst rrs, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, have : rls = 1 := sr.2.1.1, subst rls, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊢, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, have : lrs = 1 := sl.2.2.1, subst lrs, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, have : lls = 1 := sl.2.1.1, subst lls, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≤ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≤ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≤ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : @balance_l α l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : ¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : ℕ) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_refl _, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_refl _⟩ }, { rintro ⟨h₁, h₂⟩, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm h₂ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≤ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, nat.sub_le_left_iff_le_add] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≤ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ x₂ r₁ r₂} (H : raised (size r₁) (size r₂)) : raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := begin dsimp [node', size], generalize_hyp : size r₂ = m at H ⊢, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l α l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, H₂⟩⟩ | ⟨r', e, H | ⟨H₁, H₂⟩⟩, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:ℕ)<_) }, { exact le_trans H₂ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 H₂ } } end theorem balance_sz_dual {l r} (H : (∃ l', raised (@size α l) l' ∧ balanced_sz l' (@size α r)) ∨ ∃ r', raised r' (size r) ∧ balanced_sz (size l) r') : (∃ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ λ _, and.imp_right balanced_sz.symm) (Exists.imp $ λ _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l α l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r α l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r α l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder α] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded : ordnode α → with_bot α → with_top α → Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ o₂ := bounded l o₁ ↑x ∧ bounded r ↑x o₂ theorem bounded.dual : ∀ {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂), @bounded (order_dual α) _ (dual t) o₂ o₁ | nil o₁ o₂ h := by cases o₁; cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode α} {o₁ o₂} : bounded t o₁ o₂ ↔ @bounded (order_dual α) _ (dual t) o₂ o₁ := ⟨bounded.dual, λ h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t ⊥ o₂ | nil o₁ o₂ h := by cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t o₁ ⊤ | nil o₁ o₂ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := h.weak_left.weak_right theorem bounded.mono_left {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t ↑y o → bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t o ↑x → bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : ∀ {t : ordnode α} {x y : α}, bounded t x y → x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, h₂⟩ := lt_trans h₁.to_lt h₂.to_lt theorem bounded.to_nil {t : ordnode α} : ∀ {o₁ o₂}, bounded t o₁ o₂ → bounded nil o₁ o₂ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₂ o₁ o₂ | none o₂ h₁ h₂ := h₂.weak_left | (some y) o₂ h₁ h₂ := h₂.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₁ o₁ o₂ | o₁ none h₁ h₂ := h₁.weak_right | o₁ (some y) h₁ h₂ := h₁.mono_right (le_of_lt h₂.to_lt) theorem bounded.mem_lt : ∀ {t o} {x : α}, bounded t o ↑x → all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_lt.imp (λ z h, lt_trans h h₂.to_lt), h₂.to_lt, h₂.mem_lt⟩ theorem bounded.mem_gt : ∀ {t o} {x : α}, bounded t ↑x o → all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp (λ z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil o₁ ↑x → all (< x) t → bounded t o₁ ↑x | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁, h₂.of_lt al₂ al₃⟩ theorem bounded.of_gt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil ↑x o₂ → all (> x) t → bounded t ↑x o₂ | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁.of_gt al₂ al₁, h₂⟩ theorem bounded.to_sep {t₁ t₂ o₁ o₂} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ ↑x o₂) : t₁.all (λ y, t₂.all (λ z : α, y < z)) := h₁.mem_lt.imp $ λ y yx, h₂.mem_gt.imp $ λ z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder α] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot α) (t : ordnode α) (hi : with_top α) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode α) : Prop := valid' ⊥ t ⊤ theorem valid'.mono_left {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x t₂ o₂) : valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ ↑x o₂) : valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil ↑x o₂) (h₂ : all (> x) t) : valid' ↑x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem valid'.valid {t o₁ o₂} (h : @valid' α _ o₁ t o₂) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : bounded nil o₁ o₂) : valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil α) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : ∀ {t : ordnode α} {o₁ o₂} (h : valid' o₁ t o₂), @valid' (order_dual α) _ o₂ (dual t) o₁ | nil o₁ o₂ h := valid'_nil h.1.dual | (node s l x r) o₁ o₂ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode α} {o₁ o₂} : valid' o₁ t o₂ ↔ @valid' (order_dual α) _ o₂ (dual t) o₁ := ⟨valid'.dual, λ h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode α} : valid t → @valid (order_dual α) _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode α} : valid t ↔ @valid (order_dual α) _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' ↑x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node α s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node α s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil ↑x o₂) : valid' o₁ (singleton x : ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (or.inl zero_le_one) rfl theorem valid_singleton {x : α} : valid (singleton x : ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by linarith theorem valid'.node4_l_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≤ 1) ∨ (0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r)) : valid' o₁ (@node4_l α l x m y r) o₂ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mr₂, cases not_le_of_lt Hm mr₂ }, rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂, by_cases mm : size ml + size mr ≤ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨_,⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, nat.le_zero_iff] at mm₂, rw [ml0, mm₂] at mm, cases mm dec_trivial }, cases nat.eq_zero_or_pos (size mr) with mr0 mr0, { rw [mr0, mul_zero, nat.le_zero_iff] at mm₁, rw [mr0, mm₁] at mm, cases mm dec_trivial }, have : 2 * size l ≤ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mm₂, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lr₂ mr₂ mm₁) }, { exact valid'.node4_l_lemma₂ mr₂ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemma₄ lr₁ mr₂ mm₁ }, { exact valid'.node4_l_lemma₅ lr₂ mr₁ mm₂ } } end theorem valid'.rotate_l_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by linarith theorem valid'.rotate_l_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@rotate_l α l x r) o₂ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 → size rl + size rr ≤ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact λ h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := λ l0 : 1 ≤ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1, {intros, linarith}, have hlp : size l > 0 → ¬ size rl + size rr ≤ 1 := λ l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊢, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hb₂⟩, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at hb₂, cases not_le_of_gt rr0 hb₂ }, cases eq_or_lt_of_le (show 1 ≤ size rr, from rr0) with rr1 rr1, { rw [← rr1] at h H2 ⊢, have : size rl = 1 := le_antisymm (nat.lt_succ_iff.1 h) rl0, rw this at H2, exact absurd (le_trans (nat.mul_le_mul_left _ l0) H2) dec_trivial }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hb₂ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemma₂ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hb₂ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@rotate_r α l x r) o₂ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance' α l x r) o₂ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 H₂ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {α l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := begin suffices : @size α r ≤ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≤ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, h₂⟩, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans h₂ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance' α l x r) o₂ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance α l x r) o₂ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance_l α l x r) o₂ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace H₂ : _ ≤ 3 * _ := H₂ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l α l x r) o₂ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@balance_r α l x r) o₂ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ H₂ H₃ end theorem valid'.balance_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r α l x r) o₂ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (@erase_max α (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊢, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' ↑(find_min' l x) (@erase_min α (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : ∀ {t} (h : @valid α _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid α _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact λ x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (λ a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (λ a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact λ y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (λ a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ λ x hx, sep.imp $ λ y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ λ y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ o₂} (hl : valid' o₁ l ↑(x:α)) (hr : valid' ↑x r o₂) : balanced_sz (size l) (size r) → valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node α ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hr₂⟩, {linarith}, suffices H₂, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ H₂ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hr₂ ⊢, linarith } end theorem valid'.merge_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) : valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ o₂ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ o₂, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ λ x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ λ x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (λ x, r.all (λ y, x < y))) : valid (@merge α l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil ↑x o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ o₂ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ o₂ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≤) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, ordnode.insert x t = insert_with (λ _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (λ _ _, ⟨le_refl _, le_refl _⟩) h theorem insert'_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (λ _, id) h end end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type*) [preorder α] := {t : ordnode α // t.valid} namespace ordset open ordnode variable [preorder α] /-- O(1). The empty set. -/ def nil : ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : ordset α := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset α) := ⟨nil⟩ instance : inhabited (ordset α) := ⟨nil⟩ instance : has_singleton α (ordset α) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset α) : Prop := s = ∅ theorem empty_iff {s : ordset α} : s = ∅ ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, λ h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty α _) := λ s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total α (≤)] [@decidable_rel α (≤)] : has_insert α (ordset α) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ end ordset
fcffc76c138e58dd2fbdbcc6ca07a8e30ec1f52b
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Random.lean
84de67063d07a8a956cacf4716634ce11c2242a3
[ "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
4,118
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.Data.Int universe u /- Basic random number generator support based on the one available on the Haskell library -/ /- Interface for random number generators. -/ class RandomGen (g : Type u) where /- `range` returns the range of values returned by the generator. -/ range : g → Nat × Nat /- `next` operation returns a natural number that is uniformly distributed the range returned by `range` (including both end points), and a new generator. -/ next : g → Nat × g /- The 'split' operation allows one to obtain two distinct random number generators. This is very useful in functional programs (for example, when passing a random number generator down to recursive calls). -/ split : g → g × g /- "Standard" random number generator. -/ structure StdGen where s1 : Nat s2 : Nat instance : Inhabited StdGen := ⟨{ s1 := 0, s2 := 0 }⟩ def stdRange := (1, 2147483562) instance : Repr StdGen where reprPrec | ⟨s1, s2⟩, _ => Std.Format.bracket "⟨" (repr s1 ++ ", " ++ repr s2) "⟩" def stdNext : StdGen → Nat × StdGen | ⟨s1, s2⟩ => let s1 : Int := s1 let s2 : Int := s2 let k : Int := s1 / 53668 let s1' : Int := 40014 * ((s1 : Int) - k * 53668) - k * 12211 let s1'' : Int := if s1' < 0 then s1' + 2147483563 else s1' let k' : Int := s2 / 52774 let s2' : Int := 40692 * ((s2 : Int) - k' * 52774) - k' * 3791 let s2'' : Int := if s2' < 0 then s2' + 2147483399 else s2' let z : Int := s1'' - s2'' let z' : Int := if z < 1 then z + 2147483562 else z % 2147483562 (z'.toNat, ⟨s1''.toNat, s2''.toNat⟩) def stdSplit : StdGen → StdGen × StdGen | g@⟨s1, s2⟩ => let newS1 := if s1 = 2147483562 then 1 else s1 + 1 let newS2 := if s2 = 1 then 2147483398 else s2 - 1 let newG := (stdNext g).2 let leftG := StdGen.mk newS1 newG.2 let rightG := StdGen.mk newG.1 newS2 (leftG, rightG) instance : RandomGen StdGen := { range := fun _ => stdRange, next := stdNext, split := stdSplit } /-- Return a standard number generator. -/ def mkStdGen (s : Nat := 0) : StdGen := let q := s / 2147483562 let s1 := s % 2147483562 let s2 := q % 2147483398 ⟨s1 + 1, s2 + 1⟩ /- Auxiliary function for randomNatVal. Generate random values until we exceed the target magnitude. `genLo` and `genMag` are the generator lower bound and magnitude. The parameter `r` is the "remaining" magnitude. -/ private partial def randNatAux {gen : Type u} [RandomGen gen] (genLo genMag : Nat) : Nat → (Nat × gen) → Nat × gen | 0, (v, g) => (v, g) | r'@(r+1), (v, g) => let (x, g') := RandomGen.next g let v' := v*genMag + (x - genLo) randNatAux genLo genMag (r' / genMag - 1) (v', g') /-- Generate a random natural number in the interval [lo, hi]. -/ def randNat {gen : Type u} [RandomGen gen] (g : gen) (lo hi : Nat) : Nat × gen := let lo' := if lo > hi then hi else lo let hi' := if lo > hi then lo else hi let (genLo, genHi) := RandomGen.range g let genMag := genHi - genLo + 1 /- Probabilities of the most likely and least likely result will differ at most by a factor of (1 +- 1/q). Assuming the RandomGen is uniform, of course -/ let q := 1000 let k := hi' - lo' + 1 let tgtMag := k * q let (v, g') := randNatAux genLo genMag tgtMag (0, g) let v' := lo' + (v % k) (v', g') /-- Generate a random Boolean. -/ def randBool {gen : Type u} [RandomGen gen] (g : gen) : Bool × gen := let (v, g') := randNat g 0 1 (v = 1, g') initialize IO.stdGenRef : IO.Ref StdGen ← IO.mkRef mkStdGen def IO.setRandSeed (n : Nat) : IO Unit := IO.stdGenRef.set (mkStdGen n) def IO.rand (lo hi : Nat) : IO Nat := do let gen ← IO.stdGenRef.get let (r, gen) := randNat gen lo hi IO.stdGenRef.set gen pure r
b8e2f248b7cdea77655e866941fb4feec9bb8138
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/witt_vector/witt_polynomial.lean
5d20e8308e910c6c362fbe2f37050b09be7450e0
[ "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
10,755
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.char_p.invertible import data.fintype.card import data.mv_polynomial.variables import data.mv_polynomial.comm_ring import data.mv_polynomial.expand import data.zmod.basic /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open mv_polynomial open finset (hiding map) open finsupp (single) open_locale big_operators local attribute [-simp] coe_eval₂_hom variables (p : ℕ) variables (R : Type*) [comm_ring R] /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R := ∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i : R) lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) : witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) := begin apply sum_congr rfl, rintro i -, rw [monomial_eq, finsupp.prod_single_index], rw pow_zero, end /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit localized "notation (name := witt_polynomial) `W_` := witt_polynomial p" in witt -- Notation with ring of coefficients implicit localized "notation (name := witt_polynomial.infer) `W` := witt_polynomial p hole!" in witt open_locale witt open mv_polynomial /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) : map f (W n) = W n := begin rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl], intros i hi, rw [map_monomial, ring_hom.map_pow, map_nat_cast], end variables (R) @[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) : constant_coeff (witt_polynomial p R n) = 0 := begin simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial], rw [sum_eq_zero], rintro i hi, rw [if_neg], rw [finsupp.single_eq_zero], exact ne_of_gt (pow_pos hp.1.pos _) end @[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 := by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero] @[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p := by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ_comm, range_one, sum_singleton, one_mul, pow_one, C_1, pow_zero] lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) := by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index] /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th Witt polynomial by `p`. -/ @[simp] lemma witt_polynomial_zmod_self (n : ℕ) : W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) := begin simp only [witt_polynomial_eq_sum_C_mul_X_pow], rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul, add_zero, alg_hom.map_sum, sum_congr rfl], intros k hk, rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ], congr, rw mem_range at hk, rw [add_comm, add_tsub_assoc_of_le (nat.lt_succ_iff.mp hk), ← add_comm], end section p_prime variables [hp : ne_zero p] include hp lemma witt_polynomial_vars [char_zero R] (n : ℕ) : (witt_polynomial p R n).vars = range (n + 1) := begin have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i}, { intro i, refine vars_monomial_single i (pow_ne_zero _ hp.1) _, rw [← nat.cast_pow, nat.cast_ne_zero], exact pow_ne_zero i hp.1 }, rw [witt_polynomial, vars_sum_of_disjoint], { simp only [this, bUnion_singleton_eq_self], }, { simp only [this], intros a b h, apply disjoint_singleton_left.mpr, rwa mem_singleton, }, end lemma witt_polynomial_vars_subset (n : ℕ) : (witt_polynomial p R n).vars ⊆ range (n + 1) := begin rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ], apply vars_map, end end p_prime end /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ noncomputable def X_in_terms_of_W [invertible (p : R)] : ℕ → mv_polynomial ℕ R | n := (X n - (∑ i : fin n, have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R) lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} : X_in_terms_of_W p R n = (X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) := by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] } @[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) : constant_coeff (X_in_terms_of_W p R n) = 0 := begin apply nat.strong_induction_on n; clear n, intros n IH, rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum, constant_coeff_C, sum_eq_zero], { simp only [constant_coeff_X, sub_zero, mul_zero] }, { intros m H, rw mem_range at H, simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H], rw [zero_pow, mul_zero], apply pow_pos hp.1.pos, } end @[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] : X_in_terms_of_W p R 0 = X 0 := by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero] section p_prime variables [hp : fact p.prime] include hp lemma X_in_terms_of_W_vars_aux (n : ℕ) : n ∈ (X_in_terms_of_W p ℚ n).vars ∧ (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := begin apply nat.strong_induction_on n, clear n, intros n ih, rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ, insert_eq], swap 3, { apply nonzero_of_invertible }, work_on_goal 1 { simp only [true_and, true_or, eq_self_iff_true, mem_union, mem_singleton], intro i, rw [mem_union, mem_union], apply or.imp id }, work_on_goal 2 { rw [vars_X, disjoint_singleton_left] }, all_goals { intro H, replace H := vars_sum_subset _ _ H, rw mem_bUnion at H, rcases H with ⟨j, hj, H⟩, rw vars_C_mul at H, swap, { apply pow_ne_zero, exact_mod_cast hp.1.ne_zero }, rw mem_range at hj, replace H := (ih j hj).2 (vars_pow _ _ H), rw mem_range at H }, { rw mem_range, exact lt_of_lt_of_le H hj }, { exact lt_irrefl n (lt_of_lt_of_le H hj) }, end lemma X_in_terms_of_W_vars_subset (n : ℕ) : (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := (X_in_terms_of_W_vars_aux p n).2 end p_prime lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) : X_in_terms_of_W p R n * C (p^n : R) = X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) := by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one] @[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) : bind₁ (X_in_terms_of_W p R) (W_ R k) = X k := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum], simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C], rw [sum_range_succ_comm, tsub_self, pow_zero, pow_one, bind₁_X_right, mul_comm, ← C_pow, X_in_terms_of_W_aux], simp only [C_pow, bind₁_X_right, sub_add_cancel], end @[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) : bind₁ (W_ R) (X_in_terms_of_W p R n) = X n := begin apply nat.strong_induction_on n, clear n, intros n H, rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C, alg_hom.map_sum], have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n, by simp only [witt_polynomial_eq_sum_C_mul_X_pow, tsub_self, sum_range_succ_comm, pow_one, add_sub_cancel, pow_zero], rw [sum_congr rfl, this], { -- this is really slow for some reason rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] }, { intros i h, rw mem_range at h, simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] }, end
0a0303718ece2542dfe5b6ae93e2ce683651e529
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/lie_algebra.lean
bceab4a880110d662b767b29ef0eb18b1fae792f
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
17,314
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import ring_theory.algebra data.matrix.basic linear_algebra.linear_action /-! # Lie algebras This file defines Lie rings, and Lie algebras over a commutative ring. It shows how these arise from associative rings and algebras via the ring commutator. In particular it defines the Lie algebra of endomorphisms of a module as well as of the algebra of square matrices over a commutative ring. It also includes definitions of morphisms of Lie algebras, Lie subalgebras, Lie modules, Lie submodules, and the quotient of a Lie algebra by an ideal. ## Notations We introduce the notation ⁅x, y⁆ for the Lie bracket. Note that these are the Unicode "square with quill" brackets rather than the usual square brackets. We also introduce the notations L →ₗ⁅R⁆ L' for a morphism of Lie algebras over a commutative ring R, and L →ₗ⁅⁆ L' for the same, when the ring is implicit. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure, and thus are partially unbundled. Since they extend Lie rings, these are also partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*][bourbaki1975] ## Tags lie bracket, ring commutator, jacobi identity, lie ring, lie algebra -/ universes u v /-- A binary operation, intended use in Lie algebras and similar structures. -/ class has_bracket (L : Type v) := (bracket : L → L → L) notation `⁅`x`,` y`⁆` := has_bracket.bracket x y namespace ring_commutator variables {A : Type v} [ring A] /-- The ring commutator captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ def commutator (x y : A) := x*y - y*x local notation `⁅`x`,` y`⁆` := commutator x y @[simp] lemma add_left (x y z : A) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma add_right (x y z : A) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma alternate (x : A) : ⁅x, x⁆ = 0 := by simp [commutator] lemma jacobi (x y z : A) : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := begin unfold commutator, repeat { rw mul_sub_left_distrib }, repeat { rw mul_sub_right_distrib }, repeat { rw add_sub }, repeat { rw ←sub_add }, repeat { rw ←mul_assoc }, have h : ∀ (x y z : A), x - y + z + y = x+z := by simp [sub_eq_add_neg, add_left_comm], repeat { rw h }, simp [sub_eq_add_neg, add_left_comm], end end ring_commutator section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. The bracket is not associative unless it is identically zero. -/ class lie_ring (L : Type v) extends add_comm_group L, has_bracket L := (add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : ∀ (x y z : L), ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆) (lie_self : ∀ (x : L), ⁅x, x⁆ = 0) (jacobi : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0) end prio section lie_ring variables {L : Type v} [lie_ring L] @[simp] lemma add_lie (x y z : L) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := lie_ring.add_lie x y z @[simp] lemma lie_add (x y z : L) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := lie_ring.lie_add x y z @[simp] lemma lie_self (x : L) : ⁅x, x⁆ = 0 := lie_ring.lie_self x @[simp] lemma lie_skew (x y : L) : -⁅y, x⁆ = ⁅x, y⁆ := begin symmetry, rw [←sub_eq_zero_iff_eq, sub_neg_eq_add], have H : ⁅x + y, x + y⁆ = 0, from lie_self _, rw add_lie at H, simpa using H, end @[simp] lemma lie_zero (x : L) : ⁅x, 0⁆ = 0 := begin have H : ⁅x, 0⁆ + ⁅x, 0⁆ = ⁅x, 0⁆ + 0 := by { rw ←lie_add, simp, }, exact add_left_cancel H, end @[simp] lemma zero_lie (x : L) : ⁅0, x⁆ = 0 := by { rw [←lie_skew, lie_zero], simp, } @[simp] lemma neg_lie (x y : L) : ⁅-x, y⁆ = -⁅x, y⁆ := by { rw [←sub_eq_zero_iff_eq, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg (x y : L) : ⁅x, -y⁆ = -⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew], simp, } @[simp] lemma gsmul_lie (x y : L) (n : ℤ) : ⁅n • x, y⁆ = n • ⁅x, y⁆ := add_monoid_hom.map_gsmul ⟨λ x, ⁅x, y⁆, zero_lie y, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_gsmul (x y : L) (n : ℤ) : ⁅x, n • y⁆ = n • ⁅x, y⁆ := begin rw [←lie_skew, ←lie_skew x, gsmul_lie], unfold has_scalar.smul, rw gsmul_neg, end /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ def lie_ring.of_associative_ring (A : Type v) [ring A] : lie_ring A := { bracket := ring_commutator.commutator, add_lie := ring_commutator.add_left, lie_add := ring_commutator.add_right, lie_self := ring_commutator.alternate, jacobi := ring_commutator.jacobi } end lie_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends module R L := (lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆) end prio @[simp] lemma lie_smul (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅x, t • y⁆ = t • ⁅x, y⁆ := lie_algebra.lie_smul t x y @[simp] lemma smul_lie (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅t • x, y⁆ = t • ⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew x y], simp [-lie_skew], } namespace lie_algebra /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure morphism (R : Type u) (L : Type v) (L' : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends linear_map R L L' := (map_lie : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) infixr ` →ₗ⁅⁆ `:25 := morphism _ notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := morphism R L L' instance (R : Type u) (L : Type v) (L' : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] : has_coe (L →ₗ⁅R⁆ L') (L →ₗ[R] L') := ⟨morphism.to_linear_map⟩ lemma map_lie {R : Type u} {L : Type v} {L' : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] (f : L →ₗ⁅R⁆ L') (x y : L) : f ⁅x, y⁆ = ⁅f x, f y⁆ := morphism.map_lie f @[simp] lemma map_lie' {R : Type u} {L : Type v} {L' : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] (f : L →ₗ⁅R⁆ L') (x y : L) : (f : L →ₗ[R] L') ⁅x, y⁆ = ⁅f x, f y⁆ := morphism.map_lie f variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ def of_associative_algebra (A : Type v) [ring A] [algebra R A] : @lie_algebra R A _ (lie_ring.of_associative_ring _) := { lie_smul := begin intros, show _ - _ = _ • (_ - _), rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], end } instance (M : Type v) [add_comm_group M] [module R M] : lie_ring (module.End R M) := lie_ring.of_associative_ring _ /-- An important class of Lie algebras are those arising from the associative algebra structure on module endomorphisms. -/ instance of_endomorphism_algebra (M : Type v) [add_comm_group M] [module R M] : lie_algebra R (module.End R M) := of_associative_algebra (module.End R M) lemma endo_algebra_bracket (M : Type v) [add_comm_group M] [module R M] (f g : module.End R M) : ⁅f, g⁆ = f.comp g - g.comp f := rfl /-- The adjoint action of a Lie algebra on itself. -/ def Ad : L →ₗ⁅R⁆ module.End R L := { to_fun := λ x, { to_fun := has_bracket.bracket x, add := by { intros, apply lie_add, }, smul := by { intros, apply lie_smul, } }, add := by { intros, ext, simp, }, smul := by { intros, ext, simp, }, map_lie := by { intros x y, ext z, rw endo_algebra_bracket, suffices : ⁅⁅x, y⁆, z⁆ = ⁅x, ⁅y, z⁆⁆ + ⁅⁅x, z⁆, y⁆, by simpa [sub_eq_add_neg], rw [eq_comm, ←lie_skew ⁅x, y⁆ z, ←lie_skew ⁅x, z⁆ y, ←lie_skew x z, lie_neg, neg_neg, ←sub_eq_zero_iff_eq, sub_neg_eq_add, lie_ring.jacobi], } } end lie_algebra section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) instance lie_subalgebra_coe_submodule : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ /-- A Lie subalgebra forms a new Lie ring. This cannot be an instance, since being a Lie subalgebra is (currently) not a class. -/ def lie_subalgebra_lie_ring (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, jacobi := by { intros, apply set_coe.ext, apply lie_ring.jacobi, } } /-- A Lie subalgebra forms a new Lie algebra. This cannot be an instance, since being a Lie subalgebra is (currently) not a class. -/ def lie_subalgebra_lie_algebra (L' : lie_subalgebra R L) : @lie_algebra R L' _ (lie_subalgebra_lie_ring _ _ _) := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } end lie_subalgebra section lie_module variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] variables (M : Type v) [add_comm_group M] [module R M] section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ class lie_module extends linear_action R L M := (lie_act : ∀ (l l' : L) (m : M), act ⁅l, l'⁆ m = act l (act l' m) - act l' (act l m)) end prio @[simp] lemma lie_act [lie_module R L M] (l l' : L) (m : M) : linear_action.act R ⁅l, l'⁆ m = linear_action.act R l (linear_action.act R l' m) - linear_action.act R l' (linear_action.act R l m) := lie_module.lie_act R l l' m protected lemma of_endo_map_action (α : L →ₗ⁅R⁆ module.End R M) (x : L) (m : M) : @linear_action.act R _ _ _ _ _ _ _ (linear_action.of_endo_map R L M α) x m = α x m := rfl /-- A Lie morphism from a Lie algebra to the endomorphism algebra of a module yields a Lie module structure. -/ def lie_module.of_endo_morphism (α : L →ₗ⁅R⁆ module.End R M) : lie_module R L M := { lie_act := by { intros x y m, rw [of_endo_map_action, lie_algebra.map_lie, lie_algebra.endo_algebra_bracket], refl, }, ..(linear_action.of_endo_map R L M α) } /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := lie_module.of_endo_morphism R L L lie_algebra.Ad /-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie module. -/ structure lie_submodule [lie_module R L M] extends submodule R M := (lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → linear_action.act R x m ∈ carrier) instance lie_submodule_coe_submodule [lie_module R L M] : has_coe (lie_submodule R L M) (submodule R M) := ⟨lie_submodule.to_submodule⟩ instance lie_submodule_has_mem [lie_module R L M] : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩ instance lie_submodule_lie_module [lie_module R L M] (N : lie_submodule R L M) : lie_module R L N := { act := λ x m, ⟨linear_action.act R x m.val, N.lie_mem m.property⟩, add_act := by { intros x y m, apply set_coe.ext, apply linear_action.add_act, }, act_add := by { intros x m n, apply set_coe.ext, apply linear_action.act_add, }, act_smul := by { intros r x y, apply set_coe.ext, apply linear_action.act_smul, }, smul_act := by { intros r x y, apply set_coe.ext, apply linear_action.smul_act, }, lie_act := by { intros x y m, apply set_coe.ext, apply lie_module.lie_act, } } /-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/ abbreviation lie_ideal := lie_submodule R L L lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I := by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, } /-- An ideal of a Lie algebra is a Lie subalgebra. -/ def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L := { lie_mem := by { intros x y hx hy, apply lie_mem_right, exact hy, }, ..I.to_submodule, } end lie_module namespace lie_submodule variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] variables {M : Type v} [add_comm_group M] [module R M] [lie_module R L M] variables (N : lie_submodule R L M) (I : lie_ideal R L) /-- The quotient of a Lie module by a Lie submodule. It is a Lie module. -/ abbreviation quotient := N.to_submodule.quotient namespace quotient variables {N I} /-- Map sending an element of `M` to the corresponding element of `M/N`, when `N` is a lie_submodule of the lie_module `N`. -/ abbreviation mk : M → N.quotient := submodule.quotient.mk lemma is_quotient_mk (m : M) : quotient.mk' m = (mk m : N.quotient) := rfl instance lie_quotient_has_bracket : has_bracket (quotient I) := ⟨by { intros x y, apply quotient.lift_on₂' x y (λ x' y', mk ⁅x', y'⁆), intros x₁ x₂ y₁ y₂ h₁ h₂, apply (submodule.quotient.eq I.to_submodule).2, have h : ⁅x₁, x₂⁆ - ⁅y₁, y₂⁆ = ⁅x₁, x₂ - y₂⁆ + ⁅x₁ - y₁, y₂⁆ := by simp [-lie_skew, sub_eq_add_neg], rw h, apply submodule.add_mem, { apply lie_mem_right R L I x₁ (x₂ - y₂) h₂, }, { apply lie_mem_left R L I (x₁ - y₁) y₂ h₁, }, }⟩ @[simp] lemma mk_bracket (x y : L) : (mk ⁅x, y⁆ : quotient I) = ⁅mk x, mk y⁆ := rfl instance lie_quotient_lie_ring : lie_ring (quotient I) := { add_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply add_lie, }, lie_add := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_add, }, lie_self := by { intros x', apply quotient.induction_on' x', intros x, rw [is_quotient_mk, ←mk_bracket], apply congr_arg, apply lie_self, }, jacobi := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_ring.jacobi, } } instance lie_quotient_lie_algebra : lie_algebra R (quotient I) := { lie_smul := by { intros t x' y', apply quotient.induction_on₂' x' y', intros x y, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_smul, }, apply congr_arg, apply lie_smul, } } end quotient end lie_submodule /-- An important class of Lie rings are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_ring (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_ring R] : lie_ring (matrix n n R) := lie_ring.of_associative_ring (matrix n n R) /-- An important class of Lie algebras are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_algebra (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_ring R] : @lie_algebra R (matrix n n R) _ (matrix.lie_ring _ _) := lie_algebra.of_associative_algebra (matrix n n R)
81a3bf0358865f008a21e75fa7e923b335308700
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/metric_space/hausdorff_dimension.lean
28dd8e7a54eeb39c84d3d1af5cafc1949f9443e7
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
22,834
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.hausdorff /-! # Hausdorff dimension The Hausdorff dimension of a set `X` in an (extended) metric space is the unique number `dimH s : ℝ≥0∞` such that for any `d : ℝ≥0` we have - `μH[d] s = 0` if `dimH s < d`, and - `μH[d] s = ∞` if `d < dimH s`. In this file we define `dimH s` to be the Hausdorff dimension of `s`, then prove some basic properties of Hausdorff dimension. ## Main definitions * `measure_theory.dimH`: the Hausdorff dimension of a set. For the Hausdorff dimension of the whole space we use `measure_theory.dimH (set.univ : set X)`. ## Main results ### Basic properties of Hausdorff dimension * `hausdorff_measure_of_lt_dimH`, `dimH_le_of_hausdorff_measure_ne_top`, `le_dimH_of_hausdorff_measure_eq_top`, `hausdorff_measure_of_dimH_lt`, `measure_zero_of_dimH_lt`, `le_dimH_of_hausdorff_measure_ne_zero`, `dimH_of_hausdorff_measure_ne_zero_ne_top`: various forms of the characteristic property of the Hausdorff dimension; * `dimH_union`: the Hausdorff dimension of the union of two sets is the maximum of their Hausdorff dimensions. * `dimH_Union`, `dimH_bUnion`, `dimH_sUnion`: the Hausdorff dimension of a countable union of sets is the supremum of their Hausdorff dimensions; * `dimH_empty`, `dimH_singleton`, `set.subsingleton.dimH_zero`, `set.countable.dimH_zero` : `dimH s = 0` whenever `s` is countable; ### (Pre)images under (anti)lipschitz and Hölder continuous maps * `holder_with.dimH_image_le` etc: if `f : X → Y` is Hölder continuous with exponent `r > 0`, then for any `s`, `dimH (f '' s) ≤ dimH s / r`. We prove versions of this statement for `holder_with`, `holder_on_with`, and locally Hölder maps, as well as for `set.image` and `set.range`. * `lipschitz_with.dimH_image_le` etc: Lipschitz continuous maps do not increase the Hausdorff dimension of sets. * for a map that is known to be both Lipschitz and antilipschitz (e.g., for an `isometry` or a `continuous_linear_equiv`) we also prove `dimH (f '' s) = dimH s`. ### Hausdorff measure in `ℝⁿ` * `real.dimH_of_nonempty_interior`: if `s` is a set in a finite dimensional real vector space `E` with nonempty interior, then the Hausdorff dimension of `s` is equal to the dimension of `E`. * `dense_compl_of_dimH_lt_finrank`: if `s` is a set in a finite dimensional real vector space `E` with Hausdorff dimension strictly less than the dimension of `E`, the `s` has a dense complement. * `cont_diff.dense_compl_range_of_finrank_lt_finrank`: the complement to the range of a `C¹` smooth map is dense provided that the dimension of the domain is strictly less than the dimension of the codomain. ## Notations We use the following notation localized in `measure_theory`. It is defined in `measure_theory.measure.hausdorff`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes * The definition of `dimH` explicitly uses `borel X` as a measurable space structure. This way we can formulate lemmas about Hausdorff dimension without assuming that the environment has a `[measurable_space X]` instance that is equal but possibly not defeq to `borel X`. Lemma `dimH_def` unfolds this definition using whatever `[measurable_space X]` instance we have in the environment (as long as it is equal to `borel X`). * The definition `dimH` is irreducible; use API lemmas or `dimH_def` instead. ## Tags Hausdorff measure, Hausdorff dimension, dimension -/ open_locale measure_theory ennreal nnreal topological_space open measure_theory measure_theory.measure set topological_space finite_dimensional filter variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] /-- Hausdorff dimension of a set in an (e)metric space. -/ @[irreducible] noncomputable def dimH (s : set X) : ℝ≥0∞ := by { borelize X, exact ⨆ (d : ℝ≥0) (hd : @hausdorff_measure X _ _ ⟨rfl⟩ d s = ∞), d } /-! ### Basic properties -/ section measurable variables [measurable_space X] [borel_space X] /-- Unfold the definition of `dimH` using `[measurable_space X] [borel_space X]` from the environment. -/ lemma dimH_def (s : set X) : dimH s = ⨆ (d : ℝ≥0) (hd : μH[d] s = ∞), d := by { borelize X, rw dimH } lemma hausdorff_measure_of_lt_dimH {s : set X} {d : ℝ≥0} (h : ↑d < dimH s) : μH[d] s = ∞ := begin simp only [dimH_def, lt_supr_iff] at h, rcases h with ⟨d', hsd', hdd'⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hdd', exact top_unique (hsd' ▸ hausdorff_measure_mono hdd'.le _) end lemma dimH_le {s : set X} {d : ℝ≥0∞} (H : ∀ d' : ℝ≥0, μH[d'] s = ∞ → ↑d' ≤ d) : dimH s ≤ d := (dimH_def s).trans_le $ supr₂_le H lemma dimH_le_of_hausdorff_measure_ne_top {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ ∞) : dimH s ≤ d := le_of_not_lt $ mt hausdorff_measure_of_lt_dimH h lemma le_dimH_of_hausdorff_measure_eq_top {s : set X} {d : ℝ≥0} (h : μH[d] s = ∞) : ↑d ≤ dimH s := by { rw dimH_def, exact le_supr₂ d h } lemma hausdorff_measure_of_dimH_lt {s : set X} {d : ℝ≥0} (h : dimH s < d) : μH[d] s = 0 := begin rw dimH_def at h, rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨d', hsd', hd'd⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hd'd, exact (hausdorff_measure_zero_or_top hd'd s).resolve_right (λ h, hsd'.not_le $ le_supr₂ d' h) end lemma measure_zero_of_dimH_lt {μ : measure X} {d : ℝ≥0} (h : μ ≪ μH[d]) {s : set X} (hd : dimH s < d) : μ s = 0 := h $ hausdorff_measure_of_dimH_lt hd lemma le_dimH_of_hausdorff_measure_ne_zero {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ 0) : ↑d ≤ dimH s := le_of_not_lt $ mt hausdorff_measure_of_dimH_lt h lemma dimH_of_hausdorff_measure_ne_zero_ne_top {d : ℝ≥0} {s : set X} (h : μH[d] s ≠ 0) (h' : μH[d] s ≠ ∞) : dimH s = d := le_antisymm (dimH_le_of_hausdorff_measure_ne_top h') (le_dimH_of_hausdorff_measure_ne_zero h) end measurable @[mono] lemma dimH_mono {s t : set X} (h : s ⊆ t) : dimH s ≤ dimH t := begin borelize X, exact dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top $ top_unique $ hd ▸ measure_mono h) end lemma dimH_subsingleton {s : set X} (h : s.subsingleton) : dimH s = 0 := begin borelize X, apply le_antisymm _ (zero_le _), refine dimH_le_of_hausdorff_measure_ne_top _, exact ((hausdorff_measure_le_one_of_subsingleton h le_rfl).trans_lt ennreal.one_lt_top).ne, end alias dimH_subsingleton ← set.subsingleton.dimH_zero @[simp] lemma dimH_empty : dimH (∅ : set X) = 0 := subsingleton_empty.dimH_zero @[simp] lemma dimH_singleton (x : X) : dimH ({x} : set X) = 0 := subsingleton_singleton.dimH_zero @[simp] lemma dimH_Union [encodable ι] (s : ι → set X) : dimH (⋃ i, s i) = ⨆ i, dimH (s i) := begin borelize X, refine le_antisymm (dimH_le $ λ d hd, _) (supr_le $ λ i, dimH_mono $ subset_Union _ _), contrapose! hd, have : ∀ i, μH[d] (s i) = 0, from λ i, hausdorff_measure_of_dimH_lt ((le_supr (λ i, dimH (s i)) i).trans_lt hd), rw measure_Union_null this, exact ennreal.zero_ne_top end @[simp] lemma dimH_bUnion {s : set ι} (hs : s.countable) (t : ι → set X) : dimH (⋃ i ∈ s, t i) = ⨆ i ∈ s, dimH (t i) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union, dimH_Union, ← supr_subtype''] end @[simp] lemma dimH_sUnion {S : set (set X)} (hS : S.countable) : dimH (⋃₀ S) = ⨆ s ∈ S, dimH s := by rw [sUnion_eq_bUnion, dimH_bUnion hS] @[simp] lemma dimH_union (s t : set X) : dimH (s ∪ t) = max (dimH s) (dimH t) := by rw [union_eq_Union, dimH_Union, supr_bool_eq, cond, cond, ennreal.sup_eq_max] lemma dimH_countable {s : set X} (hs : s.countable) : dimH s = 0 := bUnion_of_singleton s ▸ by simp only [dimH_bUnion hs, dimH_singleton, ennreal.supr_zero_eq_zero] alias dimH_countable ← set.countable.dimH_zero lemma dimH_finite {s : set X} (hs : s.finite) : dimH s = 0 := hs.countable.dimH_zero alias dimH_finite ← set.finite.dimH_zero @[simp] lemma dimH_coe_finset (s : finset X) : dimH (s : set X) = 0 := s.finite_to_set.dimH_zero alias dimH_coe_finset ← finset.dimH_zero /-! ### Hausdorff dimension as the supremum of local Hausdorff dimensions -/ section variables [second_countable_topology X] /-- If `r` is less than the Hausdorff dimension of a set `s` in an (extended) metric space with second countable topology, then there exists a point `x ∈ s` such that every neighborhood `t` of `x` within `s` has Hausdorff dimension greater than `r`. -/ lemma exists_mem_nhds_within_lt_dimH_of_lt_dimH {s : set X} {r : ℝ≥0∞} (h : r < dimH s) : ∃ x ∈ s, ∀ t ∈ 𝓝[s] x, r < dimH t := begin contrapose! h, choose! t htx htr using h, rcases countable_cover_nhds_within htx with ⟨S, hSs, hSc, hSU⟩, calc dimH s ≤ dimH (⋃ x ∈ S, t x) : dimH_mono hSU ... = ⨆ x ∈ S, dimH (t x) : dimH_bUnion hSc _ ... ≤ r : supr₂_le (λ x hx, htr x $ hSs hx) end /-- In an (extended) metric space with second countable topology, the Hausdorff dimension of a set `s` is the supremum over `x ∈ s` of the limit superiors of `dimH t` along `(𝓝[s] x).small_sets`. -/ lemma bsupr_limsup_dimH (s : set X) : (⨆ x ∈ s, limsup dimH (𝓝[s] x).small_sets) = dimH s := begin refine le_antisymm (supr₂_le $ λ x hx, _) _, { refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _), exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ }, { refine le_of_forall_ge_of_dense (λ r hr, _), rcases exists_mem_nhds_within_lt_dimH_of_lt_dimH hr with ⟨x, hxs, hxr⟩, refine le_supr₂_of_le x hxs _, rw limsup_eq, refine le_Inf (λ b hb, _), rcases eventually_small_sets.1 hb with ⟨t, htx, ht⟩, exact (hxr t htx).le.trans (ht t subset.rfl) } end /-- In an (extended) metric space with second countable topology, the Hausdorff dimension of a set `s` is the supremum over all `x` of the limit superiors of `dimH t` along `(𝓝[s] x).small_sets`. -/ lemma supr_limsup_dimH (s : set X) : (⨆ x, limsup dimH (𝓝[s] x).small_sets) = dimH s := begin refine le_antisymm (supr_le $ λ x, _) _, { refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _), exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ }, { rw ← bsupr_limsup_dimH, exact supr₂_le_supr _ _ } end end /-! ### Hausdorff dimension and Hölder continuity -/ variables {C K r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f` is a Hölder continuous map with exponent `r > 0`, then `dimH (f '' s) ≤ dimH s / r`. -/ lemma holder_on_with.dimH_image_le (h : holder_on_with C r f s) (hr : 0 < r) : dimH (f '' s) ≤ dimH s / r := begin borelize [X, Y], refine dimH_le (λ d hd, _), have := h.hausdorff_measure_image_le hr d.coe_nonneg, rw [hd, ennreal.coe_rpow_of_nonneg _ d.coe_nonneg, top_le_iff] at this, have Hrd : μH[(r * d : ℝ≥0)] s = ⊤, { contrapose this, exact ennreal.mul_ne_top ennreal.coe_ne_top this }, rw [ennreal.le_div_iff_mul_le, mul_comm, ← ennreal.coe_mul], exacts [le_dimH_of_hausdorff_measure_eq_top Hrd, or.inl (mt ennreal.coe_eq_zero.1 hr.ne'), or.inl ennreal.coe_ne_top] end namespace holder_with /-- If `f : X → Y` is Hölder continuous with a positive exponent `r`, then the Hausdorff dimension of the image of a set `s` is at most `dimH s / r`. -/ lemma dimH_image_le (h : holder_with C r f) (hr : 0 < r) (s : set X) : dimH (f '' s) ≤ dimH s / r := (h.holder_on_with s).dimH_image_le hr /-- If `f` is a Hölder continuous map with exponent `r > 0`, then the Hausdorff dimension of its range is at most the Hausdorff dimension of its domain divided by `r`. -/ lemma dimH_range_le (h : holder_with C r f) (hr : 0 < r) : dimH (range f) ≤ dimH (univ : set X) / r := @image_univ _ _ f ▸ h.dimH_image_le hr univ end holder_with /-- If `s` is a set in a space `X` with second countable topology and `f : X → Y` is Hölder continuous in a neighborhood within `s` of every point `x ∈ s` with the same positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the image `f '' s` is at most the Hausdorff dimension of `s` divided by `r`. -/ lemma dimH_image_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y} (hr : 0 < r) {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C r f t) : dimH (f '' s) ≤ dimH s / r := begin choose! C t htn hC using hf, rcases countable_cover_nhds_within htn with ⟨u, hus, huc, huU⟩, replace huU := inter_eq_self_of_subset_left huU, rw inter_Union₂ at huU, rw [← huU, image_Union₂, dimH_bUnion huc, dimH_bUnion huc], simp only [ennreal.supr_div], exact supr₂_mono (λ x hx, ((hC x (hus hx)).mono (inter_subset_right _ _)).dimH_image_le hr) end /-- If `f : X → Y` is Hölder continuous in a neighborhood of every point `x : X` with the same positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the range of `f` is at most the Hausdorff dimension of `X` divided by `r`. -/ lemma dimH_range_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y} (hr : 0 < r) (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), holder_on_with C r f s) : dimH (range f) ≤ dimH (univ : set X) / r := begin rw ← image_univ, refine dimH_image_le_of_locally_holder_on hr (λ x _, _), simpa only [exists_prop, nhds_within_univ] using hf x end /-! ### Hausdorff dimension and Lipschitz continuity -/ /-- If `f : X → Y` is Lipschitz continuous on `s`, then `dimH (f '' s) ≤ dimH s`. -/ lemma lipschitz_on_with.dimH_image_le (h : lipschitz_on_with K f s) : dimH (f '' s) ≤ dimH s := by simpa using h.holder_on_with.dimH_image_le zero_lt_one namespace lipschitz_with /-- If `f` is a Lipschitz continuous map, then `dimH (f '' s) ≤ dimH s`. -/ lemma dimH_image_le (h : lipschitz_with K f) (s : set X) : dimH (f '' s) ≤ dimH s := (h.lipschitz_on_with s).dimH_image_le /-- If `f` is a Lipschitz continuous map, then the Hausdorff dimension of its range is at most the Hausdorff dimension of its domain. -/ lemma dimH_range_le (h : lipschitz_with K f) : dimH (range f) ≤ dimH (univ : set X) := @image_univ _ _ f ▸ h.dimH_image_le univ end lipschitz_with /-- If `s` is a set in an extended metric space `X` with second countable topology and `f : X → Y` is Lipschitz in a neighborhood within `s` of every point `x ∈ s`, then the Hausdorff dimension of the image `f '' s` is at most the Hausdorff dimension of `s`. -/ lemma dimH_image_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y} {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with C f t) : dimH (f '' s) ≤ dimH s := begin have : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C 1 f t, by simpa only [holder_on_with_one] using hf, simpa only [ennreal.coe_one, div_one] using dimH_image_le_of_locally_holder_on zero_lt_one this end /-- If `f : X → Y` is Lipschitz in a neighborhood of each point `x : X`, then the Hausdorff dimension of `range f` is at most the Hausdorff dimension of `X`. -/ lemma dimH_range_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y} (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), lipschitz_on_with C f s) : dimH (range f) ≤ dimH (univ : set X) := begin rw ← image_univ, refine dimH_image_le_of_locally_lipschitz_on (λ x _, _), simpa only [exists_prop, nhds_within_univ] using hf x end namespace antilipschitz_with lemma dimH_preimage_le (hf : antilipschitz_with K f) (s : set Y) : dimH (f ⁻¹' s) ≤ dimH s := begin borelize [X, Y], refine dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top _), have := hf.hausdorff_measure_preimage_le d.coe_nonneg s, rw [hd, top_le_iff] at this, contrapose! this, exact ennreal.mul_ne_top (by simp) this end lemma le_dimH_image (hf : antilipschitz_with K f) (s : set X) : dimH s ≤ dimH (f '' s) := calc dimH s ≤ dimH (f ⁻¹' (f '' s)) : dimH_mono (subset_preimage_image _ _) ... ≤ dimH (f '' s) : hf.dimH_preimage_le _ end antilipschitz_with /-! ### Isometries preserve Hausdorff dimension -/ lemma isometry.dimH_image (hf : isometry f) (s : set X) : dimH (f '' s) = dimH s := le_antisymm (hf.lipschitz.dimH_image_le _) (hf.antilipschitz.le_dimH_image _) namespace isometric @[simp] lemma dimH_image (e : X ≃ᵢ Y) (s : set X) : dimH (e '' s) = dimH s := e.isometry.dimH_image s @[simp] lemma dimH_preimage (e : X ≃ᵢ Y) (s : set Y) : dimH (e ⁻¹' s) = dimH s := by rw [← e.image_symm, e.symm.dimH_image] lemma dimH_univ (e : X ≃ᵢ Y) : dimH (univ : set X) = dimH (univ : set Y) := by rw [← e.dimH_preimage univ, preimage_univ] end isometric namespace continuous_linear_equiv variables {𝕜 E F : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] @[simp] lemma dimH_image (e : E ≃L[𝕜] F) (s : set E) : dimH (e '' s) = dimH s := le_antisymm (e.lipschitz.dimH_image_le s) $ by simpa only [e.symm_image_image] using e.symm.lipschitz.dimH_image_le (e '' s) @[simp] lemma dimH_preimage (e : E ≃L[𝕜] F) (s : set F) : dimH (e ⁻¹' s) = dimH s := by rw [← e.image_symm_eq_preimage, e.symm.dimH_image] lemma dimH_univ (e : E ≃L[𝕜] F) : dimH (univ : set E) = dimH (univ : set F) := by rw [← e.dimH_preimage, preimage_univ] end continuous_linear_equiv /-! ### Hausdorff dimension in a real vector space -/ namespace real variables {E : Type*} [fintype ι] [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] theorem dimH_ball_pi (x : ι → ℝ) {r : ℝ} (hr : 0 < r) : dimH (metric.ball x r) = fintype.card ι := begin casesI is_empty_or_nonempty ι, { rwa [dimH_subsingleton, eq_comm, nat.cast_eq_zero, fintype.card_eq_zero_iff], exact λ x _ y _, subsingleton.elim x y }, { rw ← ennreal.coe_nat, have : μH[fintype.card ι] (metric.ball x r) = ennreal.of_real ((2 * r) ^ fintype.card ι), by rw [hausdorff_measure_pi_real, real.volume_pi_ball _ hr], refine dimH_of_hausdorff_measure_ne_zero_ne_top _ _; rw [nnreal.coe_nat_cast, this], { simp [pow_pos (mul_pos (zero_lt_two' ℝ) hr)] }, { exact ennreal.of_real_ne_top } } end theorem dimH_ball_pi_fin {n : ℕ} (x : fin n → ℝ) {r : ℝ} (hr : 0 < r) : dimH (metric.ball x r) = n := by rw [dimH_ball_pi x hr, fintype.card_fin] theorem dimH_univ_pi (ι : Type*) [fintype ι] : dimH (univ : set (ι → ℝ)) = fintype.card ι := by simp only [← metric.Union_ball_nat_succ (0 : ι → ℝ), dimH_Union, dimH_ball_pi _ (nat.cast_add_one_pos _), supr_const] theorem dimH_univ_pi_fin (n : ℕ) : dimH (univ : set (fin n → ℝ)) = n := by rw [dimH_univ_pi, fintype.card_fin] theorem dimH_of_mem_nhds {x : E} {s : set E} (h : s ∈ 𝓝 x) : dimH s = finrank ℝ E := begin have e : E ≃L[ℝ] (fin (finrank ℝ E) → ℝ), from continuous_linear_equiv.of_finrank_eq (finite_dimensional.finrank_fin_fun ℝ).symm, rw ← e.dimH_image, refine le_antisymm _ _, { exact (dimH_mono (subset_univ _)).trans_eq (dimH_univ_pi_fin _) }, { have : e '' s ∈ 𝓝 (e x), by { rw ← e.map_nhds_eq, exact image_mem_map h }, rcases metric.nhds_basis_ball.mem_iff.1 this with ⟨r, hr0, hr⟩, simpa only [dimH_ball_pi_fin (e x) hr0] using dimH_mono hr } end theorem dimH_of_nonempty_interior {s : set E} (h : (interior s).nonempty) : dimH s = finrank ℝ E := let ⟨x, hx⟩ := h in dimH_of_mem_nhds (mem_interior_iff_mem_nhds.1 hx) variable (E) theorem dimH_univ_eq_finrank : dimH (univ : set E) = finrank ℝ E := dimH_of_mem_nhds (@univ_mem _ (𝓝 0)) theorem dimH_univ : dimH (univ : set ℝ) = 1 := by rw [dimH_univ_eq_finrank ℝ, finite_dimensional.finrank_self, nat.cast_one] end real variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] [normed_add_comm_group F] [normed_space ℝ F] theorem dense_compl_of_dimH_lt_finrank {s : set E} (hs : dimH s < finrank ℝ E) : dense sᶜ := begin refine λ x, mem_closure_iff_nhds.2 (λ t ht, nonempty_iff_ne_empty.2 $ λ he, hs.not_le _), rw [← diff_eq, diff_eq_empty] at he, rw [← real.dimH_of_mem_nhds ht], exact dimH_mono he end /-! ### Hausdorff dimension and `C¹`-smooth maps `C¹`-smooth maps are locally Lipschitz continuous, hence they do not increase the Hausdorff dimension of sets. -/ /-- Let `f` be a function defined on a finite dimensional real normed space. If `f` is `C¹`-smooth on a convex set `s`, then the Hausdorff dimension of `f '' s` is less than or equal to the Hausdorff dimension of `s`. TODO: do we actually need `convex ℝ s`? -/ lemma cont_diff_on.dimH_image_le {f : E → F} {s t : set E} (hf : cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s) : dimH (f '' t) ≤ dimH t := dimH_image_le_of_locally_lipschitz_on $ λ x hx, let ⟨C, u, hu, hf⟩ := (hf x (ht hx)).exists_lipschitz_on_with hc in ⟨C, u, nhds_within_mono _ ht hu, hf⟩ /-- The Hausdorff dimension of the range of a `C¹`-smooth function defined on a finite dimensional real normed space is at most the dimension of its domain as a vector space over `ℝ`. -/ lemma cont_diff.dimH_range_le {f : E → F} (h : cont_diff ℝ 1 f) : dimH (range f) ≤ finrank ℝ E := calc dimH (range f) = dimH (f '' univ) : by rw image_univ ... ≤ dimH (univ : set E) : h.cont_diff_on.dimH_image_le convex_univ subset.rfl ... = finrank ℝ E : real.dimH_univ_eq_finrank E /-- A particular case of Sard's Theorem. Let `f : E → F` be a map between finite dimensional real vector spaces. Suppose that `f` is `C¹` smooth on a convex set `s` of Hausdorff dimension strictly less than the dimension of `F`. Then the complement of the image `f '' s` is dense in `F`. -/ lemma cont_diff_on.dense_compl_image_of_dimH_lt_finrank [finite_dimensional ℝ F] {f : E → F} {s t : set E} (h : cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s) (htF : dimH t < finrank ℝ F) : dense (f '' t)ᶜ := dense_compl_of_dimH_lt_finrank $ (h.dimH_image_le hc ht).trans_lt htF /-- A particular case of Sard's Theorem. If `f` is a `C¹` smooth map from a real vector space to a real vector space `F` of strictly larger dimension, then the complement of the range of `f` is dense in `F`. -/ lemma cont_diff.dense_compl_range_of_finrank_lt_finrank [finite_dimensional ℝ F] {f : E → F} (h : cont_diff ℝ 1 f) (hEF : finrank ℝ E < finrank ℝ F) : dense (range f)ᶜ := dense_compl_of_dimH_lt_finrank $ h.dimH_range_le.trans_lt $ ennreal.coe_nat_lt_coe_nat.2 hEF
7f5ce3c2639e29b7001a4d31aaa2467a70036db2
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/multiset/sort.lean
648d975765165e9448765c32afb2e744c427d921
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
1,667
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.sort import data.multiset.basic /-! # Construct a sorted list from a multiset. -/ namespace multiset open list variables {α : Type*} section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_perm_of_sorted ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card := quot.induction_on s $ length_merge_sort _ @[simp] theorem sort_zero : sort r 0 = [] := list.merge_sort_nil r @[simp] theorem sort_singleton (a : α) : sort r {a} = [a] := list.merge_sort_singleton r a end sort -- TODO: use a sort order if available, gh-18166 meta instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " (s.unquot.map repr) ++ "}"⟩ end multiset
a9c91c72525350bb7661e65b3055c13383e24b6e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/664.lean
39951d3fb390f5b608f7d306e7dd26365f4f21c0
[ "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
131
lean
class A (α : Type _) where a : α → Unit instance : A Empty where a x := nomatch x def test : A Empty where a x := nomatch x
d63c23483e7a480b30980431ceb04c36a75c1dfc
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/MonadEnv.lean
be1e8aabf0ac3459d9445d1ee56e0e349c351871
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
8,664
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.Environment import Lean.Exception import Lean.Declaration import Lean.Log import Lean.Util.FindExpr import Lean.AuxRecursor import Lean.Compiler.Old namespace Lean def setEnv [MonadEnv m] (env : Environment) : m Unit := modifyEnv fun _ => env def withEnv [Monad m] [MonadFinally m] [MonadEnv m] (env : Environment) (x : m α) : m α := do let saved ← getEnv try setEnv env x finally setEnv saved def isInductive [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo ..) => return true | _ => return false def isRecCore (env : Environment) (declName : Name) : Bool := match env.find? declName with | some (ConstantInfo.recInfo ..) => true | _ => false def isRec [Monad m] [MonadEnv m] (declName : Name) : m Bool := return isRecCore (← getEnv) declName @[inline] def withoutModifyingEnv [Monad m] [MonadEnv m] [MonadFinally m] {α : Type} (x : m α) : m α := do let env ← getEnv try x finally setEnv env /-- Similar to `withoutModifyingEnv`, but also returns the updated environment -/ @[inline] def withoutModifyingEnv' [Monad m] [MonadEnv m] [MonadFinally m] {α : Type} (x : m α) : m (α × Environment) := do let env ← getEnv try let a ← x return (a, ← getEnv) finally setEnv env @[inline] def matchConst [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstantInfo → List Level → m α) : m α := do match e with | Expr.const constName us => do match (← getEnv).find? constName with | some cinfo => k cinfo us | none => failK () | _ => failK () @[inline] def matchConstInduct [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.inductInfo val => k val us | _ => failK () @[inline] def matchConstCtor [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstructorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.ctorInfo val => k val us | _ => failK () @[inline] def matchConstRec [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : RecursorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.recInfo val => k val us | _ => failK () def hasConst [Monad m] [MonadEnv m] (constName : Name) : m Bool := do return (← getEnv).contains constName private partial def mkAuxNameAux (env : Environment) (base : Name) (i : Nat) : Name := let candidate := base.appendIndexAfter i if env.contains candidate then mkAuxNameAux env base (i+1) else candidate def mkAuxName [Monad m] [MonadEnv m] (baseName : Name) (idx : Nat) : m Name := do return mkAuxNameAux (← getEnv) baseName idx def getConstInfo [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstantInfo := do match (← getEnv).find? constName with | some info => pure info | none => throwError "unknown constant '{mkConst constName}'" def mkConstWithLevelParams [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m Expr := do let info ← getConstInfo constName return mkConst constName (info.levelParams.map mkLevelParam) def getConstInfoDefn [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m DefinitionVal := do match (← getConstInfo constName) with | ConstantInfo.defnInfo v => pure v | _ => throwError "'{mkConst constName}' is not a definition" def getConstInfoInduct [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m InductiveVal := do match (← getConstInfo constName) with | ConstantInfo.inductInfo v => pure v | _ => throwError "'{mkConst constName}' is not a inductive type" def getConstInfoCtor [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstructorVal := do match (← getConstInfo constName) with | ConstantInfo.ctorInfo v => pure v | _ => throwError "'{mkConst constName}' is not a constructor" def getConstInfoRec [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m RecursorVal := do match (← getConstInfo constName) with | ConstantInfo.recInfo v => pure v | _ => throwError "'{mkConst constName}' is not a recursor" @[inline] def matchConstStruct [Monad m] [MonadEnv m] [MonadError m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → ConstructorVal → m α) : m α := matchConstInduct e failK fun ival us => do if ival.isRec || ival.numIndices != 0 then failK () else match ival.ctors with | [ctor] => match (← getConstInfo ctor) with | ConstantInfo.ctorInfo cval => k ival us cval | _ => failK () | _ => failK () def addDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] [MonadLog m] [AddMessageContext m] (decl : Declaration) : m Unit := do if !(← MonadLog.hasErrors) && decl.hasSorry then logWarning "declaration uses 'sorry'" match (← getEnv).addDecl decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def supportedRecursors := #[``Empty.rec, ``False.rec, ``Eq.ndrec, ``Eq.rec, ``Eq.recOn, ``Eq.casesOn, ``False.casesOn, ``Empty.casesOn, ``And.rec, ``And.casesOn] /-- This is a temporary workaround for generating better error messages for the compiler. It can be deleted after we rewrite the remaining parts of the compiler in Lean. -/ private def checkUnsupported [Monad m] [MonadEnv m] [MonadError m] (decl : Declaration) : m Unit := do let env ← getEnv decl.forExprM fun e => let unsupportedRecursor? := e.find? fun | Expr.const declName .. => ((isAuxRecursor env declName && !isCasesOnRecursor env declName) || isRecCore env declName) && !supportedRecursors.contains declName | _ => false match unsupportedRecursor? with | some (Expr.const declName ..) => throwError "code generator does not support recursor '{declName}' yet, consider using 'match ... with' and/or structural recursion" | _ => pure () def compileDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do match (← getEnv).compileDecl (← getOptions) decl with | Except.ok env => setEnv env | Except.error (KernelException.other msg) => checkUnsupported decl -- Generate nicer error message for unsupported recursors and axioms throwError msg | Except.error ex => throwKernelException ex def compileDecls [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decls : List Name) : m Unit := do match (← getEnv).compileDecls (← getOptions) decls with | Except.ok env => setEnv env | Except.error (KernelException.other msg) => throwError msg | Except.error ex => throwKernelException ex def addAndCompile [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] [MonadLog m] [AddMessageContext m] (decl : Declaration) : m Unit := do addDecl decl; compileDecl decl unsafe def evalConst [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConst α (← getOptions) constName unsafe def evalConstCheck [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (typeName : Name) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConstCheck α (← getOptions) typeName constName def findModuleOf? [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m (Option Name) := do discard <| getConstInfo declName -- ensure declaration exists match (← getEnv).getModuleIdxFor? declName with | none => return none | some modIdx => return some ((← getEnv).allImportedModuleNames[modIdx.toNat]!) def isEnumType [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Bool := do if let ConstantInfo.inductInfo info ← getConstInfo declName then if !info.type.isProp && info.all.length == 1 && info.numIndices == 0 && info.numParams == 0 && !info.ctors.isEmpty && !info.isRec && !info.isNested && !info.isUnsafe then info.ctors.allM fun ctorName => do let ConstantInfo.ctorInfo info ← getConstInfo ctorName | return false return info.numFields == 0 else return false else return false end Lean
d4e2a473bee7644c2d7be7ff54766f3802fa3f30
798dd332c1ad790518589a09bc82459fb12e5156
/category_theory/functor.lean
cce1c904952903b7ff7ac8229fe78c5bcc42e347
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,495
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 Defines a functor between categories. (As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised by the underlying function on objects, the name is capitalised.) Introduces notations `C ⥤ D` for the type of all functors from `C` to `D`. (I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.) `F X` (a coercion) for a functor `F` acting on an object `X`. -/ import category_theory.category import tactic.tidy namespace category_theory universes u v u₁ v₁ u₂ v₂ u₃ v₃ /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F X` (which uses a coercion), and to a morphism use `F.map f`. The axiom `map_id_lemma` expresses preservation of identities, and `map_comp_lemma` expresses functoriality. Implementation note: when constructing a `functor`, you need to define the `map'` field (which does not know about the coercion). When using a `functor`, use the `map` field (which makes use of the coercion). -/ structure functor (C : Type u₁) [category.{u₁ v₁} C] (D : Type u₂) [category.{u₂ v₂} D] : Type (max u₁ v₁ u₂ v₂) := (obj : C → D) (map' : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y))) (map_id' : ∀ (X : C), map' (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map' (f ≫ g) = (map' f) ≫ (map' g) . obviously) infixr ` ⥤ `:70 := functor -- type as \func -- namespace functor section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 instance : has_coe_to_fun (C ⥤ D) := { F := λ F, C → D, coe := λ F, F.obj } def map (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : (F X) ⟶ (F Y) := F.map' f @[simp] lemma map_id (F : C ⥤ D) (X : C) : F.map (𝟙 X) = 𝟙 (F X) := begin unfold functor.map, erw F.map_id', refl end @[simp] lemma map_comp (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map (f ≫ g) = F.map f ≫ F.map g := begin unfold functor.map, erw F.map_comp' end -- We define a refl lemma 'refolding' the coercion, -- and two lemmas for the coercion applied to an explicit structure. @[simp] lemma obj_eq_coe {F : C ⥤ D} (X : C) : F.obj X = F X := by unfold_coes @[simp] lemma mk_obj (o : C → D) (m mi mc) (X : C) : ({ functor . obj := o, map' := m, map_id' := mi, map_comp' := mc } : C ⥤ D) X = o X := rfl @[simp] lemma mk_map (o : C → D) (m mi mc) {X Y : C} (f : X ⟶ Y) : functor.map { functor . obj := o, map' := m, map_id' := mi, map_comp' := mc } f = m f := rfl end section variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] include 𝒞 /-- `functor.id C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map' := λ _ _ f, f } variable {C} @[simp] lemma id_obj (X : C) : (functor.id C) X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (functor.id C).map f = f := rfl end section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E] include 𝒞 𝒟 ℰ /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G (F X), map' := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G) X = G (F X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) (X Y : C) (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl end end functor def bundled.map {c : Type u → Type v} {d : Type u → Type v} (f : Π{a}, c a → d a) (s : bundled c) : bundled d := { α := s.α, str := f s.str } def concrete_functor {C : Type u → Type v} {hC : ∀{α β}, C α → C β → (α → β) → Prop} [concrete_category @hC] {D : Type u → Type v} {hD : ∀{α β}, D α → D β → (α → β) → Prop} [concrete_category @hD] (m : ∀{α}, C α → D α) (h : ∀{α β} {ia : C α} {ib : C β} {f}, hC ia ib f → hD (m ia) (m ib) f) : bundled C ⥤ bundled D := { obj := bundled.map @m, map' := λ X Y f, ⟨ f, h f.2 ⟩} end category_theory
e5f5a47a34e79c74f9fe06aa78dc0dba695c74da
b87641ffb6358d6508ccbfa54e67c87070cb28d8
/cat/curve_geometr.lean
91eaea6b7ca61068f11b490714d9c197a2546393
[]
no_license
Nolrai/LeanGiggle
a4b628745ae3f5a36ae79b673ee8543e18ed4899
8326b2a6685b60a3529ee0fe26bd86f5d849b071
refs/heads/master
1,545,396,766,168
1,538,238,458,000
1,538,238,458,000
105,524,473
0
0
null
null
null
null
UTF-8
Lean
false
false
2,279
lean
open function structure distinct (size : ℕ) (α : Type) : Type := (f : fin size → α) (injective : injective f) namespace distinct section parameter {size : ℕ} parameter {α : Type} definition to_set (d : distinct size α) : set α := λ a : α, ∃ i, d.f i = a instance distinct_has_coe : has_coe (distinct size α) (set α) := has_coe.mk to_set end namespace unordered section open fin open distinct parameter size : ℕ parameter α : Type open function.equiv private definition eqv (d0 d1 : distinct size α) : Prop := d0.to_set = d1.to_set private lemma eqv_is_equiv : equivalence eqv := begin repeat {split} ; unfold reflexive symmetric transitive eqv ; intro x , {reflexivity} , {intros y h, symmetry, exact h} , {intros y z xy yz, transitivity (to_set y); assumption} end instance setoid : setoid (distinct size α) := setoid.mk _ eqv_is_equiv definition unordered : Type := quotient setoid end section parameter {size : ℕ} parameter {α : Type} definition to_set_respects : ∀ a b : (distinct size α), a ≈ b → to_set a = to_set b := begin intros a b h , unfold has_equiv.equiv setoid.r eqv at h , exact h end definition to_set := quotient.lift to_set to_set_respects end instance has_lift (n : ℕ) (α : Type) : has_lift (unordered n α) (set α) := has_lift.mk to_set end unordered definition unordered := unordered.unordered end distinct open distinct.unordered namespace line_geometry section notation `double` a :100 := (unordered 2 a : Type) open distinct parameters (Point Line : Type) class line_geometry [has_lift Line (set Point)] := mk :: (fixed_by : double Point → Line) (fixed_by_correct : ∀ (pt : double Point) (l : Line), 1 ≤ 2) end end line_geometry namespace curve_geometry section notation `tripple` a :100 := (unordered 3 a : Type) open distinct parameters (Point Curve : Type) class curve_geometry [has_lift Curve (set Point)] := (fixed_by : tripple Point → Curve) (fixed_by_correct : ∀ (pt : tripple Point) (c : Curve) , ↑pt ⊆ (↑c : set Point) ↔ c = fixed_by pt) end end curve_geometry notation `curve_geometry` := curve_geometry.curve_geometry
f049f612c331f93c5ff2fc52bc4e109fd768c1ea
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/decidelet.lean
6d1a965287790a75a65c86cc363edb01495f437f
[ "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
56
lean
theorem ex : let x := 1; x < 2 := by intro x decide
9a3c19045749480040fff481ce7c8682dd23434f
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world7/level8.lean
fa8f452c9610f061be3d0305383806025a3eb558
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
413
lean
lemma and_or_distrib_left (P Q R : Prop) : P ∧ (Q ∨ R) → (P ∧ Q) ∨ (P ∧ R) := begin intro pqr, cases pqr with p qr, cases qr with q r, { left, split, { exact p, }, { exact q, }, }, { right, split, { exact p, }, { exact r, } } end
dca018939c7428992941c7e5616e469c24ddfee4
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_ematch_cast3.lean
18af9d273799c38bb83cae7257e177d472ee5c54
[ "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
365
lean
import data.nat open nat constant C : nat → Type₁ constant f : ∀ n, C n → C n constant g : ∀ n, C n → C n → C n lemma gffax [forward] (n : nat) (a b : C n) : (: g n a b :) = a := sorry set_option blast.strategy "ematch" set_option trace.blast.ematch true example (n m : nat) (a c : C n) (b : C m) (e : m = n) : a == b → g n a a == b := by blast
8a27d11df26614522a4e4d3b6be14327f712cce0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/alias_auto.lean
41e9b2873ffe8daca82bd30e37e4306cc4c79e1c
[]
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
857
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.buffer.parser import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # The `alias` command This file defines an `alias` command, which can be used to create copies of a theorem or definition with different names. Syntax: ```lean /-- doc string -/ alias my_theorem ← alias1 alias2 ... ``` This produces defs or theorems of the form: ```lean /-- doc string -/ /-- doc string -/ namespace tactic.alias /-- The `alias` command can be used to create copies of a theorem or definition with different names. Syntax: ```lean /-- doc string -/ /-- doc string -/ /-- doc string -/ end Mathlib
463994bf120ae223ee1a80422e86569a094552e5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/combinatorics/composition.lean
b67cfdf21c48d3d6d3130053481f92aa0dc33dfb
[ "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
36,463
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.fintype.card import data.finset.sort import algebra.big_operators.order /-! # Compositions A composition of a natural number `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks. This notion is closely related to that of a partition of `n`, but in a composition of `n` the order of the `iⱼ`s matters. We implement two different structures covering these two viewpoints on compositions. The first one, made of a list of positive integers summing to `n`, is the main one and is called `composition n`. The second one is useful for combinatorial arguments (for instance to show that the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}` containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost points of each block. The main API is built on `composition n`, and we provide an equivalence between the two types. ## Main functions * `c : composition n` is a structure, made of a list of integers which are all positive and add up to `n`. * `composition_card` states that the cardinality of `composition n` is exactly `2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is nat subtraction). Let `c : composition n` be a composition of `n`. Then * `c.blocks` is the list of blocks in `c`. * `c.length` is the number of blocks in the composition. * `c.blocks_fun : fin c.length → ℕ` is the realization of `c.blocks` as a function on `fin c.length`. This is the main object when using compositions to understand the composition of analytic functions. * `c.size_up_to : ℕ → ℕ` is the sum of the size of the blocks up to `i`.; * `c.embedding i : fin (c.blocks_fun i) → fin n` is the increasing embedding of the `i`-th block in `fin n`; * `c.index j`, for `j : fin n`, is the index of the block containing `j`. * `composition.ones n` is the composition of `n` made of ones, i.e., `[1, ..., 1]`. * `composition.single n (hn : 0 < n)` is the composition of `n` made of a single block of size `n`. Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition of `n`. * `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the blocks of `c`. * `join_split_wrt_composition` states that splitting a list and then joining it gives back the original list. * `split_wrt_composition_join` states that joining a list of lists, and then splitting it back according to the right composition, gives back the original list of lists. We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`. `c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries` and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not make sense in the edge case `n = 0`, while the previous description works in all cases). The elements of this set (other than `n`) correspond to leftmost points of blocks. Thus, there is an equiv between `composition n` and `composition_as_set n`. We only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n` from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that `composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)` (see `composition_as_set_card` and `composition_card`). ## Implementation details The main motivation for this structure and its API is in the construction of the composition of formal multilinear series, and the proof that the composition of analytic functions is analytic. The representation of a composition as a list is very handy as lists are very flexible and already have a well-developed API. ## Tags Composition, partition ## References <https://en.wikipedia.org/wiki/Composition_(combinatorics)> -/ open list open_locale big_operators variable {n : ℕ} /-- A composition of `n` is a list of positive integers summing to `n`. -/ @[ext] structure composition (n : ℕ) := (blocks : list ℕ) (blocks_pos : ∀ {i}, i ∈ blocks → 0 < i) (blocks_sum : blocks.sum = n) /-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure `composition_as_set n`. -/ @[ext] structure composition_as_set (n : ℕ) := (boundaries : finset (fin n.succ)) (zero_mem : (0 : fin n.succ) ∈ boundaries) (last_mem : fin.last n ∈ boundaries) instance {n : ℕ} : inhabited (composition_as_set n) := ⟨⟨finset.univ, finset.mem_univ _, finset.mem_univ _⟩⟩ /-! ### Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. -/ namespace composition variables (c : composition n) instance (n : ℕ) : has_to_string (composition n) := ⟨λ c, to_string c.blocks⟩ /-- The length of a composition, i.e., the number of blocks in the composition. -/ @[reducible] def length : ℕ := c.blocks.length lemma blocks_length : c.blocks.length = c.length := rfl /-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic functions using compositions, this is the main player. -/ def blocks_fun : fin c.length → ℕ := λ i, nth_le c.blocks i i.2 lemma of_fn_blocks_fun : of_fn c.blocks_fun = c.blocks := of_fn_nth_le _ lemma sum_blocks_fun : ∑ i, c.blocks_fun i = n := by conv_rhs { rw [← c.blocks_sum, ← of_fn_blocks_fun, sum_of_fn] } lemma blocks_fun_mem_blocks (i : fin c.length) : c.blocks_fun i ∈ c.blocks := nth_le_mem _ _ _ @[simp] lemma one_le_blocks {i : ℕ} (h : i ∈ c.blocks) : 1 ≤ i := c.blocks_pos h @[simp] lemma one_le_blocks' {i : ℕ} (h : i < c.length) : 1 ≤ nth_le c.blocks i h:= c.one_le_blocks (nth_le_mem (blocks c) i h) @[simp] lemma blocks_pos' (i : ℕ) (h : i < c.length) : 0 < nth_le c.blocks i h:= c.one_le_blocks' h lemma one_le_blocks_fun (i : fin c.length) : 1 ≤ c.blocks_fun i := c.one_le_blocks (c.blocks_fun_mem_blocks i) lemma length_le : c.length ≤ n := begin conv_rhs { rw ← c.blocks_sum }, exact length_le_sum_of_one_le _ (λ i hi, c.one_le_blocks hi) end lemma length_pos_of_pos (h : 0 < n) : 0 < c.length := begin apply length_pos_of_sum_pos, convert h, exact c.blocks_sum end /-- The sum of the sizes of the blocks in a composition up to `i`. -/ def size_up_to (i : ℕ) : ℕ := (c.blocks.take i).sum @[simp] lemma size_up_to_zero : c.size_up_to 0 = 0 := by simp [size_up_to] lemma size_up_to_of_length_le (i : ℕ) (h : c.length ≤ i) : c.size_up_to i = n := begin dsimp [size_up_to], convert c.blocks_sum, exact take_all_of_le h end @[simp] lemma size_up_to_length : c.size_up_to c.length = n := c.size_up_to_of_length_le c.length (le_refl _) lemma size_up_to_le (i : ℕ) : c.size_up_to i ≤ n := begin conv_rhs { rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] }, exact nat.le_add_right _ _ end lemma size_up_to_succ {i : ℕ} (h : i < c.length) : c.size_up_to (i+1) = c.size_up_to i + c.blocks.nth_le i h := by { simp only [size_up_to], rw sum_take_succ _ _ h } lemma size_up_to_succ' (i : fin c.length) : c.size_up_to ((i : ℕ) + 1) = c.size_up_to i + c.blocks_fun i := c.size_up_to_succ i.2 lemma size_up_to_strict_mono {i : ℕ} (h : i < c.length) : c.size_up_to i < c.size_up_to (i+1) := by { rw c.size_up_to_succ h, simp } lemma monotone_size_up_to : monotone c.size_up_to := monotone_sum_take _ /-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundary : fin (c.length + 1) ↪o fin (n+1) := order_embedding.of_strict_mono (λ i, ⟨c.size_up_to i, nat.lt_succ_of_le (c.size_up_to_le i)⟩) $ fin.strict_mono_iff_lt_succ.2 $ λ i hi, c.size_up_to_strict_mono $ lt_of_add_lt_add_right hi @[simp] lemma boundary_zero : c.boundary 0 = 0 := by simp [boundary, fin.ext_iff] @[simp] lemma boundary_last : c.boundary (fin.last c.length) = fin.last n := by simp [boundary, fin.ext_iff] /-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundaries : finset (fin (n+1)) := finset.univ.map c.boundary.to_embedding lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := by simp [boundaries] /-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost point of each block, and adding a virtual point at the right of the last block. -/ def to_composition_as_set : composition_as_set n := { boundaries := c.boundaries, zero_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map], exact ⟨0, rfl⟩, end, last_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_map], exact ⟨fin.last c.length, c.boundary_last⟩, end } /-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is exactly `c.boundary`. -/ lemma order_emb_of_fin_boundaries : c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length = c.boundary := begin refine (finset.order_emb_of_fin_unique' _ _).symm, exact λ i, (finset.mem_map' _).2 (finset.mem_univ _) end /-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into `fin n` at the relevant position. -/ def embedding (i : fin c.length) : fin (c.blocks_fun i) ↪o fin n := (fin.nat_add $ c.size_up_to i).trans $ fin.cast_le $ calc c.size_up_to i + c.blocks_fun i = c.size_up_to (i + 1) : (c.size_up_to_succ _).symm ... ≤ c.size_up_to c.length : monotone_sum_take _ i.2 ... = n : c.size_up_to_length @[simp] lemma coe_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.embedding i j : ℕ) = c.size_up_to i + j := rfl /-- `index_exists` asserts there is some `i` with `j < c.size_up_to (i+1)`. In the next definition `index` we use `nat.find` to produce the minimal such index. -/ lemma index_exists {j : ℕ} (h : j < n) : ∃ i : ℕ, j < c.size_up_to i.succ ∧ i < c.length := begin have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h, have : 0 < c.blocks.sum, by rwa [← c.blocks_sum] at n_pos, have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this, refine ⟨c.length.pred, _, nat.pred_lt (ne_of_gt length_pos)⟩, have : c.length.pred.succ = c.length := nat.succ_pred_eq_of_pos length_pos, simp [this, h] end /-- `c.index j` is the index of the block in the composition `c` containing `j`. -/ def index (j : fin n) : fin c.length := ⟨nat.find (c.index_exists j.2), (nat.find_spec (c.index_exists j.2)).2⟩ lemma lt_size_up_to_index_succ (j : fin n) : (j : ℕ) < c.size_up_to (c.index j).succ := (nat.find_spec (c.index_exists j.2)).1 lemma size_up_to_index_le (j : fin n) : c.size_up_to (c.index j) ≤ j := begin by_contradiction H, set i := c.index j with hi, push_neg at H, have i_pos : (0 : ℕ) < i, { by_contradiction i_pos, push_neg at i_pos, revert H, simp [nonpos_iff_eq_zero.1 i_pos, c.size_up_to_zero] }, let i₁ := (i : ℕ).pred, have i₁_lt_i : i₁ < i := nat.pred_lt (ne_of_gt i_pos), have i₁_succ : i₁.succ = i := nat.succ_pred_eq_of_pos i_pos, have := nat.find_min (c.index_exists j.2) i₁_lt_i, simp [lt_trans i₁_lt_i (c.index j).2, i₁_succ] at this, exact nat.lt_le_antisymm H this end /-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with `fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/ def inv_embedding (j : fin n) : fin (c.blocks_fun (c.index j)) := ⟨j - c.size_up_to (c.index j), begin rw [nat.sub_lt_right_iff_lt_add, add_comm, ← size_up_to_succ'], { exact lt_size_up_to_index_succ _ _ }, { exact size_up_to_index_le _ _ } end⟩ @[simp] lemma coe_inv_embedding (j : fin n) : (c.inv_embedding j : ℕ) = j - c.size_up_to (c.index j) := rfl lemma embedding_comp_inv (j : fin n) : c.embedding (c.index j) (c.inv_embedding j) = j := begin rw fin.ext_iff, apply nat.add_sub_cancel' (c.size_up_to_index_le j), end lemma mem_range_embedding_iff {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ c.size_up_to i ≤ j ∧ (j : ℕ) < c.size_up_to (i : ℕ).succ := begin split, { assume h, rcases set.mem_range.2 h with ⟨k, hk⟩, rw fin.ext_iff at hk, change c.size_up_to i + k = (j : ℕ) at hk, rw ← hk, simp [size_up_to_succ', k.is_lt] }, { assume h, apply set.mem_range.2, refine ⟨⟨j - c.size_up_to i, _⟩, _⟩, { rw [nat.sub_lt_left_iff_lt_add, ← size_up_to_succ'], { exact h.2 }, { exact h.1 } }, { rw fin.ext_iff, exact nat.add_sub_cancel' h.1 } } end /-- The embeddings of different blocks of a composition are disjoint. -/ lemma disjoint_range {i₁ i₂ : fin c.length} (h : i₁ ≠ i₂) : disjoint (set.range (c.embedding i₁)) (set.range (c.embedding i₂)) := begin classical, wlog h' : i₁ ≤ i₂ using i₁ i₂, by_contradiction d, obtain ⟨x, hx₁, hx₂⟩ : ∃ x : fin n, (x ∈ set.range (c.embedding i₁) ∧ x ∈ set.range (c.embedding i₂)) := set.not_disjoint_iff.1 d, have : i₁ < i₂ := lt_of_le_of_ne h' h, have A : (i₁ : ℕ).succ ≤ i₂ := nat.succ_le_of_lt this, apply lt_irrefl (x : ℕ), calc (x : ℕ) < c.size_up_to (i₁ : ℕ).succ : (c.mem_range_embedding_iff.1 hx₁).2 ... ≤ c.size_up_to (i₂ : ℕ) : monotone_sum_take _ A ... ≤ x : (c.mem_range_embedding_iff.1 hx₂).1 end lemma mem_range_embedding (j : fin n) : j ∈ set.range (c.embedding (c.index j)) := begin have : c.embedding (c.index j) (c.inv_embedding j) ∈ set.range (c.embedding (c.index j)) := set.mem_range_self _, rwa c.embedding_comp_inv j at this end lemma mem_range_embedding_iff' {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ i = c.index j := begin split, { rw ← not_imp_not, assume h, exact set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) }, { assume h, rw h, exact c.mem_range_embedding j } end lemma index_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : c.index (c.embedding i j) = i := begin symmetry, rw ← mem_range_embedding_iff', apply set.mem_range_self end lemma inv_embedding_comp (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.inv_embedding (c.embedding i j) : ℕ) = j := by simp_rw [coe_inv_embedding, index_embedding, coe_embedding, nat.add_sub_cancel_left] /-- Equivalence between the disjoint union of the blocks (each of them seen as `fin (c.blocks_fun i)`) with `fin n`. -/ def blocks_fin_equiv : (Σ i : fin c.length, fin (c.blocks_fun i)) ≃ fin n := { to_fun := λ x, c.embedding x.1 x.2, inv_fun := λ j, ⟨c.index j, c.inv_embedding j⟩, left_inv := λ x, begin rcases x with ⟨i, y⟩, dsimp, congr, { exact c.index_embedding _ _ }, rw fin.heq_ext_iff, { exact c.inv_embedding_comp _ _ }, { rw c.index_embedding } end, right_inv := λ j, c.embedding_comp_inv j } lemma blocks_fun_congr {n₁ n₂ : ℕ} (c₁ : composition n₁) (c₂ : composition n₂) (i₁ : fin c₁.length) (i₂ : fin c₂.length) (hn : n₁ = n₂) (hc : c₁.blocks = c₂.blocks) (hi : (i₁ : ℕ) = i₂) : c₁.blocks_fun i₁ = c₂.blocks_fun i₂ := by { cases hn, rw ← composition.ext_iff at hc, cases hc, congr, rwa fin.ext_iff } /-- Two compositions (possibly of different integers) coincide if and only if they have the same sequence of blocks. -/ lemma sigma_eq_iff_blocks_eq {c : Σ n, composition n} {c' : Σ n, composition n} : c = c' ↔ c.2.blocks = c'.2.blocks := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases c with ⟨n, c⟩, rcases c' with ⟨n', c'⟩, have : n = n', by { rw [← c.blocks_sum, ← c'.blocks_sum, H] }, induction this, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext1, exact H end /-! ### The composition `composition.ones` -/ /-- The composition made of blocks all of size `1`. -/ def ones (n : ℕ) : composition n := ⟨repeat (1 : ℕ) n, λ i hi, by simp [list.eq_of_mem_repeat hi], by simp⟩ instance {n : ℕ} : inhabited (composition n) := ⟨composition.ones n⟩ @[simp] lemma ones_length (n : ℕ) : (ones n).length = n := list.length_repeat 1 n @[simp] lemma ones_blocks (n : ℕ) : (ones n).blocks = repeat (1 : ℕ) n := rfl @[simp] lemma ones_blocks_fun (n : ℕ) (i : fin (ones n).length) : (ones n).blocks_fun i = 1 := by simp [blocks_fun, ones, blocks, i.2] @[simp] lemma ones_size_up_to (n : ℕ) (i : ℕ) : (ones n).size_up_to i = min i n := by simp [size_up_to, ones_blocks, take_repeat] @[simp] lemma ones_embedding (i : fin (ones n).length) (h : 0 < (ones n).blocks_fun i) : (ones n).embedding i ⟨0, h⟩ = ⟨i, lt_of_lt_of_le i.2 (ones n).length_le⟩ := by { ext, simpa using i.2.le } lemma eq_ones_iff {c : composition n} : c = ones n ↔ ∀ i ∈ c.blocks, i = 1 := begin split, { rintro rfl, exact λ i, eq_of_mem_repeat }, { assume H, ext1, have A : c.blocks = repeat 1 c.blocks.length := eq_repeat_of_mem H, have : c.blocks.length = n, by { conv_rhs { rw [← c.blocks_sum, A] }, simp }, rw [A, this, ones_blocks] }, end lemma ne_ones_iff {c : composition n} : c ≠ ones n ↔ ∃ i ∈ c.blocks, 1 < i := begin refine (not_congr eq_ones_iff).trans _, have : ∀ j ∈ c.blocks, j = 1 ↔ j ≤ 1 := λ j hj, by simp [le_antisymm_iff, c.one_le_blocks hj], simp [this] {contextual := tt} end lemma eq_ones_iff_length {c : composition n} : c = ones n ↔ c.length = n := begin split, { rintro rfl, exact ones_length n }, { contrapose, assume H length_n, apply lt_irrefl n, calc n = ∑ (i : fin c.length), 1 : by simp [length_n] ... < ∑ (i : fin c.length), c.blocks_fun i : begin obtain ⟨i, hi, i_blocks⟩ : ∃ i ∈ c.blocks, 1 < i := ne_ones_iff.1 H, rw [← of_fn_blocks_fun, mem_of_fn c.blocks_fun, set.mem_range] at hi, obtain ⟨j : fin c.length, hj : c.blocks_fun j = i⟩ := hi, rw ← hj at i_blocks, exact finset.sum_lt_sum (λ i hi, by simp [blocks_fun]) ⟨j, finset.mem_univ _, i_blocks⟩, end ... = n : c.sum_blocks_fun } end lemma eq_ones_iff_le_length {c : composition n} : c = ones n ↔ n ≤ c.length := by simp [eq_ones_iff_length, le_antisymm_iff, c.length_le] /-! ### The composition `composition.single` -/ /-- The composition made of a single block of size `n`. -/ def single (n : ℕ) (h : 0 < n) : composition n := ⟨[n], by simp [h], by simp⟩ @[simp] lemma single_length {n : ℕ} (h : 0 < n) : (single n h).length = 1 := rfl @[simp] lemma single_blocks {n : ℕ} (h : 0 < n) : (single n h).blocks = [n] := rfl @[simp] lemma single_blocks_fun {n : ℕ} (h : 0 < n) (i : fin (single n h).length) : (single n h).blocks_fun i = n := by simp [blocks_fun, single, blocks, i.2] @[simp] lemma single_embedding {n : ℕ} (h : 0 < n) (i : fin n) : (single n h).embedding ⟨0, single_length h ▸ zero_lt_one⟩ i = i := by { ext, simp } lemma eq_single_iff_length {n : ℕ} (h : 0 < n) {c : composition n} : c = single n h ↔ c.length = 1 := begin split, { assume H, rw H, exact single_length h }, { assume H, ext1, have A : c.blocks.length = 1 := H ▸ c.blocks_length, have B : c.blocks.sum = n := c.blocks_sum, rw eq_cons_of_length_one A at B ⊢, simpa [single_blocks] using B } end lemma ne_single_iff {n : ℕ} (hn : 0 < n) {c : composition n} : c ≠ single n hn ↔ ∀ i, c.blocks_fun i < n := begin rw ← not_iff_not, push_neg, split, { rintros rfl, exact ⟨⟨0, by simp⟩, by simp⟩ }, { rintros ⟨i, hi⟩, rw eq_single_iff_length, have : ∀ j : fin c.length, j = i, { intros j, by_contradiction ji, apply lt_irrefl ∑ k, c.blocks_fun k, calc ∑ k, c.blocks_fun k ≤ c.blocks_fun i : by simp only [c.sum_blocks_fun, hi] ... < ∑ k, c.blocks_fun k : finset.single_lt_sum ji (finset.mem_univ _) (finset.mem_univ _) (c.one_le_blocks_fun j) (λ _ _ _, zero_le _) }, simpa using fintype.card_eq_one_of_forall_eq this } end end composition /-! ### Splitting a list Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the join operation. -/ namespace list variable {α : Type*} /-- Auxiliary for `list.split_wrt_composition`. -/ def split_wrt_composition_aux : list α → list ℕ → list (list α) | l [] := [] | l (n :: ns) := let (l₁, l₂) := l.split_at n in l₁ :: split_wrt_composition_aux l₂ ns /-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of `k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`. This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/ def split_wrt_composition (l : list α) (c : composition n) : list (list α) := split_wrt_composition_aux l c.blocks local attribute [simp] split_wrt_composition_aux.equations._eqn_1 local attribute [simp] lemma split_wrt_composition_aux_cons (l : list α) (n ns) : l.split_wrt_composition_aux (n :: ns) = take n l :: (drop n l).split_wrt_composition_aux ns := by simp [split_wrt_composition_aux] lemma length_split_wrt_composition_aux (l : list α) (ns) : length (l.split_wrt_composition_aux ns) = ns.length := by induction ns generalizing l; simp * /-- When one splits a list along a composition `c`, the number of sublists thus created is `c.length`. -/ @[simp] lemma length_split_wrt_composition (l : list α) (c : composition n) : length (l.split_wrt_composition c) = c.length := length_split_wrt_composition_aux _ _ lemma map_length_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum ≤ l.length → map length (l.split_wrt_composition_aux ns) = ns := begin induction ns with n ns IH; intros l h; simp at h ⊢, have := le_trans (nat.le_add_right _ _) h, rw IH, {simp [this]}, rwa [length_drop, nat.le_sub_left_iff_add_le this] end /-- When one splits a list along a composition `c`, the lengths of the sublists thus created are given by the block sizes in `c`. -/ lemma map_length_split_wrt_composition (l : list α) (c : composition l.length) : map length (l.split_wrt_composition c) = c.blocks := map_length_split_wrt_composition_aux (le_of_eq c.blocks_sum) lemma length_pos_of_mem_split_wrt_composition {l l' : list α} {c : composition l.length} (h : l' ∈ l.split_wrt_composition c) : 0 < length l' := begin have : l'.length ∈ (l.split_wrt_composition c).map list.length := list.mem_map_of_mem list.length h, rw map_length_split_wrt_composition at this, exact c.blocks_pos this end lemma sum_take_map_length_split_wrt_composition (l : list α) (c : composition l.length) (i : ℕ) : (((l.split_wrt_composition c).map length).take i).sum = c.size_up_to i := by { congr, exact map_length_split_wrt_composition l c } lemma nth_le_split_wrt_composition_aux (l : list α) (ns : list ℕ) {i : ℕ} (hi) : nth_le (l.split_wrt_composition_aux ns) i hi = (l.take (ns.take (i+1)).sum).drop (ns.take i).sum := begin induction ns with n ns IH generalizing l i, {cases hi}, cases i; simp [IH], rw [add_comm n, drop_add, drop_take], end /-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l` between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th block of the composition. -/ lemma nth_le_split_wrt_composition (l : list α) (c : composition n) {i : ℕ} (hi : i < (l.split_wrt_composition c).length) : nth_le (l.split_wrt_composition c) i hi = (l.take (c.size_up_to (i+1))).drop (c.size_up_to i) := nth_le_split_wrt_composition_aux _ _ _ theorem join_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum = l.length → (l.split_wrt_composition_aux ns).join = l := begin induction ns with n ns IH; intros l h; simp at h ⊢, { exact (length_eq_zero.1 h.symm).symm }, rw IH, {simp}, rwa [length_drop, ← h, nat.add_sub_cancel_left] end /-- If one splits a list along a composition, and then joins the sublists, one gets back the original list. -/ @[simp] theorem join_split_wrt_composition (l : list α) (c : composition l.length) : (l.split_wrt_composition c).join = l := join_split_wrt_composition_aux c.blocks_sum /-- If one joins a list of lists and then splits the join along the right composition, one gets back the original list of lists. -/ @[simp] theorem split_wrt_composition_join (L : list (list α)) (c : composition L.join.length) (h : map length L = c.blocks) : split_wrt_composition (join L) c = L := by simp only [eq_self_iff_true, and_self, eq_iff_join_eq, join_split_wrt_composition, map_length_split_wrt_composition, h] end list /-! ### Compositions as sets Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and `n`, where the points of the set (other than `n`) correspond to the leftmost points of each block. -/ /-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/ def composition_as_set_equiv (n : ℕ) : composition_as_set n ≃ finset (fin (n - 1)) := { to_fun := λ c, {i : fin (n-1) | (⟨1 + (i : ℕ), begin apply (add_lt_add_left i.is_lt 1).trans_le, rw [nat.succ_eq_add_one, add_comm], exact add_le_add (nat.sub_le n 1) (le_refl 1) end ⟩ : fin n.succ) ∈ c.boundaries}.to_finset, inv_fun := λ s, { boundaries := {i : fin n.succ | (i = 0) ∨ (i = fin.last n) ∨ (∃ (j : fin (n-1)) (hj : j ∈ s), (i : ℕ) = j + 1)}.to_finset, zero_mem := by simp, last_mem := by simp }, left_inv := begin assume c, ext i, simp only [exists_prop, add_comm, set.mem_to_finset, true_or, or_true, set.mem_set_of_eq], split, { rintro (rfl | rfl | ⟨j, hj1, hj2⟩), { exact c.zero_mem }, { exact c.last_mem }, { convert hj1, rwa fin.ext_iff } }, { simp only [or_iff_not_imp_left], assume i_mem i_ne_zero i_ne_last, simp [fin.ext_iff] at i_ne_zero i_ne_last, have A : (1 + (i-1) : ℕ) = (i : ℕ), by { rw add_comm, exact nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr i_ne_zero) }, refine ⟨⟨i - 1, _⟩, _, _⟩, { have : (i : ℕ) < n + 1 := i.2, simp [nat.lt_succ_iff_lt_or_eq, i_ne_last] at this, exact nat.pred_lt_pred i_ne_zero this }, { convert i_mem, rw fin.ext_iff, simp only [fin.coe_mk, A] }, { simp [A] } }, end, right_inv := begin assume s, ext i, have : 1 + (i : ℕ) ≠ n, { apply ne_of_lt, convert add_lt_add_left i.is_lt 1, rw add_comm, apply (nat.succ_pred_eq_of_pos _).symm, exact (zero_le i.val).trans_lt (i.2.trans_le (nat.sub_le n 1)) }, simp only [fin.ext_iff, exists_prop, fin.coe_zero, add_comm, set.mem_to_finset, set.mem_set_of_eq, fin.coe_last], erw [set.mem_set_of_eq], simp only [this, false_or, add_right_inj, add_eq_zero_iff, one_ne_zero, false_and, fin.coe_mk], split, { rintros ⟨j, js, hj⟩, convert js, exact (fin.ext_iff _ _).2 hj }, { assume h, exact ⟨i, h, rfl⟩ } end } instance composition_as_set_fintype (n : ℕ) : fintype (composition_as_set n) := fintype.of_equiv _ (composition_as_set_equiv n).symm lemma composition_as_set_card (n : ℕ) : fintype.card (composition_as_set n) = 2 ^ (n - 1) := begin have : fintype.card (finset (fin (n-1))) = 2 ^ (n - 1), by simp, rw ← this, exact fintype.card_congr (composition_as_set_equiv n) end namespace composition_as_set variables (c : composition_as_set n) lemma boundaries_nonempty : c.boundaries.nonempty := ⟨0, c.zero_mem⟩ lemma card_boundaries_pos : 0 < finset.card c.boundaries := finset.card_pos.mpr c.boundaries_nonempty /-- Number of blocks in a `composition_as_set`. -/ def length : ℕ := finset.card c.boundaries - 1 lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := (nat.sub_eq_iff_eq_add c.card_boundaries_pos).mp rfl lemma length_lt_card_boundaries : c.length < c.boundaries.card := by { rw c.card_boundaries_eq_succ_length, exact lt_add_one _ } lemma lt_length (i : fin c.length) : (i : ℕ) + 1 < c.boundaries.card := nat.add_lt_of_lt_sub_right i.2 lemma lt_length' (i : fin c.length) : (i : ℕ) < c.boundaries.card := lt_of_le_of_lt (nat.le_succ i) (c.lt_length i) /-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/ def boundary : fin c.boundaries.card ↪o fin (n + 1) := c.boundaries.order_emb_of_fin rfl @[simp] lemma boundary_zero : (c.boundary ⟨0, c.card_boundaries_pos⟩ : fin (n + 1)) = 0 := begin rw [boundary, finset.order_emb_of_fin_zero rfl c.card_boundaries_pos], exact le_antisymm (finset.min'_le _ _ c.zero_mem) (fin.zero_le _), end @[simp] lemma boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = fin.last n := begin convert finset.order_emb_of_fin_last rfl c.card_boundaries_pos, exact le_antisymm (finset.le_max' _ _ c.last_mem) (fin.le_last _) end /-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/ def blocks_fun (i : fin c.length) : ℕ := (c.boundary ⟨(i : ℕ) + 1, c.lt_length i⟩) - (c.boundary ⟨i, c.lt_length' i⟩) lemma blocks_fun_pos (i : fin c.length) : 0 < c.blocks_fun i := begin have : (⟨i, c.lt_length' i⟩ : fin c.boundaries.card) < ⟨i + 1, c.lt_length i⟩ := nat.lt_succ_self _, exact nat.lt_sub_left_of_add_lt ((c.boundaries.order_emb_of_fin rfl).strict_mono this) end /-- List of the sizes of the blocks in a `composition_as_set`. -/ def blocks (c : composition_as_set n) : list ℕ := of_fn c.blocks_fun @[simp] lemma blocks_length : c.blocks.length = c.length := length_of_fn _ lemma blocks_partial_sum {i : ℕ} (h : i < c.boundaries.card) : (c.blocks.take i).sum = c.boundary ⟨i, h⟩ := begin induction i with i IH, { simp }, have A : i < c.blocks.length, { rw c.card_boundaries_eq_succ_length at h, simp [blocks, nat.lt_of_succ_lt_succ h] }, have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length, nat.sub_le]), rw [sum_take_succ _ _ A, IH B], simp only [blocks, blocks_fun, nth_le_of_fn'], apply nat.add_sub_cancel', simp end lemma mem_boundaries_iff_exists_blocks_sum_take_eq {j : fin (n+1)} : j ∈ c.boundaries ↔ ∃ i < c.boundaries.card, (c.blocks.take i).sum = j := begin split, { assume hj, rcases (c.boundaries.order_iso_of_fin rfl).surjective ⟨j, hj⟩ with ⟨i, hi⟩, rw [subtype.ext_iff, subtype.coe_mk] at hi, refine ⟨i.1, i.2, _⟩, rw [← hi, c.blocks_partial_sum i.2], refl }, { rintros ⟨i, hi, H⟩, convert (c.boundaries.order_iso_of_fin rfl ⟨i, hi⟩).2, have : c.boundary ⟨i, hi⟩ = j, by rwa [fin.ext_iff, ← c.blocks_partial_sum hi], exact this.symm } end lemma blocks_sum : c.blocks.sum = n := begin have : c.blocks.take c.length = c.blocks := take_all_of_le (by simp [blocks]), rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length], refl end /-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the blocks as a list of positive integers. -/ def to_composition : composition n := { blocks := c.blocks, blocks_pos := by simp only [blocks, forall_mem_of_fn_iff, blocks_fun_pos c, forall_true_iff], blocks_sum := c.blocks_sum } end composition_as_set /-! ### Equivalence between compositions and compositions as sets In this section, we explain how to go back and forth between a `composition` and a `composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to each other, and construct an equivalence between them called `composition_equiv`. -/ @[simp] lemma composition.to_composition_as_set_length (c : composition n) : c.to_composition_as_set.length = c.length := by simp [composition.to_composition_as_set, composition_as_set.length, c.card_boundaries_eq_succ_length] @[simp] lemma composition_as_set.to_composition_length (c : composition_as_set n) : c.to_composition.length = c.length := by simp [composition_as_set.to_composition, composition.length, composition.blocks] @[simp] lemma composition.to_composition_as_set_blocks (c : composition n) : c.to_composition_as_set.blocks = c.blocks := begin let d := c.to_composition_as_set, change d.blocks = c.blocks, have length_eq : d.blocks.length = c.blocks.length, { convert c.to_composition_as_set_length, simp [composition_as_set.blocks] }, suffices H : ∀ (i ≤ d.blocks.length), (d.blocks.take i).sum = (c.blocks.take i).sum, from eq_of_sum_take_eq length_eq H, assume i hi, have i_lt : i < d.boundaries.card, { convert nat.lt_succ_iff.2 hi, convert d.card_boundaries_eq_succ_length, exact length_of_fn _ }, have i_lt' : i < c.boundaries.card := i_lt, have i_lt'' : i < c.length + 1, by rwa c.card_boundaries_eq_succ_length at i_lt', have A : d.boundaries.order_emb_of_fin rfl ⟨i, i_lt⟩ = c.boundaries.order_emb_of_fin c.card_boundaries_eq_succ_length ⟨i, i_lt''⟩ := rfl, have B : c.size_up_to i = c.boundary ⟨i, i_lt''⟩ := rfl, rw [d.blocks_partial_sum i_lt, composition_as_set.boundary, ← composition.size_up_to, B, A, c.order_emb_of_fin_boundaries] end @[simp] lemma composition_as_set.to_composition_blocks (c : composition_as_set n) : c.to_composition.blocks = c.blocks := rfl @[simp] lemma composition_as_set.to_composition_boundaries (c : composition_as_set n) : c.to_composition.boundaries = c.boundaries := begin ext j, simp [c.mem_boundaries_iff_exists_blocks_sum_take_eq, c.card_boundaries_eq_succ_length, composition.boundary, fin.ext_iff, composition.size_up_to, exists_prop, finset.mem_univ, take, exists_prop_of_true, finset.mem_image, composition_as_set.to_composition_blocks, composition.boundaries], split, { rintros ⟨i, hi⟩, refine ⟨i.1, _, hi⟩, convert i.2, simp }, { rintros ⟨i, i_lt, hi⟩, have : i < c.to_composition.length + 1, by simpa using i_lt, exact ⟨⟨i, this⟩, hi⟩ } end @[simp] lemma composition.to_composition_as_set_boundaries (c : composition n) : c.to_composition_as_set.boundaries = c.boundaries := rfl /-- Equivalence between `composition n` and `composition_as_set n`. -/ def composition_equiv (n : ℕ) : composition n ≃ composition_as_set n := { to_fun := λ c, c.to_composition_as_set, inv_fun := λ c, c.to_composition, left_inv := λ c, by { ext1, exact c.to_composition_as_set_blocks }, right_inv := λ c, by { ext1, exact c.to_composition_boundaries } } instance composition_fintype (n : ℕ) : fintype (composition n) := fintype.of_equiv _ (composition_equiv n).symm lemma composition_card (n : ℕ) : fintype.card (composition n) = 2 ^ (n - 1) := begin rw ← composition_as_set_card n, exact fintype.card_congr (composition_equiv n) end
f144948cb9dd00a6aada72616727996f34d6b4c9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/EllipticCurve.lean
5208e75178cf37e6eb2fcb77c31354e2fcf06047
[ "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
10,972
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, David Kurniadi Angdinata -/ import algebra.cubic_discriminant import tactic.linear_combination /-! # The category of elliptic curves (over a field or a PID) We give a working definition of elliptic curves which is mathematically accurate in many cases, and also good for computation. ## Mathematical background Let `S` be a scheme. The actual category of elliptic curves over `S` is a large category, whose objects are schemes `E` equipped with a map `E → S`, a section `S → E`, and some axioms (the map is smooth and proper and the fibres are geometrically connected group varieties of dimension one). In the special case where `S` is `Spec R` for some commutative ring `R` whose Picard group is trivial (this includes all fields, all principal ideal domains, and many other commutative rings) then it can be shown (using rather a lot of algebro-geometric machinery) that every elliptic curve is, up to isomorphism, a projective plane cubic defined by the equation `y² + a₁xy + a₃y = x³ + a₂x² + a₄x + a₆`, with `aᵢ : R`, and such that the discriminant of the aᵢ is a unit in `R`. Some more details of the construction can be found on pages 66-69 of [N. Katz and B. Mazur, *Arithmetic moduli of elliptic curves*][katz_mazur] or pages 53-56 of [P. Deligne, *Courbes elliptiques: formulaire d'après J. Tate*][deligne_formulaire]. ## Warning The definition in this file makes sense for all commutative rings `R`, but it only gives a type which can be beefed up to a category which is equivalent to the category of elliptic curves over `Spec R` in the case that `R` has trivial Picard group `Pic R` or, slightly more generally, when its `12`-torsion is trivial. The issue is that for a general ring `R`, there might be elliptic curves over `Spec R` in the sense of algebraic geometry which are not globally defined by a cubic equation valid over the entire base. ## TODO Define the `R`-points (or even `A`-points if `A` is an `R`-algebra). Care will be needed at infinity if `R` is not a field. Define the group law on the `R`-points. Prove associativity (hard). -/ universes u v /-- The discriminant of an elliptic curve given by the long Weierstrass equation `y² + a₁xy + a₃y = x³ + a₂x² + a₄x + a₆`. If `R` is a field, then this polynomial vanishes iff the cubic curve cut out by this equation is singular. Sometimes only defined up to sign in the literature; we choose the sign used by the LMFDB. For more discussion, see [the LMFDB page on discriminants](https://www.lmfdb.org/knowledge/show/ec.discriminant). -/ @[simp] def EllipticCurve.Δ_aux {R : Type u} [comm_ring R] (a₁ a₂ a₃ a₄ a₆ : R) : R := let b₂ : R := a₁ ^ 2 + 4 * a₂, b₄ : R := 2 * a₄ + a₁ * a₃, b₆ : R := a₃ ^ 2 + 4 * a₆, b₈ : R := a₁ ^ 2 * a₆ + 4 * a₂ * a₆ - a₁ * a₃ * a₄ + a₂ * a₃ ^ 2 - a₄ ^ 2 in -b₂ ^ 2 * b₈ - 8 * b₄ ^ 3 - 27 * b₆ ^ 2 + 9 * b₂ * b₄ * b₆ /-- The category of elliptic curves over `R` (note that this definition is only mathematically correct for certain rings `R` with `Pic(R)[12] = 0`, for example if `R` is a field or a PID). -/ structure EllipticCurve (R : Type u) [comm_ring R] := (a₁ a₂ a₃ a₄ a₆ : R) (Δ : Rˣ) (Δ_eq : ↑Δ = EllipticCurve.Δ_aux a₁ a₂ a₃ a₄ a₆) namespace EllipticCurve instance : inhabited (EllipticCurve ℚ) := ⟨⟨0, 0, 1, -1, 0, ⟨37, 37⁻¹, by norm_num1, by norm_num1⟩, show (37 : ℚ) = _ + _, by norm_num1 ⟩⟩ variables {R : Type u} [comm_ring R] (E : EllipticCurve R) section quantity /-! ### Standard quantities -/ /-- The `b₂` coefficient of an elliptic curve. -/ @[simp] def b₂ : R := E.a₁ ^ 2 + 4 * E.a₂ /-- The `b₄` coefficient of an elliptic curve. -/ @[simp] def b₄ : R := 2 * E.a₄ + E.a₁ * E.a₃ /-- The `b₆` coefficient of an elliptic curve. -/ @[simp] def b₆ : R := E.a₃ ^ 2 + 4 * E.a₆ /-- The `b₈` coefficient of an elliptic curve. -/ @[simp] def b₈ : R := E.a₁ ^ 2 * E.a₆ + 4 * E.a₂ * E.a₆ - E.a₁ * E.a₃ * E.a₄ + E.a₂ * E.a₃ ^ 2 - E.a₄ ^ 2 lemma b_relation : 4 * E.b₈ = E.b₂ * E.b₆ - E.b₄ ^ 2 := by { simp, ring1 } /-- The `c₄` coefficient of an elliptic curve. -/ @[simp] def c₄ : R := E.b₂ ^ 2 - 24 * E.b₄ /-- The `c₆` coefficient of an elliptic curve. -/ @[simp] def c₆ : R := -E.b₂ ^ 3 + 36 * E.b₂ * E.b₄ - 216 * E.b₆ @[simp] lemma coe_Δ : ↑E.Δ = -E.b₂ ^ 2 * E.b₈ - 8 * E.b₄ ^ 3 - 27 * E.b₆ ^ 2 + 9 * E.b₂ * E.b₄ * E.b₆ := E.Δ_eq lemma c_relation : 1728 * ↑E.Δ = E.c₄ ^ 3 - E.c₆ ^ 2 := by { simp, ring1 } /-- The j-invariant of an elliptic curve, which is invariant under isomorphisms over `R`. -/ @[simp] def j : R := ↑E.Δ⁻¹ * E.c₄ ^ 3 end quantity section torsion_polynomial /-! ### `2`-torsion polynomials -/ /-- The polynomial whose roots over a splitting field of `R` are the `2`-torsion points of the elliptic curve when `R` is a field of characteristic different from `2`, and whose discriminant happens to be a multiple of the discriminant of the elliptic curve. -/ def two_torsion_polynomial : cubic R := ⟨4, E.b₂, 2 * E.b₄, E.b₆⟩ lemma two_torsion_polynomial.disc_eq : E.two_torsion_polynomial.disc = 16 * E.Δ := by { simp only [two_torsion_polynomial, cubic.disc, coe_Δ, b₂, b₄, b₆, b₈], ring1 } lemma two_torsion_polynomial.disc_ne_zero [nontrivial R] [invertible (2 : R)] : E.two_torsion_polynomial.disc ≠ 0 := λ hdisc, E.Δ.ne_zero $ (is_unit_of_invertible $ 2 ^ 4).mul_left_cancel $ by linear_combination hdisc - two_torsion_polynomial.disc_eq E with { normalization_tactic := `[ring1] } end torsion_polynomial section base_change /-! ### Base changes -/ variables (A : Type v) [comm_ring A] [algebra R A] private meta def simp_map : tactic unit := `[simp only [map_one, map_bit0, map_bit1, map_neg, map_add, map_sub, map_mul, map_pow]] /-- The elliptic curve over `R` base changed to `A`. -/ @[simps] def base_change : EllipticCurve A := { a₁ := algebra_map R A E.a₁, a₂ := algebra_map R A E.a₂, a₃ := algebra_map R A E.a₃, a₄ := algebra_map R A E.a₄, a₆ := algebra_map R A E.a₆, Δ := units.map ↑(algebra_map R A) E.Δ, Δ_eq := by { simp only [units.coe_map, ring_hom.coe_monoid_hom, Δ_eq, Δ_aux], simp_map } } @[simp] lemma base_change_b₂ : (E.base_change A).b₂ = algebra_map R A E.b₂ := by { simp only [b₂, base_change_a₁, base_change_a₂], simp_map } @[simp] lemma base_change_b₄ : (E.base_change A).b₄ = algebra_map R A E.b₄ := by { simp only [b₄, base_change_a₁, base_change_a₃, base_change_a₄], simp_map } @[simp] lemma base_change_b₆ : (E.base_change A).b₆ = algebra_map R A E.b₆ := by { simp only [b₆, base_change_a₃, base_change_a₆], simp_map } @[simp] lemma base_change_b₈ : (E.base_change A).b₈ = algebra_map R A E.b₈ := by { simp only [b₈, base_change_a₁, base_change_a₂, base_change_a₃, base_change_a₄, base_change_a₆], simp_map } @[simp] lemma base_change_c₄ : (E.base_change A).c₄ = algebra_map R A E.c₄ := by { simp only [c₄, base_change_b₂, base_change_b₄], simp_map } @[simp] lemma base_change_c₆ : (E.base_change A).c₆ = algebra_map R A E.c₆ := by { simp only [c₆, base_change_b₂, base_change_b₄, base_change_b₆], simp_map } lemma base_change_Δ_coe : ↑(E.base_change A).Δ = algebra_map R A E.Δ := rfl lemma base_change_Δ_inv_coe : ↑(E.base_change A).Δ⁻¹ = algebra_map R A ↑E.Δ⁻¹ := rfl @[simp] lemma base_change_j : (E.base_change A).j = algebra_map R A E.j := by { simp only [j, base_change_c₄, base_change_Δ_inv_coe], simp_map } end base_change section variable_change /-! ### Variable changes -/ variables (u : Rˣ) (r s t : R) /-- The elliptic curve over `R` induced by an admissible linear change of variables `(x, y) ↦ (u²x + r, u³y + u²sx + t)` for some `u ∈ Rˣ` and some `r, s, t ∈ R`. When `R` is a field, any two isomorphic long Weierstrass equations are related by this. -/ @[simps] def variable_change : EllipticCurve R := { a₁ := ↑u⁻¹ * (E.a₁ + 2 * s), a₂ := ↑u⁻¹ ^ 2 * (E.a₂ - s * E.a₁ + 3 * r - s ^ 2), a₃ := ↑u⁻¹ ^ 3 * (E.a₃ + r * E.a₁ + 2 * t), a₄ := ↑u⁻¹ ^ 4 * (E.a₄ - s * E.a₃ + 2 * r * E.a₂ - (t + r * s) * E.a₁ + 3 * r ^ 2 - 2 * s * t), a₆ := ↑u⁻¹ ^ 6 * (E.a₆ + r * E.a₄ + r ^ 2 * E.a₂ + r ^ 3 - t * E.a₃ - t ^ 2 - r * t * E.a₁), Δ := u⁻¹ ^ 12 * E.Δ, Δ_eq := by { simp [-inv_pow], ring1 } } @[simp] lemma variable_change_b₂ : (E.variable_change u r s t).b₂ = ↑u⁻¹ ^ 2 * (E.b₂ + 12 * r) := by { simp only [b₂, variable_change_a₁, variable_change_a₂], ring1 } @[simp] lemma variable_change_b₄ : (E.variable_change u r s t).b₄ = ↑u⁻¹ ^ 4 * (E.b₄ + r * E.b₂ + 6 * r ^ 2) := by { simp only [b₂, b₄, variable_change_a₁, variable_change_a₃, variable_change_a₄], ring1 } @[simp] lemma variable_change_b₆ : (E.variable_change u r s t).b₆ = ↑u⁻¹ ^ 6 * (E.b₆ + 2 * r * E.b₄ + r ^ 2 * E.b₂ + 4 * r ^ 3) := by { simp only [b₂, b₄, b₆, variable_change_a₃, variable_change_a₆], ring1 } @[simp] lemma variable_change_b₈ : (E.variable_change u r s t).b₈ = ↑u⁻¹ ^ 8 * (E.b₈ + 3 * r * E.b₆ + 3 * r ^ 2 * E.b₄ + r ^ 3 * E.b₂ + 3 * r ^ 4) := by { simp only [b₂, b₄, b₆, b₈, variable_change_a₁, variable_change_a₂, variable_change_a₃, variable_change_a₄, variable_change_a₆], ring1 } @[simp] lemma variable_change_c₄ : (E.variable_change u r s t).c₄ = ↑u⁻¹ ^ 4 * E.c₄ := by { simp only [c₄, variable_change_b₂, variable_change_b₄], ring1 } @[simp] lemma variable_change_c₆ : (E.variable_change u r s t).c₆ = ↑u⁻¹ ^ 6 * E.c₆ := by { simp only [c₆, variable_change_b₂, variable_change_b₄, variable_change_b₆], ring1 } lemma variable_change_Δ_coe : (↑(E.variable_change u r s t).Δ : R) = ↑u⁻¹ ^ 12 * E.Δ := by rw [variable_change_Δ, units.coe_mul, units.coe_pow] lemma variable_change_Δ_inv_coe : (↑(E.variable_change u r s t).Δ⁻¹ : R) = u ^ 12 * ↑E.Δ⁻¹ := by rw [variable_change_Δ, mul_inv, inv_pow, inv_inv, units.coe_mul, units.coe_pow] @[simp] lemma variable_change_j : (E.variable_change u r s t).j = E.j := begin simp only [b₂, b₄, c₄, j, variable_change_c₄, variable_change_Δ, mul_inv, inv_pow, inv_inv, units.coe_mul, u.coe_pow], have hu : (u * ↑u⁻¹ : R) ^ 12 = 1 := by rw [u.mul_inv, one_pow], linear_combination ↑E.Δ⁻¹ * ((E.a₁ ^ 2 + 4 * E.a₂) ^ 2 - 24 * (2 * E.a₄ + E.a₁ * E.a₃)) ^ 3 * hu with { normalization_tactic := `[ring1] } end end variable_change end EllipticCurve
c0e28902db4ddb0051fc7cbcbf648fad5253b71b
cc104245380aa3287223e0e350a8319e583aba37
/src/h0reviewed.lean
20112fb815f6e135c36ebd6183f06974238aa9fb
[]
no_license
anca797/group-cohomology
7d10749d28430d30698e7ec0cc33adbac97fe5e7
f896dfa5057bd70c6fbb09ee6fdc26a7ffab5e5d
refs/heads/master
1,591,037,800,699
1,561,424,571,000
1,561,424,571,000
190,891,710
3
0
null
null
null
null
UTF-8
Lean
false
false
1,907
lean
import algebra.module group_theory.subgroup class group_module (G : Type*) [group G] (M : Type*) [add_comm_group M] extends has_scalar G M := (one_smul : ∀ m : M, (1 : G) • m = m) (smul_smul : ∀ g h : G, ∀ m : M, g • (h • m) = (g * h) • m) (smul_add : ∀ g : G, ∀ m n : M, g • (m + n) = g • m + g • n) namespace group_module variables {G : Type*} [group G] {M : Type*} [add_comm_group M] [group_module G M] variables (M) instance is_add_group_hom_smul (g : G) : is_add_group_hom ((•) g : M → M) := ⟨group_module.smul_add g⟩ lemma smul_zero (g : G) : g • (0 : M) = 0 := is_add_group_hom.zero _ variables {M} lemma smul_neg (g : G) (m : M) : g • (-m) = -(g • m) := is_add_group_hom.neg _ _ definition fixed_points (G : Type*) [group G] (M : Type*) [add_comm_group M] [group_module G M] : set M := {m : M | ∀ g : G, g • m = m} instance fixed_points.is_add_subgroup : is_add_subgroup (fixed_points G M) := { add_mem := λ m n hm hn g, by rw [smul_add, hm g, hn g], zero_mem := smul_zero M, neg_mem := λ m hm g, by rw [smul_neg, hm g] } definition H0 (G : Type*) [group G] (M : Type*) [add_comm_group M] [group_module G M] := fixed_points G M instance H0.add_comm_group : add_comm_group (H0 G M) := { add_comm := λ m n, subtype.eq $ add_comm _ _, .. @subtype.add_group _ _ _ fixed_points.is_add_subgroup } end group_module variables {G : Type*} [group G] {M : Type*} [add_comm_group M] [group_module G M] variables {N : Type*} [add_comm_group N] [group_module G N] variable (G) def is_group_module_hom (f : M → N) : Prop := ∀ g : G, ∀ m : M, f (g • m) = g • (f m) namespace is_group_module_hom open group_module def map_H0 (f : M → N) (hf : is_group_module_hom G f) (x : H0 G M) : H0 G N := ⟨f x.1, λ g, by rw [← hf, x.2]⟩ lemma id.group_module_hom : is_group_module_hom G (id : M → M) := λ g m, rfl end is_group_module_hom
608c4c5326b60aec083da958c8f0f747f747325a
4034f8da6f54c838133a7ab6a8c0c61086c9c949
/src/bundles.lean
e8beee6c51ae23420ff356da1dd0db24dba516dd
[]
no_license
mguaypaq/lean-topology
f9e6c69e2b85cca1377ee89d75c65bd384225170
57b15b3862d441095e254e65009856fa922758cc
refs/heads/main
1,691,451,271,943
1,631,647,691,000
1,631,647,691,000
398,682,545
0
0
null
null
null
null
UTF-8
Lean
false
false
17,916
lean
import tactic import .topology import .gluing import .fiber_product section fiber_bundle /- Bundles. Goal: Show that trivializations pull back. We distinguish between: 1. *trivial bundles* : these are bundles of the form prod.fst : B × fiber → B 2. *trivializations of bundles* : given π : E → B, this is the data of φ : equiv (B × fiber) E, hφ : π ∘ φ = prod.fst These aren't the same thing of course. (In real life, this occurs when a bundle can be trivialized in many ways. Think of picking a basis of a vector space. For trivial bundles (1), the choice is already made. Otherwise it's data.) Warning: The pullback of a trivial bundle B × fiber along f : B' → B is trivializable, in fact *canonically* trivializable (we will write down a natural trivialization). But it is not *definitionally* trivial. This is because it has the form {(b, f b, v)} ⊆ B' × (B × fiber) rather than being B' × fiber, with the definition we give in terms of fiber products. It is (almost) defeq to (id ×f f) × fiber, except for being parenthesized wrong. Our approach: a) Define bundles, bundle maps and functorial pullbacks of bundle maps (in particular of equivalences). b) Define trivial bundle c) Define trivialization of bundle (:= equivalence to the bundle from a trivial bundle) d) Construct a *canonical* trivialization of the pullback of a trivial bundle. (Method: equivalence from trivial bundles to bundles pulled back from the constant map to a point). e) Combine (a) and (d) to "pull back trivializations". 🎉 -/ -- Bundles and bundle maps. structure bundle (B : Type) := (space : Type) (π : space → B) instance bundle_to_proj (B : Type) : has_coe_to_fun (bundle B) := { F := λ E, E.space → B, coe := λ E, E.π } @[ext] structure bundle_map {B : Type} (E F : bundle B) := (map : E.space → F.space) (h : F.π ∘ map = E.π) infix `→→`:110 := bundle_map instance bundle_map_to_fn {B : Type} (E F : bundle B) : has_coe_to_fun (E →→ F) := { F := λ φ, E.space → F.space, coe := λ φ, φ.map } def bundle_map.id {B : Type} (E : bundle B) : E →→ E := { map := id, h := function.comp.right_id E.π, } def bundle_map.comp {B : Type} {E F G : bundle B} (φ' : F →→ G) (φ : E →→ F) : E →→ G := { map := φ'.map ∘ φ.map, h := by rw [← function.comp.assoc, φ'.h, φ.h], } infix `∘∘`:110 := bundle_map.comp @[simp] lemma bundle_map.comp.assoc {B : Type} {E F G H : bundle B} (φ'' : G →→ H) (φ' : F →→ G) (φ : E →→ F) : (φ'' ∘∘ φ') ∘∘ φ = φ'' ∘∘ (φ' ∘∘ φ) := rfl @[simp] lemma bundle_map.left_id {B : Type} {E F : bundle B} (φ : bundle_map E F) : (bundle_map.id F) ∘∘ φ = φ := begin ext x, refl, end @[simp] lemma bundle_map.right_id {B : Type} {E F : bundle B} (φ : bundle_map E F) : φ ∘∘ (bundle_map.id E) = φ := begin ext x, refl, end structure bundle_equiv {B : Type} (E F : bundle B) := (to_bundle_map : E →→ F) (inv_bundle_map : F →→ E) (left_inv : inv_bundle_map ∘∘ to_bundle_map = bundle_map.id E) (right_inv : to_bundle_map ∘∘ inv_bundle_map = bundle_map.id F) infix `≃≃`:100 := bundle_equiv def bundle_equiv.mk' {B : Type} {E F : bundle B} (φ : equiv E.space F.space) (hφ : F.π ∘ φ.to_fun = E.π) (hφ_inv : E.π ∘ φ.inv_fun = F.π) : E ≃≃ F := { to_bundle_map := ⟨φ.to_fun, hφ⟩, inv_bundle_map := ⟨φ.inv_fun, hφ_inv⟩, left_inv := begin ext e, exact φ.left_inv e, end, right_inv := begin ext e, exact φ.right_inv e, end } def bundle_equiv.symm {B : Type} {E F : bundle B} (φ : E ≃≃ F) : F ≃≃ E := { to_bundle_map := φ.inv_bundle_map, inv_bundle_map := φ.to_bundle_map, left_inv := φ.right_inv, right_inv := φ.left_inv } def bundle_equiv.trans {B : Type} {E F G : bundle B} (φ : E ≃≃ F) (φ' : F ≃≃ G) : E ≃≃ G := { to_bundle_map := φ'.to_bundle_map ∘∘ φ.to_bundle_map, inv_bundle_map := φ.inv_bundle_map ∘∘ φ'.inv_bundle_map, left_inv := by rw [bundle_map.comp.assoc, ← bundle_map.comp.assoc φ'.inv_bundle_map, φ'.left_inv, bundle_map.left_id, φ.left_inv], right_inv := by rw [bundle_map.comp.assoc, ← bundle_map.comp.assoc φ.to_bundle_map, φ.right_inv, bundle_map.left_id, φ'.right_inv], } infix `≃∘≃`:110 := bundle_equiv.trans section pullback -- Pullbacks. Closely related to fiber products. open fiber_product @[reducible] def pullback_bundle {B' B : Type} (f : B' → B) (E : bundle B) : bundle B' := { space := E.π ×f f, π := fiber_product.fst E.π f } infix `**`:110 := pullback_bundle def pullback_map {B' B : Type} (f : B' → B) {E F : bundle B} (φ : E →→ F) : (f ** E) →→ (f ** F) := { map := fiber_product.exact.map F.π f (f ** E).π (φ.map ∘ (fiber_product.snd E.π f)) begin rw [← function.comp.assoc F.π, φ.h, ← fiber_product.sound], end, h := begin ext ⟨⟨e', b'⟩, h⟩, refl, end, } infix `↖*`:110 := pullback_map @[simp] lemma pullback_map.def {B' B : Type} (f : B' → B) {E F G : bundle B} (φ' : F →→ G) (φ : E →→ F) {b' : B'} {e : E.space} {h : f b' = E.π e} : (f ↖* φ) ⟨(b', e), h⟩ = ⟨(b', φ e), begin change f b' = (F.π ∘ φ.map) e, rw φ.h, exact h, end⟩ := rfl lemma pullback_map.comp {B' B : Type} (f : B' → B) {E F G : bundle B} (φ' : F →→ G) (φ : E →→ F) : (f ↖* φ') ∘∘ (f ↖* φ) = f ↖* (φ' ∘∘ φ) := rfl lemma pullback_map.of_id {B' B : Type} (f : B' → B) (E : bundle B) : (f ↖* (bundle_map.id E)) = (bundle_map.id (f ** E)) := begin ext ⟨⟨e, b'⟩, h⟩, refl, refl, end def pullback_bundle_equiv {B' B : Type} (f : B' → B) {E F : bundle B} (φ : E ≃≃ F) : (f ** E) ≃≃ (f ** F) := { to_bundle_map := f ↖* φ.to_bundle_map, inv_bundle_map := f ↖* φ.inv_bundle_map, left_inv := by rw [pullback_map.comp, φ.left_inv, pullback_map.of_id], right_inv := by rw [pullback_map.comp, φ.right_inv, pullback_map.of_id], } infix `↖≃`:110 := pullback_bundle_equiv def pullback_comp {B'' B' B : Type} (g : B'' → B') (f : B' → B) (E : bundle B) : g ** (f ** E) ≃≃ (f ∘ g) ** E := @bundle_equiv.mk' B'' (g ** (f ** E)) ((f ∘ g) ** E) (fiber_product.comp_base E.π f g) rfl rfl end pullback section trivial_bundle -- Trivial bundles @[reducible] def trivial_bundle (B fiber : Type) : bundle B := { space := B × fiber, π := prod.fst } infix `××`:110 := trivial_bundle @[reducible] def trivial_equiv_pullback_from_pt (B fiber : Type) : B ×× fiber ≃≃ (topology.map_to_point B) ** (trivial_bundle topology.point fiber) := bundle_equiv.mk' (equiv.trans (prod_equiv_left B (prod_point_left fiber)).symm { to_fun := restrict_cod id (λ b, (topology.point.is_singleton b.snd.fst).symm), inv_fun := coe, left_inv := begin rintro ⟨x, y⟩, refl, end, right_inv := begin rintro ⟨x, h⟩, refl, end } ) rfl rfl end trivial_bundle section trivialization -- Trivializations. @[reducible] def trivialization {B : Type} (E : bundle B) (fiber : Type) := (B ×× fiber) ≃≃ E /- -- Trivializing the pullback of a trivial bundle along any map. -- This has to be done "by hand". def trivialization_of_pullback_of_trivial {B B' : Type} (fiber : Type) (f : B' → B) : trivialization (f ** (B ×× fiber)) fiber := bundle_equiv.mk' (equiv.trans (prod_equiv_right (domain_equiv_graph f) fiber) (graph_equiv_pullback_of_trivial fiber f)) rfl begin ext ⟨⟨b', b, v⟩, h⟩, refl, end -- Pullback of a *trivialization* along any map. 🎉 def trivialization.pullback' {B B' : Type} (E : bundle B) (fiber : Type) (f : B' → B) (triv : trivialization E fiber) : trivialization (f ** E) fiber := bundle_equiv.trans (trivialization_of_pullback_of_trivial fiber f) (f ↖≃ triv) -/ -- Pullback of a *trivialization* along any map. 🎉 def trivialization.pullback {B B' : Type} {E : bundle B} {fiber : Type} (f : B' → B) (triv : trivialization E fiber) : trivialization (f ** E) fiber := trivial_equiv_pullback_from_pt B' fiber ≃∘≃ (pullback_comp f (topology.map_to_point B) (topology.point ×× fiber)).symm ≃∘≃ (f ↖≃ (triv.symm ≃∘≃ trivial_equiv_pullback_from_pt B fiber)).symm -- This says: -- B' ×× fiber -- ≃≃ (B' → point) ** (point ×× fiber) -- ≃≃ (B' → B) ** ((B → point) ** (point ×× fiber)) -- ≃≃ f ** (B ×× fiber) -- ≃≃ f ** E -- As desired. def trivialization.subset {B : Type} (U : set B) {E : bundle B} {fiber : Type} (triv : trivialization E fiber) : trivialization ((coe : U → B) ** E) fiber := trivialization.pullback coe triv -- Given a trivialization over A ⊆ B, obtain a trivialization over A ∩ V. -- (By pulling back along A ∩ V → A.) def trivialization.subset_of_subset {B fiber : Type} (E : bundle B) (A V : set B) (triv : trivialization ((coe : A → B) ** E) fiber) : trivialization ((coe : (A ∩ V) → B) ** E) fiber := let c1 : (A ∩ V) → A := set.inclusion (set.inter_subset_left _ _) in bundle_equiv.trans (@trivialization.pullback _ _ _ fiber c1 triv) (pullback_comp c1 (coe : A → B) E) end trivialization section locally_trivial_fiber_bundle variables {B : Type} (E : bundle B) (fiber : Type) [topology B] [topology E.space] [topology fiber] {I : Type} (U : open_cover I B) -- 🎉 🎉 🎉 -- structure local_trivialization (h : cts E.π) := (triv : ∀ i, trivialization ((coe : U i → B) ** E) fiber) (htriv : ∀ i, cts (triv i).to_bundle_map) (htriv_inv : ∀ i, cts (triv i).inv_bundle_map) example {J : Type} (V : open_cover J B) (h : cts E.π) (loc_triv : local_trivialization E fiber U h) : @local_trivialization B E fiber _ _ _ (I × J) (open_cover.refine U V) h := { triv := λ ij, trivialization.subset_of_subset E (U ij.1) (V ij.2) (loc_triv.triv ij.1), htriv := begin rintro ⟨i, j⟩, unfold trivialization.subset_of_subset, sorry, -- make continuity lemmas for ≃≃s end, htriv_inv := sorry, } end locally_trivial_fiber_bundle section cts_bundle -- Bundle maps variables {B : Type} --[topology B] lemma bundle_map.id.cts (E : bundle B) [topology E.space] : cts (bundle_map.id E) := cts.id variables {E F G : bundle B} [topology E.space] [topology F.space] [topology G.space] lemma bundle_map.comp.cts {φ' : F →→ G} {φ : E →→ F} (hφ' : cts φ'.map) (hφ : cts φ.map) : cts (φ' ∘∘ φ).map := cts_of_comp _ _ hφ hφ' -- Bundle equivalences lemma bundle_equiv.symm.cts {φ : E ≃≃ F} (hφ_inv : cts φ.inv_bundle_map) : cts φ.symm.to_bundle_map := hφ_inv lemma bundle_equiv.symm.inv_cts {φ : E ≃≃ F} (hφ : cts φ.to_bundle_map) : cts φ.symm.inv_bundle_map := hφ lemma bundle_equiv.trans.cts {φ : E ≃≃ F} {φ' : F ≃≃ G} (hφ'_cts : cts φ'.to_bundle_map) (hφ_cts : cts φ.to_bundle_map): cts (bundle_equiv.trans φ φ').to_bundle_map.map := bundle_map.comp.cts hφ'_cts hφ_cts lemma bundle_equiv.trans.inv_cts {φ : E ≃≃ F} {φ' : F ≃≃ G} (hφ'_inv_cts : cts φ'.inv_bundle_map) (hφ_inv_cts : cts φ.inv_bundle_map): cts (bundle_equiv.trans φ φ').inv_bundle_map.map := bundle_map.comp.cts hφ_inv_cts hφ'_inv_cts lemma bundle_equiv.mk'.cts {φ : E.space ≃ F.space} {hφ : F.π ∘ φ.to_fun = E.π} {hφ_inv : E.π ∘ φ.inv_fun = F.π} (hφ_cts : cts φ) : cts (bundle_equiv.mk' φ hφ hφ_inv).to_bundle_map := hφ_cts lemma bundle_equiv.mk'.inv_cts {φ : E.space ≃ F.space} {hφ : F.π ∘ φ.to_fun = E.π} {hφ_inv : E.π ∘ φ.inv_fun = F.π} (hφ_inv_cts : cts φ.inv_fun) : cts (bundle_equiv.mk' φ hφ hφ_inv).inv_bundle_map := hφ_inv_cts -- Pullback maps and equivs variables {B' : Type} (f : B' → B) [topology B] [topology B'] --(hf : cts f) lemma pullback_map.cts {φ : E →→ F} (hφ : cts φ.map) : cts (f ↖* φ).map := begin apply fiber_product.exact.map.cts, exact fiber_product.fst.cts _ _, apply cts_of_comp _ φ.map _ hφ, exact fiber_product.snd.cts _ _, end lemma pullback_bundle_equiv.cts {φ : E ≃≃ F} (hφ_cts : cts φ.to_bundle_map) : cts (f ↖≃ φ).to_bundle_map := pullback_map.cts f hφ_cts lemma pullback_bundle_equiv.inv_cts {φ : E ≃≃ F} (hφ_inv_cts : cts φ.inv_bundle_map) : cts (f ↖≃ φ).inv_bundle_map := pullback_map.cts f hφ_inv_cts variables {B'' : Type} [topology B''] (g : B'' → B') lemma pullback_comp.cts (hf : cts f) : cts (pullback_comp g f E).to_bundle_map := bundle_equiv.mk'.cts (fiber_product.comp_base.cts _ _ _ hf) lemma pullback_comp.inv_cts (hg : cts g) : cts (pullback_comp g f E).inv_bundle_map := bundle_equiv.mk'.inv_cts (fiber_product.comp_base.inv_cts _ _ _ hg) -- Trivializations variables (fiber : Type) [topology fiber] lemma trivial_equiv_pullback_from_pt.cts : cts (trivial_equiv_pullback_from_pt B fiber).to_bundle_map := begin apply bundle_equiv.mk'.cts _, apply restrict_cod_cts _, apply prod_equiv_left.cts, exact prod_point_left.inv_cts fiber, exact prod_point_left.cts fiber, end lemma trivial_equiv_pullback_from_pt.inv_cts : cts (trivial_equiv_pullback_from_pt B fiber).inv_bundle_map := begin apply bundle_equiv.mk'.inv_cts _, apply cts_of_comp _ _ coe_cts, apply prod_equiv_left.cts, exact prod_point_left.cts fiber, exact prod_point_left.inv_cts fiber, end lemma trivialization.pullback.cts (hf : cts f) {triv : trivialization E fiber} (htriv_cts : cts triv.to_bundle_map) : cts (trivialization.pullback f triv).to_bundle_map := begin apply bundle_equiv.trans.cts _ _, by apply_instance, apply bundle_equiv.symm.cts, apply pullback_map.cts, apply bundle_equiv.trans.inv_cts _ _, by apply_instance, apply trivial_equiv_pullback_from_pt.inv_cts, exact htriv_cts, -- assumption used!! apply bundle_equiv.trans.cts _ _, by apply_instance, apply bundle_equiv.symm.cts, apply pullback_comp.inv_cts, exact hf, -- assumption used!! apply trivial_equiv_pullback_from_pt.cts, end lemma trivialization.pullback.inv_cts {triv : trivialization E fiber} (htriv_inv_cts : cts triv.inv_bundle_map) : cts (trivialization.pullback f triv).inv_bundle_map := begin apply bundle_equiv.trans.inv_cts _ _, by apply_instance, apply bundle_equiv.symm.inv_cts, apply pullback_map.cts, apply bundle_equiv.trans.cts _ _, by apply_instance, apply trivial_equiv_pullback_from_pt.cts, exact htriv_inv_cts, -- assumption used!! apply bundle_equiv.trans.inv_cts _ _, by apply_instance, apply bundle_equiv.symm.inv_cts, apply pullback_comp.cts, apply map_to_point_cts, apply trivial_equiv_pullback_from_pt.inv_cts, end /- structure cts_bundle (B : Type) [topology B] := (space : Type) (top : topology space) (π : space → B) (hπ : cts π) instance cts_bundle_to_bundle (B : Type) [topology B] : has_coe (cts_bundle B) (bundle B) := ⟨λ E, ⟨E.space, E.π⟩⟩ attribute [instance] cts_bundle.top variables {B : Type} [topology B] (E F : cts_bundle B) structure cts_bundle_map := (map : E.space → F.space) (h : F.π ∘ map = E.π) (map_cts : cts map) instance cts_bundle_map_to_bundle_map : has_coe (cts_bundle_map E F) (@bundle_map B ↑E ↑F) := ⟨λ φ, ⟨φ.map, φ.h⟩⟩ structure cts_bundle_equiv := (map : cts_bundle_map E F) (inv_map : cts_bundle_map F E) (left_inv : ↑inv_map ∘∘ ↑map = bundle_map.id ↑E) (right_inv : ↑map ∘∘ ↑inv_map = bundle_map.id ↑F) : def cts_bundle_equiv.mk' {B : Type} [topology B] {E F : cts_bundle B} (map : cts_bundle_map E F) (inv_map : cts_bundle_map F E) (left_inv : inv_map.to_bundle_map ∘∘ map.to_bundle_map = bundle_map.id E.to_bundle) (right_inv : map.to_bundle_map ∘∘ inv_map.to_bundle_map = bundle_map.id F.to_bundle) : cts_bundle_equiv E F := { to_bundle_equiv := { to_bundle_map := map.to_bundle_map, inv_bundle_map := inv_map.to_bundle_map, left_inv := left_inv, right_inv := right_inv }, map_cts := map.map_cts, inv_cts := inv_map.map_cts} def cts_bundle_equiv.to_cts_bundle_map {B : Type} [topology B] {E F : cts_bundle B} (φ : cts_bundle_equiv E F) : cts_bundle_map E F := ⟨φ.to_bundle_map, φ.map_cts⟩ def cts_bundle_equiv.inv_cts_bundle_map {B : Type} [topology B] {E F : cts_bundle B} (φ : cts_bundle_equiv E F) : cts_bundle_map F E := ⟨φ.inv_bundle_map, φ.inv_cts⟩ def cts_bundle_map.id {B : Type} [topology B] (E : cts_bundle B) : cts_bundle_map E E := { map_cts := cts.id, ..(bundle_map.id E.to_bundle) } def cts_bundle_map.comp {B : Type} -- What is the most appropriate / efficient thing to do here? /- structure cts_bundle (B : Type) [topology B] extends (bundle B) := (top : topology to_bundle.space) (hπ : cts to_bundle.π) structure cts_bundle_map {B : Type} [topology B] {E F : cts_bundle B} extends (bundle_map E.to_bundle F.to_bundle) := (hcts : @cts _ _ E.top F.top to_bundle_map.map) ... But then we have to start explicitly referring to the topology everywhere. Or: just assume [topology t] for all relevant spaces t and (hf: cts f) for all relevant f? Or: put back in an assumption (hf : adjective f) throughout, where the adjective is part of the data of the bundle. -/ -/ end cts_bundle end fiber_bundle
00b779129576ec56db86f2680e34b79d1bce99ee
367134ba5a65885e863bdc4507601606690974c1
/src/data/list/nodup_equiv_fin.lean
33e18caebd13e0d313814d2938e3e735f0c32297
[ "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
2,381
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 data.list.sort import data.fin /-! # Isomorphism between `fin (length l)` and `{x // x ∈ l}` Given a list `l, * if `l` has no duplicates, then `list.nodup.nth_le_equiv` is the bijection between `fin (length l)` and `{x // x ∈ l}` sending `⟨i, hi⟩` to `⟨nth_le l i hi, _⟩` with the inverse sending `⟨x, hx⟩` to `⟨index_of x l, _⟩`; * if `l` is sorted w.r.t. `(<)`, then `list.sorted.nth_le_iso` is the same bijection reinterpreted as an `order_iso`. -/ namespace list variable {α : Type*} namespace nodup variable [decidable_eq α] /-- If `l` has no duplicates, then `list.nth_le` defines a bijection between `fin (length l)` and the set of elements of `l`. -/ def nth_le_equiv (l : list α) (H : nodup l) : fin (length l) ≃ {x // x ∈ l} := { to_fun := λ i, ⟨nth_le l i i.2, nth_le_mem l i i.2⟩, inv_fun := λ x, ⟨index_of ↑x l, index_of_lt_length.2 x.2⟩, left_inv := λ i, by simp [H], right_inv := λ x, by simp } variables {l : list α} (H : nodup l) (x : {x // x ∈ l}) (i : fin (length l)) @[simp] lemma coe_nth_le_equiv_apply : (H.nth_le_equiv l i : α) = nth_le l i i.2 := rfl @[simp] lemma coe_nth_le_equiv_symm_apply : ((H.nth_le_equiv l).symm x : ℕ) = index_of ↑x l := rfl end nodup namespace sorted variables [preorder α] {l : list α} lemma nth_le_mono (h : l.sorted (≤)) : monotone (λ i : fin l.length, l.nth_le i i.2) := λ i j, h.rel_nth_le_of_le _ _ lemma nth_le_strict_mono (h : l.sorted (<)) : strict_mono (λ i : fin l.length, l.nth_le i i.2) := λ i j, h.rel_nth_le_of_lt _ _ variable [decidable_eq α] /-- If `l` is a list sorted w.r.t. `(<)`, then `list.nth_le` defines an order isomorphism between `fin (length l)` and the set of elements of `l`. -/ def nth_le_iso (l : list α) (H : sorted (<) l) : fin (length l) ≃o {x // x ∈ l} := { to_equiv := H.nodup.nth_le_equiv l, map_rel_iff' := λ i j, H.nth_le_strict_mono.le_iff_le } variables (H : sorted (<) l) {x : {x // x ∈ l}} {i : fin l.length} @[simp] lemma coe_nth_le_iso_apply : (H.nth_le_iso l i : α) = nth_le l i i.2 := rfl @[simp] lemma coe_nth_le_iso_symm_apply : ((H.nth_le_iso l).symm x : ℕ) = index_of ↑x l := rfl end sorted end list
5adeec578ed381147c285d5dbe33509de5179309
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/monomial.lean
8fab24988a903d219754a8cb573b35fa1c461b94
[ "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
2,538
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.basic /-! # Univariate monomials Preparatory lemmas for degree_basic. -/ noncomputable theory namespace polynomial universes u variables {R : Type u} {a b : R} {m n : ℕ} variables [semiring R] {p q r : polynomial R} lemma monomial_one_eq_iff [nontrivial R] {i j : ℕ} : (monomial i 1 : polynomial R) = monomial j 1 ↔ i = j := by simp [monomial, monomial_fun, finsupp.single_eq_single_iff] instance [nontrivial R] : infinite (polynomial R) := infinite.of_injective (λ i, monomial i 1) $ λ m n h, by simpa [monomial_one_eq_iff] using h lemma card_support_le_one_iff_monomial {f : polynomial R} : finset.card f.support ≤ 1 ↔ ∃ n a, f = monomial n a := begin split, { assume H, rw finset.card_le_one_iff_subset_singleton at H, rcases H with ⟨n, hn⟩, refine ⟨n, f.coeff n, _⟩, ext i, by_cases hi : i = n, { simp [hi, coeff_monomial] }, { have : f.coeff i = 0, { rw ← not_mem_support_iff, exact λ hi', hi (finset.mem_singleton.1 (hn hi')) }, simp [this, ne.symm hi, coeff_monomial] } }, { rintros ⟨n, a, rfl⟩, rw ← finset.card_singleton n, apply finset.card_le_of_subset, exact support_monomial' _ _ } end lemma ring_hom_ext {S} [semiring S] {f g : polynomial R →+* S} (h₁ : ∀ a, f (C a) = g (C a)) (h₂ : f X = g X) : f = g := begin set f' := f.comp (to_finsupp_iso R).symm.to_ring_hom with hf', set g' := g.comp (to_finsupp_iso R).symm.to_ring_hom with hg', have A : f' = g', { ext, { simp [h₁, ring_equiv.to_ring_hom_eq_coe] }, { simpa [ring_equiv.to_ring_hom_eq_coe] using h₂, } }, have B : f = f'.comp (to_finsupp_iso R), by { rw [hf', ring_hom.comp_assoc], ext x, simp only [ring_equiv.to_ring_hom_eq_coe, ring_equiv.symm_apply_apply, function.comp_app, ring_hom.coe_comp, ring_equiv.coe_to_ring_hom] }, have C : g = g'.comp (to_finsupp_iso R), by { rw [hg', ring_hom.comp_assoc], ext x, simp only [ring_equiv.to_ring_hom_eq_coe, ring_equiv.symm_apply_apply, function.comp_app, ring_hom.coe_comp, ring_equiv.coe_to_ring_hom] }, rw [B, C, A] end @[ext] lemma ring_hom_ext' {S} [semiring S] {f g : polynomial R →+* S} (h₁ : f.comp C = g.comp C) (h₂ : f X = g X) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) h₂ end polynomial
28128fc18ce50cd91116c41834bd02be322b9c9e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/focus.lean
2032cfa07daa76f9d8c6a162292e84318de7776d
[ "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
338
lean
open nat example (n m : ℕ) : n + m = m + n := begin induction m with m IHm, focus { induction n with n IHn, focus { reflexivity }, focus { exact congr_arg succ IHn }}, focus { apply eq.trans (congr_arg succ IHm), clear IHm, induction n with n IHn, focus { reflexivity }, focus { exact congr_arg succ IHn }} end
fe69a10e9bf3fc3e8a9008a9bebd7dbe80b0fb20
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/676.lean
d3e8b2c3fcd1e4ea68875bcbf25d30776dfe2b71
[ "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
185
lean
import data.nat open nat inductive foo : Prop := mk : ∀ {a : nat}, a > 0 → foo example (b : nat) (h : b > 1) : foo := begin fconstructor, exact b, exact lt_of_succ_lt h end
beba37c3979d187c61e261e230fe01a1258b5b5f
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/tools/super/splitting.lean
ccca05ada8f6976cac3afddeca77636a8192a39d
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
2,716
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 .prover_state open monad expr list tactic namespace super private meta def find_components : list expr → list (list (expr × ℕ)) → list (list (expr × ℕ)) | (e::es) comps := let (contain_e, do_not_contain_e) := partition (λc : list (expr × ℕ), c^.exists_ $ λf, (abstract_local f.1 e^.local_uniq_name)^.has_var) comps in find_components es $ list.join contain_e :: do_not_contain_e | _ comps := comps meta def get_components (hs : list expr) : list (list expr) := (find_components hs (hs^.zip_with_index^.for $ λh, [h]))^.for $ λc, (sort_on (λh : expr × ℕ, h.2) c)^.for $ λh, h.1 meta def extract_assertions : clause → prover (clause × list expr) | c := if c^.num_lits = 0 then return (c, []) else if c^.num_quants ≠ 0 then do qf ← ♯ c^.open_constn c^.num_quants, qf_wo_as ← extract_assertions qf.1, return (qf_wo_as.1^.close_constn qf.2, qf_wo_as.2) else do hd ← return $ c^.get_lit 0, hyp_opt ← get_sat_hyp_core hd^.formula hd^.is_neg, match hyp_opt with | some h := do wo_as ← extract_assertions (c^.inst h), return (wo_as.1, h :: wo_as.2) | _ := do op ← ♯c^.open_const, op_wo_as ← extract_assertions op.1, return (op_wo_as.1^.close_const op.2, op_wo_as.2) end meta def mk_splitting_clause' (empty_clause : clause) : list (list expr) → tactic (list expr × expr) | [] := return ([], empty_clause^.proof) | ([p] :: comps) := do p' ← mk_splitting_clause' comps, return (p::p'.1, p'.2) | (comp :: comps) := do (hs, p') ← mk_splitting_clause' comps, hnc ← mk_local_def `hnc (imp (pis comp empty_clause^.local_false) empty_clause^.local_false), p'' ← return $ app hnc (lambdas comp p'), return (hnc::hs, p'') meta def mk_splitting_clause (empty_clause : clause) (comps : list (list expr)) : tactic clause := do (hs, p) ← mk_splitting_clause' empty_clause comps, return $ { empty_clause with proof := p }^.close_constn hs @[super.inf] meta def splitting_inf : inf_decl := inf_decl.mk 30 $ take given, do lf ← flip monad.lift state_t.read $ λst, st^.local_false, op ← ♯ given^.c^.open_constn given^.c^.num_binders, if list.bor (given^.c^.get_lits^.for $ λl, (is_local_not lf l^.formula)^.is_some) then return () else let comps := get_components op.2 in if comps^.length < 2 then return () else do splitting_clause ← ♯ mk_splitting_clause op.1 comps, ass ← collect_ass_hyps splitting_clause, add_sat_clause (splitting_clause^.close_constn ass) given^.sc^.sched_default, remove_redundant given^.id [] end super
b8a87543d66abec648a2e28d99f030a894104f92
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/specific_limits.lean
e2a762dad8f655113d5e2b50a381fedcac150099
[ "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
41,798
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.geom_sum import analysis.asymptotics.asymptotics import order.filter.archimedean import order.iterate import topology.instances.ennreal /-! # A collection of specific limit computations -/ noncomputable theory open classical set function filter finset metric asymptotics open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := nat.sub_add_cancel (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h) lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top := (tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := h₁.eq_or_lt.elim (assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds]) (assume : 0 < r, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂), this.congr (λ n, by simp)) lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝[Ioi 0] 0) := tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂, tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩ lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := have H : 0 < r₂ := h₁.trans_lt h₂, is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $ (tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr (λ n, div_pow _ _ _) lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) : is_O (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O) lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : abs r₁ < abs r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := begin refine (is_o.of_norm_left _).of_norm_right, exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂) end /-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`. * 0: $f n = o(a ^ n)$ for some $-R < a < R$; * 1: $f n = o(a ^ n)$ for some $0 < a < R$; * 2: $f n = O(a ^ n)$ for some $-R < a < R$; * 3: $f n = O(a ^ n)$ for some $0 < a < R$; * 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$ for all `n`; * 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`; * 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`; * 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`. NB: For backwards compatibility, if you add more items to the list, please append them at the end of the list. -/ lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) : tfae [∃ a ∈ Ioo (-R) R, is_o f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_o f (pow a) at_top, ∃ a ∈ Ioo (-R) R, is_O f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_O f (pow a) at_top, ∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, abs (f n) ≤ C * a ^ n, ∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n, ∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n] := begin have A : Ico 0 R ⊆ Ioo (-R) R, from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩, have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A, -- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1 tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, tfae_have : 3 → 2, { rintro ⟨a, ha, H⟩, rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩, exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩, H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ }, tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, -- Add 5 and 6 using 4 → 6 → 5 → 3 tfae_have : 4 → 6, { rintro ⟨a, ha, H⟩, rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩, refine ⟨a, ha, C, hC₀, λ n, _⟩, simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne') }, tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩, tfae_have : 5 → 3, { rintro ⟨a, ha, C, h₀, H⟩, rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩, { obtain rfl : f = 0, by { ext n, simpa using H n }, simp only [lt_irrefl, false_or] at h₀, exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ }, exact ⟨a, A ⟨ha₀, ha⟩, is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ }, -- Add 7 and 8 using 2 → 8 → 7 → 3 tfae_have : 2 → 8, { rintro ⟨a, ha, H⟩, refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩, rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn }, tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩, tfae_have : 7 → 3, { rintro ⟨a, ha, H⟩, have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans), refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩, simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] }, tfae_finish end lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [pseudo_metric_space α] {r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) : (𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) := metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0, (exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩ lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, c * u k < u (k + 1)) : c ^ n * u 0 < u n := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn _ _ h, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) : c ^ n * u 0 ≤ u n := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl] lemma lt_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, u (k + 1) < c * u k) : u n < c ^ n * u 0 := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_lt_of_le hn _ h _, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma le_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, u (k + 1) ≤ c * u k) : u n ≤ (c ^ n) * u 0 := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ h _; simp [pow_succ, mul_assoc, le_refl] /-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_const_pow_of_one_lt {R : Type*} [normed_ring R] (k : ℕ) {r : ℝ} (hr : 1 < r) : is_o (λ n, n ^ k : ℕ → R) (λ n, r ^ n) at_top := begin have : tendsto (λ x : ℝ, x ^ k) (𝓝[Ioi 1] 1) (𝓝 1), from ((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left, obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ := ((this.eventually (gt_mem_nhds hr)).and self_mem_nhds_within).exists, have h0 : 0 ≤ r' := zero_le_one.trans h1.le, suffices : is_O _ (λ n : ℕ, (r' ^ k) ^ n) at_top, from this.trans_is_o (is_o_pow_pow_of_lt_left (pow_nonneg h0 _) hr'), conv in ((r' ^ _) ^ _) { rw [← pow_mul, mul_comm, pow_mul] }, suffices : ∀ n : ℕ, ∥(n : R)∥ ≤ (r' - 1)⁻¹ * ∥(1 : R)∥ * ∥r' ^ n∥, from (is_O_of_le' _ this).pow _, intro n, rw mul_right_comm, refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), simpa [div_eq_inv_mul, real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1 end /-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/ lemma is_o_coe_const_pow_of_one_lt {R : Type*} [normed_ring R] {r : ℝ} (hr : 1 < r) : is_o (coe : ℕ → R) (λ n, r ^ n) at_top := by simpa only [pow_one] using is_o_pow_const_const_pow_of_one_lt 1 hr /-- If `∥r₁∥ < r₂`, then for any naturak `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [normed_ring R] (k : ℕ) {r₁ : R} {r₂ : ℝ} (h : ∥r₁∥ < r₂) : is_o (λ n, n ^ k * r₁ ^ n : ℕ → R) (λ n, r₂ ^ n) at_top := begin by_cases h0 : r₁ = 0, { refine (is_o_zero _ _).congr' (mem_at_top_sets.2 $ ⟨1, λ n hn, _⟩) eventually_eq.rfl, simp [zero_pow (zero_lt_one.trans_le hn), h0] }, rw [← ne.def, ← norm_pos_iff] at h0, have A : is_o (λ n, n ^ k : ℕ → R) (λ n, (r₂ / ∥r₁∥) ^ n) at_top, from is_o_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h), suffices : is_O (λ n, r₁ ^ n) (λ n, ∥r₁∥ ^ n) at_top, by simpa [div_mul_cancel _ (pow_pos h0 _).ne'] using A.mul_is_O this, exact is_O.of_bound 1 (by simpa using eventually_norm_pow_le r₁) end lemma tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) : tendsto (λ n, n ^ k / r ^ n : ℕ → ℝ) at_top (𝓝 0) := (is_o_pow_const_const_pow_of_one_lt k hr).tendsto_0 /-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/ lemma tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : abs r < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := begin by_cases h0 : r = 0, { exact tendsto_const_nhds.congr' (mem_at_top_sets.2 ⟨1, λ n hn, by simp [zero_lt_one.trans_le hn, h0]⟩) }, have hr' : 1 < (abs r)⁻¹, from one_lt_inv (abs_pos.2 h0) hr, rw tendsto_zero_iff_norm_tendsto_zero, simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr' end /-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c) (hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top := tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $ (tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀ lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0∞} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_sum r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum_eq, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : ∑'n:ℕ, ((1:ℝ)/2) ^ n = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : ∑' n:ℕ, (a / 2) / 2^n = a := (has_sum_geometric_two' a).tsum_eq /-- **Sum of a Geometric Series** -/ lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ @[simp] lemma ennreal.tsum_geometric (r : ℝ≥0∞) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_comm_semiring.pow_le_pow_of_le_left hr, calc (n:ℝ≥0∞) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) } end variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_sum ξ n) := rfl, rw [has_sum_iff_tendsto_nat_of_summable_norm, B], { simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A }, { simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : ∑'n:ℕ, ξ ^ n = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h /-- A geometric series in a normed field is summable iff the norm of the common ratio is less than one. -/ @[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 := begin refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩, obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ := (h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists, simp only [normed_field.norm_pow, dist_zero_right] at hk, rw [← one_pow k] at hk, exact lt_of_pow_lt_pow _ zero_le_one hk end end geometric section mul_geometric lemma summable_norm_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n : ℕ, ∥(n ^ k * r ^ n : R)∥) := begin rcases exists_between hr with ⟨r', hrr', h⟩, exact summable_of_is_O_nat _ (summable_geometric_of_lt_1 ((norm_nonneg _).trans hrr'.le) h) (is_o_pow_const_mul_const_pow_const_pow_of_norm_lt _ hrr').is_O.norm_left end lemma summable_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] [complete_space R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n, n ^ k * r ^ n : ℕ → R) := summable_of_summable_norm $ summable_norm_pow_mul_geometric_of_norm_lt_1 _ hr /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `has_sum` version. -/ lemma has_sum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : has_sum (λ n, n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := begin have A : summable (λ n, n * r ^ n : ℕ → 𝕜), by simpa using summable_pow_mul_geometric_of_norm_lt_1 1 hr, have B : has_sum (pow r : ℕ → 𝕜) (1 - r)⁻¹, from has_sum_geometric_of_norm_lt_1 hr, refine A.has_sum_iff.2 _, have hr' : r ≠ 1, by { rintro rfl, simpa [lt_irrefl] using hr }, set s : 𝕜 := ∑' n : ℕ, n * r ^ n, calc s = (1 - r) * s / (1 - r) : (mul_div_cancel_left _ (sub_ne_zero.2 hr'.symm)).symm ... = (s - r * s) / (1 - r) : by rw [sub_mul, one_mul] ... = ((0 : ℕ) * r ^ 0 + (∑' n : ℕ, (n + 1) * r ^ (n + 1)) - r * s) / (1 - r) : by { congr, exact tsum_eq_zero_add A } ... = (r * (∑' n : ℕ, (n + 1) * r ^ n) - r * s) / (1 - r) : by simp [pow_succ, mul_left_comm _ r, tsum_mul_left] ... = r / (1 - r) ^ 2 : by simp [add_mul, tsum_add A B.summable, mul_add, B.tsum_eq, ← div_eq_mul_inv, sq, div_div_eq_div_mul] end /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/ lemma tsum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = (r / (1 - r) ^ 2) := (has_sum_coe_mul_geometric_of_norm_lt_1 hr).tsum_eq end mul_geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [pseudo_emetric_space α] (r C : ℝ≥0∞) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, div_eq_mul_inv, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [pseudo_emetric_space α] (C : ℝ≥0∞) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at *, rw [mul_assoc, mul_comm], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, div_eq_mul_inv, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [pseudo_metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩, { simp [has_sum_zero] }, { refine has_sum.mul_left C _, simpa using has_sum_geometric_of_lt_1 r₀ hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, ← div_div_eq_div_mul], symmetry, exact ((has_sum_geometric_two' C).div_const _).tsum_eq end end le_geometric section summable_le_geometric variables [semi_normed_group α] {r C : ℝ} {f : ℕ → α} lemma semi_normed_group.cauchy_seq_of_le_geometric {C : ℝ} {r : ℝ} (hr : r < 1) {u : ℕ → α} (h : ∀ n, ∥u n - u (n + 1)∥ ≤ C*r^n) : cauchy_seq u := cauchy_seq_of_le_geometric r C hr (by simpa [dist_eq_norm] using h) lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg, neg_sub, add_sub_cancel'], exact hf n, end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end @[simp] lemma dist_partial_sum (u : ℕ → α) (n : ℕ) : dist (∑ k in range (n + 1), u k) (∑ k in range n, u k) = ∥u n∥ := by simp [dist_eq_norm, sum_range_succ] @[simp] lemma dist_partial_sum' (u : ℕ → α) (n : ℕ) : dist (∑ k in range n, u k) (∑ k in range (n+1), u k) = ∥u n∥ := by simp [dist_eq_norm', sum_range_succ] lemma cauchy_series_of_le_geometric {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range n, u k) := cauchy_seq_of_le_geometric r C hr (by simp [h]) lemma normed_group.cauchy_series_of_le_geometric' {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin by_cases hC : C = 0, { subst hC, simp at h, exact cauchy_seq_of_le_geometric 0 0 zero_lt_one (by simp [h]) }, have : 0 ≤ C, { simpa using (norm_nonneg _).trans (h 0) }, replace hC : 0 < C, from (ne.symm hC).le_iff_lt.mp this, have : 0 ≤ r, { have := (norm_nonneg _).trans (h 1), rw pow_one at this, exact (zero_le_mul_left hC).mp this }, simp_rw finset.sum_range_succ_comm, have : cauchy_seq u, { apply tendsto.cauchy_seq, apply squeeze_zero_norm h, rw show 0 = C*0, by simp, exact tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 this hr) }, exact this.add (cauchy_series_of_le_geometric hr h), end lemma normed_group.cauchy_series_of_le_geometric'' {C : ℝ} {u : ℕ → α} {N : ℕ} {r : ℝ} (hr₀ : 0 < r) (hr₁ : r < 1) (h : ∀ n ≥ N, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin set v : ℕ → α := λ n, if n < N then 0 else u n, have hC : 0 ≤ C, from (zero_le_mul_right $ pow_pos hr₀ N).mp ((norm_nonneg _).trans $ h N $ le_refl N), have : ∀ n ≥ N, u n = v n, { intros n hn, simp [v, hn, if_neg (not_lt.mpr hn)] }, refine cauchy_seq_sum_of_eventually_eq this (normed_group.cauchy_series_of_le_geometric' hr₁ _), { exact C }, intro n, dsimp [v], split_ifs with H H, { rw norm_zero, exact mul_nonneg hC (pow_nonneg hr₀.le _) }, { push_neg at H, exact h _ H } end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥∑' n:ℕ, x ^ n∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥∑' b : ℕ, (λ n, x ^ (n + 1)) b∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' i:ℕ, x ^ i) * (1 - x) = 1 := begin have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, geom_sum_def, finset.sum_mul], end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * ∑' i:ℕ, x ^ i = 1 := begin have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, geom_sum_def, finset.mul_sum] end end normed_ring_geometric /-! ### Summability tests based on comparison with geometric series -/ lemma summable_of_ratio_norm_eventually_le {α : Type*} [semi_normed_group α] [complete_space α] {f : ℕ → α} {r : ℝ} (hr₁ : r < 1) (h : ∀ᶠ n in at_top, ∥f (n+1)∥ ≤ r * ∥f n∥) : summable f := begin by_cases hr₀ : 0 ≤ r, { rw eventually_at_top at h, rcases h with ⟨N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine summable_of_norm_bounded (λ n, ∥f N∥ * r^n) (summable.mul_left _ $ summable_geometric_of_lt_1 hr₀ hr₁) (λ n, _), conv_rhs {rw [mul_comm, ← zero_add N]}, refine le_geom hr₀ n (λ i _, _), convert hN (i + N) (N.le_add_left i) using 3, ac_refl }, { push_neg at hr₀, refine summable_of_norm_bounded_eventually 0 summable_zero _, rw nat.cofinite_eq_at_top, filter_upwards [h], intros n hn, by_contra h, push_neg at h, exact not_lt.mpr (norm_nonneg _) (lt_of_le_of_lt hn $ mul_neg_of_neg_of_pos hr₀ h) } end lemma summable_of_ratio_test_tendsto_lt_one {α : Type*} [normed_group α] [complete_space α] {f : ℕ → α} {l : ℝ} (hl₁ : l < 1) (hf : ∀ᶠ n in at_top, f n ≠ 0) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : summable f := begin rcases exists_between hl₁ with ⟨r, hr₀, hr₁⟩, refine summable_of_ratio_norm_eventually_le hr₁ _, filter_upwards [eventually_le_of_tendsto_lt hr₀ h, hf], intros n h₀ h₁, rwa ← div_le_iff (norm_pos_iff.mpr h₁) end lemma not_summable_of_ratio_norm_eventually_ge {α : Type*} [semi_normed_group α] {f : ℕ → α} {r : ℝ} (hr : 1 < r) (hf : ∃ᶠ n in at_top, ∥f n∥ ≠ 0) (h : ∀ᶠ n in at_top, r * ∥f n∥ ≤ ∥f (n+1)∥) : ¬ summable f := begin rw eventually_at_top at h, rcases h with ⟨N₀, hN₀⟩, rw frequently_at_top at hf, rcases hf N₀ with ⟨N, hNN₀ : N₀ ≤ N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine mt summable.tendsto_at_top_zero (λ h', not_tendsto_at_top_of_tendsto_nhds (tendsto_norm_zero.comp h') _), convert tendsto_at_top_of_geom_le _ hr _, { refine lt_of_le_of_ne (norm_nonneg _) _, intro h'', specialize hN₀ N hNN₀, simp only [comp_app, zero_add] at h'', exact hN h''.symm }, { intro i, dsimp only [comp_app], convert (hN₀ (i + N) (hNN₀.trans (N.le_add_left i))) using 3, ac_refl } end lemma not_summable_of_ratio_test_tendsto_gt_one {α : Type*} [semi_normed_group α] {f : ℕ → α} {l : ℝ} (hl : 1 < l) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : ¬ summable f := begin have key : ∀ᶠ n in at_top, ∥f n∥ ≠ 0, { filter_upwards [eventually_ge_of_tendsto_gt hl h], intros n hn hc, rw [hc, div_zero] at hn, linarith }, rcases exists_between hl with ⟨r, hr₀, hr₁⟩, refine not_summable_of_ratio_norm_eventually_ge hr₀ key.frequently _, filter_upwards [eventually_ge_of_tendsto_gt hr₁ h, key], intros n h₀ h₁, rwa ← le_div_iff (lt_of_le_of_ne (norm_nonneg _) h₁.symm) end /-- A series whose terms are bounded by the terms of a converging geometric series converges. -/ lemma summable_one_div_pow_of_le {m : ℝ} {f : ℕ → ℕ} (hm : 1 < m) (fi : ∀ i, i ≤ f i) : summable (λ i, 1 / m ^ f i) := begin refine summable_of_nonneg_of_le (λ a, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) (λ a, _) (summable_geometric_of_lt_1 (one_div_nonneg.mpr (zero_le_one.trans hm.le)) ((one_div_lt (zero_lt_one.trans hm) zero_lt_one).mpr (one_div_one.le.trans_lt hm))), rw [div_pow, one_pow], refine (one_div_le_one_div _ _).mpr (pow_le_pow hm.le (fi a)); exact pow_pos (zero_lt_one.trans hm) _ end /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end namespace nnreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := exists_between hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0∞} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∑' i, (ε' i : ℝ≥0∞) < ε := begin rcases exists_between hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end theorem exists_pos_sum_of_encodable' {ε : ℝ≥0∞} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0∞, (∀ i, 0 < ε' i) ∧ (∑' i, ε' i) < ε := let ⟨δ, δpos, hδ⟩ := exists_pos_sum_of_encodable hε ι in ⟨λ i, δ i, λ i, ennreal.coe_pos.2 (δpos i), hδ⟩ end ennreal /-! ### Factorial -/ lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top := tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩) lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_const_div_at_top_nhds_0_nat 1) (eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le) (pow_nonneg (by exact_mod_cast n.zero_le) _)) begin refine (eventually_gt_at_top 0).mono (λ n hn, _), rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩, rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib, finset.prod_range_succ'], simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one], refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _); intros x hx; rw finset.mem_range at hx, { refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith }, { refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith } end
62d9b849b94f0d0c5aa988aa420281d300658594
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/free_abelian_group.lean
5718d236f50cffccdbec9ad5863ebe5c698e4113
[ "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
19,479
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.pi import group_theory.free_group import group_theory.abelianization import algebra.module.basic -- we use the ℤ-module structure on an add_comm_group in punit_equiv /-! # Free abelian groups The free abelian group on a type `α`, defined as the abelianisation of the free group on `α`. The free abelian group on `α` can be abstractly defined as the left adjoint of the forgetful functor from abelian groups to types. Alternatively, one could define it as the functions `α → ℤ` which send all but finitely many `(a : α)` to `0`, under pointwise addition. In this file, it is defined as the abelianisation of the free group on `α`. All the constructions and theorems required to show the adjointness of the construction and the forgetful functor are proved in this file, but the category-theoretic adjunction statement is in `algebra.category.Group.adjunctions` . ## Main definitions Here we use the following variables: `(α β : Type*) (A : Type*) [add_comm_group A]` * `free_abelian_group α` : the free abelian group on a type `α`. As an abelian group it is `α →₀ ℤ`, the functions from `α` to `ℤ` such that all but finitely many elements get mapped to zero, however this is not how it is implemented. * `lift f : free_abelian_group α →+ A` : the group homomorphism induced by the map `f : α → A`. * `map (f : α → β) : free_abelian_group α →+ free_abelian_group β` : functoriality of `free_abelian_group` * `instance [monoid α] : semigroup (free_abelian_group α)` * `instance [comm_monoid α] : comm_ring (free_abelian_group α)` It has been suggested that we would be better off refactoring this file and using `finsupp` instead. ## Implementation issues The definition is `def free_abelian_group : Type u := additive $ abelianization $ free_group α` Chris Hughes has suggested that this all be rewritten in terms of `finsupp`. Johan Commelin has written all the API relating the definition to `finsupp` in the lean-liquid repo. The lemmas `map_pure`, `map_of`, `map_zero`, `map_add`, `map_neg` and `map_sub` are proved about the `functor.map` `<$>` construction, and need `α` and `β` to be in the same universe. But `free_abelian_group.map (f : α → β)` is defined to be the `add_group` homomorphism `free_abelian_group α →+ free_abelian_group β` (with `α` and `β` now allowed to be in different universes), so `(map f).map_add` etc can be used to prove that `free_abelian_group.map` preserves addition. The functions `map_id`, `map_id_apply`, `map_comp`, `map_comp_apply` and `map_of_apply` are about `free_abelian_group.map`. -/ universes u v variables (α : Type u) /-- The free abelian group on a type. -/ def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ instance : inhabited (free_abelian_group α) := ⟨0⟩ variable {α} namespace free_abelian_group /-- The canonical map from α to `free_abelian_group α` -/ def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x /-- The map `free_abelian_group α →+ A` induced by a map of types `α → A`. -/ def lift {β : Type v} [add_comm_group β] : (α → β) ≃ (free_abelian_group α →+ β) := (@free_group.lift _ (multiplicative β) _).trans $ (@abelianization.lift _ _ (multiplicative β) _).trans monoid_hom.to_additive namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group @[simp] protected lemma of (x : α) : lift f (of x) = f x := begin convert @abelianization.lift.of (free_group α) _ (multiplicative β) _ _ _, convert free_group.lift.of.symm end protected theorem unique (g : free_abelian_group α →+ β) (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := add_monoid_hom.congr_fun ((lift.symm_apply_eq).mp (funext hg : g ∘ of = f)) _ /-- See note [partially-applied ext lemmas]. -/ @[ext] protected theorem ext (g h : free_abelian_group α →+ β) (H : ∀ x, g (of x) = h (of x)) : g = h := lift.symm.injective $ funext H lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β →+ γ) : g (lift f a) = lift (g ∘ f) a := begin suffices : (g.comp (lift f)) a = lift (g ∘ f) a, exact this, apply @lift.unique, assume a, show g ((lift f) (of a)) = g (f a), simp only [(∘), lift.of], end end lift section open_locale classical lemma of_injective : function.injective (of : α → free_abelian_group α) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_abelian_group α →+ ℤ := lift (λ z, if x = z then (1 : ℤ) else 0) in have hfx1 : f (of x) = 1, from (lift.of _ _).trans $ if_pos rfl, have hfy1 : f (of y) = 1, from hoxy ▸ hfx1, have hfy0 : f (of y) = 0, from (lift.of _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 end local attribute [instance] quotient_group.left_rel @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on' z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {α β} [add_comm_group β] (a : free_abelian_group α) (f g : α → β) : lift (f + g) a = lift f a + lift g a := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [(lift _).map_zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [map_neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [(lift _).map_add, hx, hy, add_add_add_comm] } end /-- If `g : free_abelian_group X` and `A` is an abelian group then `lift_add_group_hom g` is the additive group homomorphism sending a function `X → A` to the term of type `A` corresponding to the evaluation of the induced map `free_abelian_group X → A` at `g`. -/ @[simps] def lift_add_group_hom {α} (β) [add_comm_group β] (a : free_abelian_group α) : (α → β) →+ β := add_monoid_hom.mk' (λ f, lift f a) (lift.add' a) lemma lift_neg' {β} [add_comm_group β] (f : α → β) : lift (-f) = -lift f := add_monoid_hom.ext $ λ _, (lift_add_group_hom _ _ : (α → β) →+ β).map_neg _ section monad variables {β : Type u} instance : monad free_abelian_group.{u} := { pure := λ α, of, bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ pure x) (Cn : ∀ x, C (pure x) → C (-pure x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_abelian_group α) = pure (f x) := rfl @[simp] protected lemma map_zero (f : α → β) : f <$> (0 : free_abelian_group α) = 0 := (lift (of ∘ f)).map_zero @[simp] protected lemma map_add (f : α → β) (x y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y := (lift _).map_add _ _ @[simp] protected lemma map_neg (f : α → β) (x : free_abelian_group α) : f <$> (-x) = -(f <$> x) := map_neg (lift $ of ∘ f) _ @[simp] protected lemma map_sub (f : α → β) (x y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y := map_sub (lift $ of ∘ f) _ _ @[simp] lemma map_of (f : α → β) (y : α) : f <$> of y = of (f y) := rfl @[simp] lemma pure_bind (f : α → free_abelian_group β) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : α → free_abelian_group β) : 0 >>= f = 0 := (lift f).map_zero @[simp] lemma add_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) := (lift _).map_add _ _ @[simp] lemma neg_bind (f : α → free_abelian_group β) (x : free_abelian_group α) : -x >>= f = -(x >>= f) := map_neg (lift f) _ @[simp] lemma sub_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) := map_sub (lift f) _ _ @[simp] lemma pure_seq (f : α → β) (x : free_abelian_group α) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group α) : (0 : free_abelian_group (α → β)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (α → β)) (x : free_abelian_group α) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ /-- If `f : free_abelian_group (α → β)`, then `f <*>` is an additive morphism `free_abelian_group α →+ free_abelian_group β`. -/ def seq_add_group_hom (f : free_abelian_group (α → β)) : free_abelian_group α →+ free_abelian_group β := add_monoid_hom.mk' ((<*>) f) (λ x y, show lift (<$> (x+y)) _ = _, by { simp only [free_abelian_group.map_add], exact lift.add' f _ _, }) @[simp] lemma seq_zero (f : free_abelian_group (α → β)) : f <*> 0 = 0 := (seq_add_group_hom f).map_zero @[simp] lemma seq_add (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x + y) = (f <*> x) + (f <*> y) := (seq_add_group_hom f).map_add x y @[simp] lemma seq_neg (f : free_abelian_group (α → β)) (x : free_abelian_group α) : f <*> (-x) = -(f <*> x) := (seq_add_group_hom f).map_neg x @[simp] lemma seq_sub (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x - y) = (f <*> x) - (f <*> y) := (seq_add_group_hom f).map_sub x y instance : is_lawful_monad free_abelian_group.{u} := { id_map := λ α x, free_abelian_group.induction_on' x (free_abelian_group.map_zero id) (map_pure id) (λ x ih, by rw [free_abelian_group.map_neg, ih]) (λ x y ihx ihy, by rw [free_abelian_group.map_add, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw neg_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := λ α β x y, free_abelian_group.induction_on' x (by rw [free_abelian_group.map_zero, zero_seq, seq_zero]) (λ p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [free_abelian_group.map_zero, free_abelian_group.map_zero, zero_seq]) (λ q, by rw [map_pure, map_pure, pure_seq, map_pure]) (λ q ih, by rw [free_abelian_group.map_neg, free_abelian_group.map_neg, neg_seq, ih]) (λ y₁ y₂ ih1 ih2, by rw [free_abelian_group.map_add, free_abelian_group.map_add, add_seq, ih1, ih2])) (λ p ih, by rw [free_abelian_group.map_neg, neg_seq, seq_neg, ih]) (λ x₁ x₂ ih1 ih2, by rw [free_abelian_group.map_add, add_seq, seq_add, ih1, ih2]) } end monad universe w variables {β : Type v} {γ : Type w} /-- The additive group homomorphism `free_abelian_group α →+ free_abelian_group β` induced from a map `α → β` -/ def map (f : α → β) : free_abelian_group α →+ free_abelian_group β := lift (of ∘ f) lemma lift_comp {α} {β} {γ} [add_comm_group γ] (f : α → β) (g : β → γ) (x : free_abelian_group α) : lift (g ∘ f) x = lift g (map f x) := begin apply free_abelian_group.induction_on x, { exact add_monoid_hom.map_zero _ }, { intro y, refl }, { intros x h, simp only [h, add_monoid_hom.map_neg] }, { intros x y h₁ h₂, simp only [h₁, h₂, add_monoid_hom.map_add] } end lemma map_id : map id = add_monoid_hom.id (free_abelian_group α) := eq.symm $ lift.ext _ _ $ λ x, lift.unique of (add_monoid_hom.id _) $ λ y, add_monoid_hom.id_apply _ _ lemma map_id_apply (x : free_abelian_group α) : map id x = x := by {rw map_id, refl } lemma map_comp {f : α → β} {g : β → γ} : map (g ∘ f) = (map g).comp (map f) := eq.symm $ lift.ext _ _ $ λ x, eq.symm $ lift_comp _ _ _ lemma map_comp_apply {f : α → β} {g : β → γ} (x : free_abelian_group α) : map (g ∘ f) x = (map g) ((map f) x) := by { rw map_comp, refl } -- version of map_of which uses `map` @[simp] lemma map_of_apply {f : α → β} (a : α) : map f (of a) = of (f a) := rfl variable (α) section has_mul variables [has_mul α] instance : has_mul (free_abelian_group α) := ⟨λ x, lift $ λ x₂, lift (λ x₁, of $ x₁ * x₂) x⟩ variable {α} lemma mul_def (x y : free_abelian_group α) : x * y = lift (λ x₂, lift (λ x₁, of (x₁ * x₂)) x) y := rfl @[simp] lemma of_mul_of (x y : α) : of x * of y = of (x * y) := rfl lemma of_mul (x y : α) : of (x * y) = of x * of y := rfl instance : distrib (free_abelian_group α) := { add := (+), left_distrib := λ x y z, (lift _).map_add _ _, right_distrib := λ x y z, by simp only [(*), map_add, ←pi.add_def, lift.add'], ..free_abelian_group.has_mul _ } instance : non_unital_non_assoc_ring (free_abelian_group α) := { zero_mul := λ a, by { have h : 0 * a + 0 * a = 0 * a, by simp [←add_mul], simpa using h }, mul_zero := λ a, rfl, ..free_abelian_group.distrib, ..free_abelian_group.add_comm_group _ } end has_mul instance [has_one α] : has_one (free_abelian_group α) := ⟨of 1⟩ instance [semigroup α] : non_unital_ring (free_abelian_group α) := { mul := (*), mul_assoc := λ x y z, begin refine free_abelian_group.induction_on z (by simp) (λ L3, _) (λ L3 ih, _) (λ z₁ z₂ ih₁ ih₂, _), { refine free_abelian_group.induction_on y (by simp) (λ L2, _) (λ L2 ih, _) (λ y₁ y₂ ih₁ ih₂, _), { refine free_abelian_group.induction_on x (by simp) (λ L1, _) (λ L1 ih, _) (λ x₁ x₂ ih₁ ih₂, _), { rw [of_mul_of, of_mul_of, of_mul_of, of_mul_of, mul_assoc] }, { rw [neg_mul, neg_mul, neg_mul, ih] }, { rw [add_mul, add_mul, add_mul, ih₁, ih₂] } }, { rw [neg_mul, mul_neg, mul_neg, neg_mul, ih] }, { rw [add_mul, mul_add, mul_add, add_mul, ih₁, ih₂] } }, { rw [mul_neg, mul_neg, mul_neg, ih] }, { rw [mul_add, mul_add, mul_add, ih₁, ih₂] } end, .. free_abelian_group.non_unital_non_assoc_ring } section monoid variables {R : Type*} [monoid α] [ring R] instance : ring (free_abelian_group α) := { mul := (*), mul_one := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl (λ L, _) (λ L ih, _) (λ x1 x2 ih1 ih2, _), { erw [lift.of], congr' 1, exact mul_one L }, { rw [map_neg, ih] }, { rw [map_add, ih1, ih2] } end, one_mul := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [map_add, ih1, ih2] } end, .. free_abelian_group.non_unital_ring _, ..free_abelian_group.has_one _ } variable {α} /-- `free_abelian_group.of` is a `monoid_hom` when `α` is a `monoid`. -/ def of_mul_hom : α →* free_abelian_group α := { to_fun := of, map_one' := rfl, map_mul' := of_mul } @[simp] lemma of_mul_hom_coe : (of_mul_hom : α → free_abelian_group α) = of := rfl /-- If `f` preserves multiplication, then so does `lift f`. -/ def lift_monoid : (α →* R) ≃ (free_abelian_group α →+* R) := { to_fun := λ f, { to_fun := lift f, map_one' := (lift.of f _).trans f.map_one, map_mul' := λ x y, begin refine free_abelian_group.induction_on y (mul_zero _).symm (λ L2, _) (λ L2 ih, _) _, { refine free_abelian_group.induction_on x (zero_mul _).symm (λ L1, _) (λ L1 ih, _) _, { simp_rw [of_mul_of, lift.of], exact f.map_mul _ _ }, { simp_rw [neg_mul, map_neg, neg_mul], exact congr_arg has_neg.neg ih }, { intros x1 x2 ih1 ih2, simp only [add_mul, map_add, ih1, ih2] } }, { rw [mul_neg, map_neg, map_neg, mul_neg, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, map_add, map_add, mul_add, ih1, ih2] }, end, .. lift f }, inv_fun := λ F, monoid_hom.comp ↑F of_mul_hom, left_inv := λ f, monoid_hom.ext $ lift.of _, right_inv := λ F, ring_hom.coe_add_monoid_hom_injective $ lift.apply_symm_apply (↑F : free_abelian_group α →+ R) } @[simp] lemma lift_monoid_coe_add_monoid_hom (f : α →* R) : ↑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_coe (f : α →* R) : ⇑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_symm_coe (f : free_abelian_group α →+* R) : ⇑(lift_monoid.symm f) = lift.symm ↑f := rfl lemma one_def : (1 : free_abelian_group α) = of 1 := rfl lemma of_one : (of 1 : free_abelian_group α) = 1 := rfl end monoid instance [comm_monoid α] : comm_ring (free_abelian_group α) := { mul_comm := λ x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end, .. free_abelian_group.ring α } instance pempty_unique : unique (free_abelian_group pempty) := { default := 0, uniq := λ x, free_abelian_group.induction_on x rfl (λ x, pempty.elim x) (λ x, pempty.elim x) (by { rintros - - rfl rfl, simp }) } /-- The free abelian group on a type with one term is isomorphic to `ℤ`. -/ def punit_equiv (T : Type*) [unique T] : free_abelian_group T ≃+ ℤ := { to_fun := free_abelian_group.lift (λ _, (1 : ℤ)), inv_fun := λ n, n • of (inhabited.default), left_inv := λ z, free_abelian_group.induction_on z (by simp only [zero_smul, add_monoid_hom.map_zero]) (unique.forall_iff.2 $ by simp only [one_smul, lift.of]) (unique.forall_iff.2 $ by simp) (λ x y hx hy, by { simp only [add_monoid_hom.map_add, add_smul] at *, rw [hx, hy]}), right_inv := λ n, begin rw [add_monoid_hom.map_zsmul, lift.of], exact zsmul_int_one n end, map_add' := add_monoid_hom.map_add _ } /-- Isomorphic types have isomorphic free abelian groups. -/ def equiv_of_equiv {α β : Type*} (f : α ≃ β) : free_abelian_group α ≃+ free_abelian_group β := { to_fun := map f, inv_fun := map f.symm, left_inv := begin intros x, rw [← map_comp_apply, equiv.symm_comp_self, map_id], refl, end, right_inv := begin intros x, rw [← map_comp_apply, equiv.self_comp_symm, map_id], refl, end, map_add' := add_monoid_hom.map_add _ } end free_abelian_group
4b84a14914c1d19a741d2b18f3d327604038e142
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/instances/ennreal.lean
ce2e438aba1692b16880965d5ddb32dcf778c5a7
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
67,407
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.nnreal import topology.algebra.order.monotone_continuity import analysis.normed.group.basic /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : normal_space ℝ≥0∞ := normal_of_compact_t2 instance : second_countable_topology ℝ≥0∞ := order_iso_unit_interval_birational.to_homeomorph.embedding.second_countable_topology lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp continuous_real_to_nnreal lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞} (hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞) (hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) : f =ᶠ[l] g := begin filter_upwards [hfi, hgi, hfg] with _ hfx hgx _, rwa ← ennreal.to_real_eq_to_real hfx hgx, end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[>] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ⟨⊤, ennreal.coe_lt_top⟩ @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[>] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x := begin rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne', -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩, { rcases exists_between xs with ⟨b, ab, bx⟩, have xb_pos : 0 < x - b := tsub_pos_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le, refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rcases exists_between xs with ⟨b, xb, ba⟩, have bx_pos : 0 < b - x := tsub_pos_iff_lt.2 xb, have xbx : x + (b - x) = b := add_tsub_cancel_of_le xb.le, refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_nhds_zero {f : filter α} {u : α → ℝ≥0∞} : tendsto u f (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in f, u x ≤ ε := begin rw ennreal.tendsto_nhds zero_ne_top, simp only [true_and, zero_tsub, zero_le, zero_add, set.mem_Icc], end protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_tsub, zero_le _, true_and], }, { exact hβ, }, end lemma tendsto_sub {a b : ℝ≥0∞} (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) (𝓝 (a, b)) (𝓝 (a - b)) := begin cases a; cases b, { simp only [eq_self_iff_true, not_true, ne.def, none_eq_top, or_self] at h, contradiction }, { simp only [some_eq_coe, with_top.top_sub_coe, none_eq_top], apply tendsto_nhds_top_iff_nnreal.2 (λ n, _), rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, ((n + (b + 1)) : ℝ≥0∞) < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ z, z < b + 1, Iio_mem_nhds ((ennreal.lt_add_right coe_ne_top one_ne_zero)), λ x hx y hy, _⟩, dsimp, rw lt_tsub_iff_right, have : ((n : ℝ≥0∞) + y) + (b + 1) < x + (b + 1) := calc ((n : ℝ≥0∞) + y) + (b + 1) = ((n : ℝ≥0∞) + (b + 1)) + y : by abel ... < x + (b + 1) : ennreal.add_lt_add hx hy, exact lt_of_add_lt_add_right this }, { simp only [some_eq_coe, with_top.sub_top, none_eq_top], suffices H : ∀ᶠ (p : ℝ≥0∞ × ℝ≥0∞) in 𝓝 (a, ∞), 0 = p.1 - p.2, from tendsto_const_nhds.congr' H, rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, z < a + 1, Iio_mem_nhds (ennreal.lt_add_right coe_ne_top one_ne_zero), λ z, (a : ℝ≥0∞) + 1 < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ x hx y hy, _⟩, rw eq_comm, simp only [tsub_eq_zero_iff_le, (has_lt.lt.trans hx hy).le], }, { simp only [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, function.comp, ← ennreal.coe_sub, tendsto_coe], exact continuous.tendsto (by continuity) _ } end protected lemma tendsto.sub {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (hmb : tendsto mb f (𝓝 b)) (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ a, ma a - mb a) f (𝓝 (a - b)) := show tendsto ((λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a - b)), from tendsto.comp (ennreal.tendsto_sub h) (hma.prod_mk_nhds hmb) protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, have : ∀ᶠ c : ℝ≥0∞ × ℝ≥0∞ in 𝓝 (∞, b), ↑n / ↑ε < c.1 ∧ ↑ε < c.2, from (lt_mem_nhds $ div_lt_top coe_ne_top hε.ne').prod_nhds (lt_mem_nhds hεb), refine this.mono (λ c hc, _), exact (div_mul_cancel hε.ne' coe_ne_top).symm.trans_lt (mul_lt_mul hc.1 hc.2) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) lemma _root_.continuous_on.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) (h₁ : ∀ x ∈ s, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x ∈ s, g x ≠ 0 ∨ f x ≠ ∞) : continuous_on (λ x, f x * g x) s := λ x hx, ennreal.tendsto.mul (hf x hx) (h₁ x hx) (hg x hx) (h₂ x hx) lemma _root_.continuous.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} (hf : continuous f) (hg : continuous g) (h₁ : ∀ x, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x, g x ≠ 0 ∨ f x ≠ ∞) : continuous (λ x, f x * g x) := continuous_iff_continuous_at.2 $ λ x, ennreal.tendsto.mul hf.continuous_at (h₁ x) hg.continuous_at (h₂ x) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) protected lemma continuous_div_const (c : ℝ≥0∞) (c_ne_zero : c ≠ 0) : continuous (λ (x : ℝ≥0∞), x / c) := begin simp_rw [div_eq_mul_inv, continuous_iff_continuous_at], intro x, exact ennreal.continuous_at_mul_const (or.intro_left _ (inv_ne_top.mpr c_ne_zero)), end @[continuity] lemma continuous_pow (n : ℕ) : continuous (λ a : ℝ≥0∞, a ^ n) := begin induction n with n IH, { simp [continuous_const] }, simp_rw [nat.succ_eq_add_one, pow_add, pow_one, continuous_iff_continuous_at], assume x, refine ennreal.tendsto.mul (IH.tendsto _) _ tendsto_id _; by_cases H : x = 0, { simp only [H, zero_ne_top, ne.def, or_true, not_false_iff]}, { exact or.inl (λ h, H (pow_eq_zero h)) }, { simp only [H, pow_eq_top_iff, zero_ne_top, false_or, eq_self_iff_true, not_true, ne.def, not_false_iff, false_and], }, { simp only [H, true_or, ne.def, not_false_iff] } end lemma continuous_on_sub : continuous_on (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) { p : ℝ≥0∞ × ℝ≥0∞ | p ≠ ⟨∞, ∞⟩ } := begin rw continuous_on, rintros ⟨x, y⟩ hp, simp only [ne.def, set.mem_set_of_eq, prod.mk.inj_iff] at hp, refine tendsto_nhds_within_of_tendsto_nhds (tendsto_sub (not_and_distrib.mp hp)), end lemma continuous_sub_left {a : ℝ≥0∞} (a_ne_top : a ≠ ⊤) : continuous (λ x, a - x) := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous.prod.mk a), intro x, simp only [a_ne_top, ne.def, mem_set_of_eq, prod.mk.inj_iff, false_and, not_false_iff], end lemma continuous_nnreal_sub {a : ℝ≥0} : continuous (λ (x : ℝ≥0∞), (a : ℝ≥0∞) - x) := continuous_sub_left coe_ne_top lemma continuous_on_sub_left (a : ℝ≥0∞) : continuous_on (λ x, a - x) {x : ℝ≥0∞ | x ≠ ∞} := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp continuous_on_sub (continuous.continuous_on (continuous.prod.mk a)), rintros _ h (_|_), exact h none_eq_top, end lemma continuous_sub_right (a : ℝ≥0∞) : continuous (λ x : ℝ≥0∞, x - a) := begin by_cases a_infty : a = ∞, { simp [a_infty, continuous_const], }, { rw (show (λ x, x - a) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨x, a⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous_id'.prod_mk continuous_const), intro x, simp only [a_infty, ne.def, mem_set_of_eq, prod.mk.inj_iff, and_false, not_false_iff], }, end protected lemma tendsto.pow {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} {n : ℕ} (hm : tendsto m f (𝓝 a)) : tendsto (λ x, (m x) ^ n) f (𝓝 (a ^ n)) := ((continuous_pow n).tendsto a).comp hm lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[<] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[<] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ⟨0, ennreal.zero_lt_one⟩, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (ennreal.mul_left_mono.map_infi_of_continuous_at' (ennreal.continuous_at_const_mul H)).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) lemma inv_map_infi {ι : Sort*} {x : ι → ℝ≥0∞} : (infi x)⁻¹ = (⨆ i, (x i)⁻¹) := order_iso.inv_ennreal.map_infi x lemma inv_map_supr {ι : Sort*} {x : ι → ℝ≥0∞} : (supr x)⁻¹ = (⨅ i, (x i)⁻¹) := order_iso.inv_ennreal.map_supr x lemma inv_limsup {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (l.limsup x)⁻¹ = l.liminf (λ i, (x i)⁻¹) := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] lemma inv_liminf {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (l.liminf x)⁻¹ = l.limsup (λ i, (x i)⁻¹) := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] instance : has_continuous_inv ℝ≥0∞ := ⟨order_iso.inv_ennreal.continuous⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [inv_inv] using tendsto.inv h, tendsto.inv⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := monotone.map_supr_of_continuous_at' (continuous_at_id.add continuous_at_const) $ monotone_id.add monotone_const lemma bsupr_add' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : (⨆ i (hi : p i), f i) + a = ⨆ i (hi : p i), f i + a := by { haveI : nonempty {i // p i} := nonempty_subtype.2 h, simp only [supr_subtype', supr_add] } lemma add_bsupr' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : a + (⨆ i (hi : p i), f i) = ⨆ i (hi : p i), a + f i := by simp only [add_comm a, bsupr_add' h] lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := bsupr_add' hs lemma add_bsupr {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : a + (⨆ i ∈ s, f i) = ⨆ i ∈ s, a + f i := add_bsupr' hs lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr_le {ι ι' : Sort*} [nonempty ι] [nonempty ι'] {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i j, f i + g j ≤ a) : supr f + supr g ≤ a := by simpa only [add_supr, supr_add] using supr₂_le h lemma bsupr_add_bsupr_le' {ι ι'} {p : ι → Prop} {q : ι' → Prop} (hp : ∃ i, p i) (hq : ∃ j, q j) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i (hi : p i) j (hj : q j), f i + g j ≤ a) : (⨆ i (hi : p i), f i) + (⨆ j (hj : q j), g j) ≤ a := by { simp_rw [bsupr_add' hp, add_bsupr' hq], exact supr₂_le (λ i hi, supr₂_le (h i hi)) } lemma bsupr_add_bsupr_le {ι ι'} {s : set ι} {t : set ι'} (hs : s.nonempty) (ht : t.nonempty) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ (i ∈ s) (j ∈ t), f i + g j ≤ a) : (⨆ i ∈ s, f i) + (⨆ j ∈ t, g j) ≤ a := bsupr_add_bsupr_le' hs ht h lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin casesI is_empty_or_nonempty ι, { simp only [supr_of_empty, bot_eq_zero, zero_add] }, { refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), refine supr_add_supr_le (λ i j, _), rcases h i j with ⟨k, hk⟩, exact le_supr_of_le k hk } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := begin by_cases hf : ∀ i, f i = 0, { obtain rfl : f = (λ _, 0), from funext hf, simp only [supr_zero_eq_zero, mul_zero] }, { refine (monotone_id.const_mul' _).map_supr_of_continuous_at _ (mul_zero a), refine ennreal.tendsto.const_mul tendsto_id (or.inl _), exact mt supr_eq_zero.1 hf } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := by simp only [Sup_eq_supr, mul_supr] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine forall_ennreal.2 ⟨λ a, _, _⟩, { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, ← with_top.coe_sub], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, tsub_le_tsub (le_refl (r : ℝ≥0∞))) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id'.2 inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_rfl lemma exists_countable_dense_no_zero_top : ∃ (s : set ℝ≥0∞), s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s := begin obtain ⟨s, s_count, s_dense, hs⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧ (∀ x, is_bot x → x ∉ s) ∧ (∀ x, is_top x → x ∉ s) := exists_countable_dense_no_bot_top ℝ≥0∞, exact ⟨s, s_count, s_dense, λ h, hs.1 0 (by simp) h, λ h, hs.2 ∞ (by simp) h⟩, end lemma exists_lt_add_of_lt_add {x y z : ℝ≥0∞} (h : x < y + z) (hy : y ≠ 0) (hz : z ≠ 0) : ∃ y' z', y' < y ∧ z' < z ∧ x < y' + z' := begin haveI : ne_bot (𝓝[<] y) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hy⟩, haveI : ne_bot (𝓝[<] z) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hz⟩, have A : tendsto (λ (p : ℝ≥0∞ × ℝ≥0∞), p.1 + p.2) ((𝓝[<] y).prod (𝓝[<] z)) (𝓝 (y + z)), { apply tendsto.mono_left _ (filter.prod_mono nhds_within_le_nhds nhds_within_le_nhds), rw ← nhds_prod_eq, exact tendsto_add }, rcases (((tendsto_order.1 A).1 x h).and (filter.prod_mem_prod self_mem_nhds_within self_mem_nhds_within)).exists with ⟨⟨y', z'⟩, hx, hy', hz'⟩, exact ⟨y', z', hy', hz', hx⟩, end end topological_space section liminf lemma exists_frequently_lt_of_liminf_ne_top {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf l (λ n, (∥x n∥₊ : ℝ≥0∞)) ≠ ∞) : ∃ R, ∃ᶠ n in l, x n < R := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h r] with i hi using hi.trans ((coe_nnnorm (x i)).symm ▸ le_abs_self (x i)), end lemma exists_frequently_lt_of_liminf_ne_top' {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf l (λ n, (∥x n∥₊ : ℝ≥0∞)) ≠ ∞) : ∃ R, ∃ᶠ n in l, R < x n := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h (-r)] with i hi using (le_neg.1 hi).trans (neg_le_abs_self _), end lemma exists_upcrossings_of_not_bounded_under {ι : Type*} {l : filter ι} {x : ι → ℝ} (hf : liminf l (λ i, (∥x i∥₊ : ℝ≥0∞)) ≠ ∞) (hbdd : ¬ is_bounded_under (≤) l (λ i, |x i|)) : ∃ a b : ℚ, a < b ∧ (∃ᶠ i in l, x i < a) ∧ (∃ᶠ i in l, ↑b < x i) := begin rw [is_bounded_under_le_abs, not_and_distrib] at hbdd, obtain hbdd | hbdd := hbdd, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top hf, obtain ⟨q, hq⟩ := exists_rat_gt R, refine ⟨q, q + 1, (lt_add_iff_pos_right _).2 zero_lt_one, _, _⟩, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 (lt_of_lt_of_le hq (not_lt.1 hx)).le }, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q + 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx } }, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top' hf, obtain ⟨q, hq⟩ := exists_rat_lt R, refine ⟨q - 1, q, (sub_lt_self_iff _).2 zero_lt_one, _, _⟩, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q - 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx }, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 ((not_lt.1 hx).trans hq.le) } } end end liminf section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_infi₂ (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a @[simp] protected lemma tsum_eq_zero : ∑' i, f i = 0 ↔ ∀ i, f i = 0 := ⟨λ h i, nonpos_iff_eq_zero.1 $ h ▸ ennreal.le_tsum i, λ h, by simp [h]⟩ protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) : (∑' (a : α), c) = ∞ := begin have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)), { apply ennreal.tendsto.mul_const tendsto_nat_nhds_top, simp only [true_or, top_ne_zero, ne.def, not_false_iff] }, have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c), { assume n, rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩, simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s }, simpa [hc] using le_of_tendsto' A B, end protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf), end lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf } /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, convert ennreal.tendsto_coe.2 (nnreal.tendsto_tsum_compl_at_top_zero f), ext1 s, rw ennreal.coe_tsum, exact nnreal.summable_comp_injective (tsum_coe_ne_top_iff_summable.1 hf) subtype.coe_injective end protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, ennreal.add_sub_cancel_right h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw tsub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end lemma tsum_mono_subtype (f : α → ℝ≥0∞) {s t : set α} (h : s ⊆ t) : ∑' (x : s), f x ≤ ∑' (x : t), f x := begin simp only [tsum_subtype], apply ennreal.tsum_le_tsum, exact indicator_le_indicator_of_subset h (λ _, zero_le _), end lemma tsum_union_le (f : α → ℝ≥0∞) (s t : set α) : ∑' (x : s ∪ t), f x ≤ ∑' (x : s), f x + ∑' (x : t), f x := calc ∑' (x : s ∪ t), f x = ∑' (x : s ∪ (t \ s)), f x : by { apply tsum_congr_subtype, rw union_diff_self } ... = ∑' (x : s), f x + ∑' (x : t \ s), f x : tsum_union_disjoint disjoint_diff ennreal.summable ennreal.summable ... ≤ ∑' (x : s), f x + ∑' (x : t), f x : add_le_add le_rfl (tsum_mono_subtype _ (diff_subset _ _)) lemma tsum_bUnion_le {ι : Type*} (f : α → ℝ≥0∞) (s : finset ι) (t : ι → set α) : ∑' (x : ⋃ (i ∈ s), t i), f x ≤ ∑ i in s, ∑' (x : t i), f x := begin classical, induction s using finset.induction_on with i s hi ihs h, { simp }, have : (⋃ (j ∈ insert i s), t j) = t i ∪ (⋃ (j ∈ s), t j), by simp, rw tsum_congr_subtype f this, calc ∑' (x : (t i ∪ (⋃ (j ∈ s), t j))), f x ≤ ∑' (x : t i), f x + ∑' (x : ⋃ (j ∈ s), t j), f x : tsum_union_le _ _ _ ... ≤ ∑' (x : t i), f x + ∑ i in s, ∑' (x : t i), f x : add_le_add le_rfl ihs ... = ∑ j in insert i s, ∑' (x : t j), f x : (finset.sum_insert hi).symm end lemma tsum_Union_le {ι : Type*} [fintype ι] (f : α → ℝ≥0∞) (t : ι → set α) : ∑' (x : ⋃ i, t i), f x ≤ ∑ i, ∑' (x : t i), f x := begin classical, have : (⋃ i, t i) = (⋃ (i ∈ (finset.univ : finset ι)), t i), by simp, rw tsum_congr_subtype f this, exact tsum_bUnion_le _ _ _ end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma has_sum_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : has_sum (λ x, (f x).to_real) (∑' x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, simp only [coe_to_real, ← nnreal.coe_tsum, nnreal.has_sum_coe], exact (tsum_coe_ne_top_iff_summable.1 hsum).has_sum end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := (has_sum_to_real hsum).summable end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_rfl) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } end nnreal namespace ennreal lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := begin lift f to α → ℝ≥0 using hf, have : (∑' (a : α), (f a : ℝ≥0∞)).to_real = ((∑' (a : α), (f a : ℝ≥0∞)).to_nnreal : ℝ≥0∞).to_real, { rw [ennreal.coe_to_real], refl }, rw [this, ← nnreal.tsum_eq_to_nnreal_tsum, ennreal.coe_to_real], exact nnreal.coe_tsum end lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_real_to_nnreal_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p (le_trans hn hp) q (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λ m hm n hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin rcases eq_or_ne C 0 with (rfl|C0), { simp only [zero_mul, add_zero] at h, exact continuous_of_const (λ x y, le_antisymm (h _ _) (h _ _)) }, { refine continuous_iff_continuous_at.2 (λ x, _), by_cases hx : f x = ∞, { have : f =ᶠ[𝓝 x] (λ _, ∞), { filter_upwards [emetric.ball_mem_nhds x ennreal.coe_lt_top], refine λ y (hy : edist y x < ⊤), _, rw edist_comm at hy, simpa [hx, hC, hy.ne] using h x y }, exact this.continuous_at }, { refine (ennreal.tendsto_nhds hx).2 (λ ε (ε0 : 0 < ε), _), filter_upwards [emetric.closed_ball_mem_nhds x (ennreal.div_pos_iff.2 ⟨ε0.ne', hC⟩)], have hεC : C * (ε / C) = ε := ennreal.mul_div_cancel' C0 hC, refine λ y (hy : edist y x ≤ ε / C), ⟨tsub_le_iff_right.2 _, _⟩, { rw edist_comm at hy, calc f x ≤ f y + C * edist x y : h x y ... ≤ f y + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f y) ... = f y + ε : by rw hεC }, { calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f x) ... = f x + ε : by rw hεC } } } end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end @[continuity] theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] lemma is_closed_set_of_lipschitz_on_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (s : set α) : is_closed {f : α → β | lipschitz_on_with K f s} := begin simp only [lipschitz_on_with, set_of_forall], refine is_closed_bInter (λ x hx, is_closed_bInter $ λ y hy, is_closed_le _ _), exacts [continuous.edist (continuous_apply x) (continuous_apply y), continuous_const] end lemma is_closed_set_of_lipschitz_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) : is_closed {f : α → β | lipschitz_with K f} := by simp only [← lipschitz_on_univ, is_closed_set_of_lipschitz_on_with] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
49687db0be1981ef296f38d2167c8d89e20553c9
1dd482be3f611941db7801003235dc84147ec60a
/src/order/filter/basic.lean
98941dee6d86976f10ce0a52b7a4b11a6676c450
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
93,964
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad Theory of filters on sets. -/ import order.galois_connection order.zorn import data.set.finite data.list data.pfun import algebra.pi_instances import category.applicative open lattice set universes u v w x y local attribute [instance] classical.prop_decidable namespace lattice variables {α : Type u} {ι : Sort v} def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ end order theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩)) structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f.sets ↔ s ∈ g.sets := by rw [filter_eq_iff, ext_iff] @[extensionality] protected lemma ext : (∀ s, s ∈ f.sets ↔ s ∈ g.sets) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f.sets := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f.sets → x ⊆ y → y ∈ f.sets := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f.sets → t ∈ f.sets → s ∩ t ∈ f.sets := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f.sets := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f.sets) (h : {x | x ∈ s → x ∈ t} ∈ f.sets) : t ∈ f.sets := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f.sets) → (⋂i∈is, s i) ∈ f.sets := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f.sets, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f.sets, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma exists_sets_subset_iff : (∃t∈f.sets, t ⊆ s) ↔ s ∈ f.sets := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter [t1, ⋯, tn]` replaces a goal of the form `s ∈ f.sets` and terms `h1 : t1 ∈ f.sets, ⋯, tn ∈ f.sets` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter [t1, ⋯, tn] e` is a short form for `{ filter [t1, ⋯, tn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ (principal s).sets := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t.sets} ∈ f.sets}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ (join f).sets ↔ {t | s ∈ filter.sets t} ∈ f.sets := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, g.sets ⊆ f.sets, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g.sets, x ∈ f.sets := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := {s | generate_sets g s}, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ univ_mem_sets, sets_of_superset := assume x y, hs ▸ mem_sets_of_superset, inter_sets := assume x y, hs ▸ inter_mem_sets } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, hs.symm ▸ iff.refl _ /- Galois insertion from sets of sets into a filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u, generate_sets.basic, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f.sets) (b ∈ g.sets), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ (f ⊓ g).sets ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f.sets) : s ∈ (f ⊓ g).sets := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g.sets) : s ∈ (f ⊓ g).sets := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α).sets ↔ (∀x, x ∈ s) := iff.refl _ @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.lattice.has_top).1 (top_unique $ assume s hs, (eq_univ_of_forall hs).symm ▸ univ_mem_sets) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ (f ⊔ g).sets ↔ s ∈ f.sets ∧ s ∈ g.sets := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ (Sup s).sets ↔ (∀f∈s, x ∈ (f:filter α).sets) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ (supr f).sets ↔ (∀i, x ∈ (f i).sets) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets := show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] lemma monotone_principal : monotone (principal : set α → filter α) := by simp only [monotone, principal_mono]; exact assume a b h, h @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) : ∃x, x ∈ s := have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ := by simp only [(@empty_in_sets_eq_bot α f).symm, ne.def]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets := have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in subset.antisymm (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i) (Union_subset $ assume i, infi_le f i) lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl lemma infi_sets_eq_finite (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), apply_instance end @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.lattice.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true], assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f.sets) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal (f : filter α) (s t : set α) : s ∈ (f ⊓ principal t).sets ↔ { x | x ∈ t → x ∈ s } ∈ f.sets := begin simp only [mem_inf_sets, mem_principal_sets, exists_prop], split, { rintros ⟨u, ul, v, tsubv, uvinter⟩, apply filter.mem_sets_of_superset ul, intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ }, intro h, refine ⟨_, h, t, set.subset.refl t, _⟩, rintros x ⟨hx, xt⟩, exact hx xt end end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ (map m f).sets ↔ {x | m x ∈ t} ∈ f.sets := iff.rfl lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ (map m f).sets := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ (map m f).sets ↔ (∃s∈f.sets, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈f.sets, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] } /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈f.sets, ∃t∈g.sets, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ instance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } section -- this section needs to be before applicative, otherwise the wrong instance will be chosen protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected def is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp only [bind, Sup_image, image_singleton, join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp only [bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true, function.comp_app, mem_set_of_eq, singleton_subset_iff] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets := by simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id @[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s := by rw [pure_def, mem_principal_sets, set.singleton_subset_iff] @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ (comap m g).sets ↔ ∃t∈g.sets, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (comap m g).sets := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h lemma monotone_map : monotone (map m) | a b := map_mono lemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h lemma monotone_comap : monotone (comap m) | a b := comap_mono @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ (f i).sets ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, monotone_comap $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) (sup_le (comap_mono le_sup_left) (comap_mono le_sup_right)) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f.sets) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l.sets) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l.sets) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma comap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈f.sets, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma comap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ := comap_neq_bot $ assume t ht, let ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht, ⟨a, (ha : m a = b)⟩ := hm b in ⟨a, ha.symm ▸ hx⟩ @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F.sets, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F.sets → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F.sets → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage_eq, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage_eq] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f.sets, filter_upwards [h, hs], simp only [subset_def, mem_preimage_eq, mem_set_of_eq, forall_true_iff] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ (infi f).sets), have ∃i, preimage m s ∈ (f i).sets, by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true] lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f.sets) (htg : t ∈ g.sets) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm (le_inf (map_mono inf_le_left) (map_mono inf_le_right)) (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage_eq, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f.sets), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈f.sets, m '' s ∈ g.sets) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ section applicative @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s := by simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff] lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α).sets := by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff] lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ (f.seq g).sets ↔ (∃u∈f.sets, ∃t∈g.sets, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.refl _ lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ (f.seq g).sets ↔ (∃u∈f.sets, ∃t∈g.sets, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ ((f.map m).seq g).sets ↔ (∃t u, t ∈ g.sets ∧ u ∈ f.sets ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f.sets) (ht : t ∈ g.sets): s.seq t ∈ (f.seq g).sets := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t∈f.sets, ∀u∈g.sets, set.seq t u ∈ h.sets) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] }, { rw mem_pure_sets at hs, refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := le_antisymm (le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $ by simp only [image_singleton, mem_singleton, singleton_subset_iff]) (le_map $ assume s, begin simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff], exact assume has, ⟨a, has, rfl⟩ end) @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs (by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) }, { rw mem_pure_sets at ht, refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ (bind f m).sets ↔ ∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets := calc s ∈ (bind f m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _ lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f.sets), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets, classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ (f i).sets, by rw [infi_sets_eq hd this] at he; simp only [mem_Union] at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).sets_of_superset hi $ empty_subset _) (assume : ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [infi_sets_eq_finite] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂.sets, f ⁻¹' s ∈ l₁.sets := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ := by rwa [tendsto, ←map_cong hl] lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f.sets) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap_comp, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, lattice.le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, lattice.le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a.sets := by simp only [tendsto, le_principal_iff, mem_map, iff_self] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := show filter.map f (pure a) ≤ pure (f a), by rw [filter.map_pure]; exact le_refl _ lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) := by simp [tendsto]; exact univ_mem_sets lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ principal p) l₂) (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, dsimp, by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f.sets, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) := infi_sets_eq' (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.sets) (hs : s ∈ (g t).sets) : s ∈ (f.lift g).sets := 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 mem_lift_sets (hg : monotone g) {s : set β} : s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) := by rw [lift_sets_eq hg]; simp only [mem_Union] lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (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.sets, 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.sets, 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 monotone_comp hg monotone_map, filter_eq $ set.ext $ by simp only [mem_lift_sets, hg, @mem_lift_sets _ _ f _ 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 monotone_comp hg monotone_comap, filter_eq $ set.ext begin simp only [hg, @mem_lift_sets _ _ f _ 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_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) := classical.by_cases (assume hn : nonempty β, calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp only [filter.lift, infi_subtype, iff_self, ne.def] ... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) : infi_neq_bot_iff_of_directed hn (assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩, hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩) ... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩) (assume hn : ¬ nonempty β, have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn, have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn, calc (f.lift g ≠ ⊥) ↔ false : by simp only [h₁, iff_self, eq_self_iff_true, not_true, ne.def] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp only [h₂, iff_self, eq_self_iff_true, not_true, ne.def]) @[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).sets, (⨅ (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 rw [lift_sets_eq g_mono], simp only [mem_Union, 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 `comap`. -/ 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.sets) : h t ∈ (f.lift' h).sets := 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).sets ↔ (∃t∈f.sets, h t ⊆ s) := have monotone (principal ∘ h), from assume a b h, principal_mono.mpr $ hh h, by simp only [filter.lift', @mem_lift_sets α β f _ this, exists_prop, iff_self, mem_principal_sets, function.comp_app] lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (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.sets, 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.sets, 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_comp hh monotone_principal ... = 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_comp hg monotone_principal 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_comp hh monotone_principal ... = 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_comp hg monotone_principal lemma lift'_principal {s : set α} (hh : monotone h) : (principal s).lift' h = principal (h s) := lift_principal $ monotone_comp hh monotone_principal lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, 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_comp hg monotone_principal) ... = 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_comp hh monotone_principal) 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_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal) (assume t, monotone_comp (hg₂ t) monotone_principal) 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'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) := calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) : lift_neq_bot_iff (monotone_comp hh monotone_principal) ... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp only [principal_eq_bot_iff, iff_self, ne.def, principal_eq_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.sets, h s ∈ g.sets) : 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 [lift_sets_eq hg], simp only [mem_Union, exists_imp_distrib, infi_sets_eq 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 {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x <- seq, y <- top, return (x, y)} hence: s ∈ F <-> ∃n, [n..∞] × univ ⊆ s G := do {y <- top, x <- seq, return (x, y)} hence: s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf] lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) := by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _))) lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f.prod g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot1 {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma prod_bot2 {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) := by simp 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).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {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' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {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 lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) : begin rw [prod_def, lift_neq_bot_iff], exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const) end ... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) : begin apply forall_congr, intro s, apply forall_congr, intro hs, rw [lift'_neq_bot_iff], apply forall_congr, intro t, apply forall_congr, intro ht, rw [set.prod_neq_empty_iff], exact set.monotone_prod monotone_const monotone_id end ... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) : ⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left, assume t ht, (h univ univ_mem_sets t ht).right⟩, assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩ ... ↔ _ : by simp only [forall_sets_neq_empty_iff_neq_bot] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z.sets, ∃ U ∈ x.sets, ∃ V ∈ y.sets, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (filter.prod x x) y ↔ ∀ W ∈ y.sets, ∃ U ∈ x.sets, ∀ (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] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ (@at_top α _).sets := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [inhabited α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_neq_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [inhabited α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α).sets ↔ ∃a:α, ∀b≥a, b ∈ s := iff.intro (assume h, infi_sets_induct h ⟨default α, by simp only [forall_const, mem_univ, forall_true_iff]⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [inhabited α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) ⟨default α⟩ ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true] lemma tendsto_at_top {α β} [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f.sets) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top_at_top {α β} [preorder α] [preorder β] [hα : nonempty α] (h : directed (@has_le.le α _) id) (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := have directed ge (λ (a : α), principal {b : α | a ≤ b}), from λ a b, let ⟨z, hz⟩ := h b a in ⟨z, λ s h x hzx, h (le_trans hz.2 hzx), λ s h x hzx, h (le_trans hz.1 hzx)⟩, by rw [tendsto_at_top, at_top, infi_sets_eq this hα]; simp lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (λs:finset γ, s.image j) at_top at_top := tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $ assume t (ht : s.image i ⊆ t), calc s = (s.image i).image j : by simp only [finset.image_image, (∘), h]; exact finset.image_id.symm ... ⊆ t.image j : finset.image_subset_image ht lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ := by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod]; exact infi_comm lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, -s ∈ f.sets ↔ s ∉ f.sets) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ principal (-s), from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $ by simp only [h, eq_self_iff_true, lattice.neg_neg], by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : - s ∈ f.sets, have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f.sets ∨ - s ∈ f.sets := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f.sets) : s ∈ f.sets ∨ t ∈ f.sets := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f.sets, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets := finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty, forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f.sets, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f.sets, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff], simp only at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : (-s) → α := subtype.val, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty], let f' := comap j f, have : f' ≠ ⊥, { apply mt empty_in_sets_eq_bot.mpr, rintro ⟨t, htf, ht⟩, suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs', rw [subset_empty_iff] at ht, have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty], erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint, set.compl_compl] at this, exact this }, rcases exists_ultrafilter this with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end ultrafilter end filter namespace filter variables {α β γ : Type u} {f : β → filter α} {s : γ → set α} open list lemma mem_traverse_sets : ∀(fs : list β) (us : list γ), forall₂ (λb c, s c ∈ (f b).sets) fs us → traverse s us ∈ (traverse f fs).sets | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) : t ∈ (traverse f fs).sets ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ (f b).sets) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def, exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) end filter
cf4cc218fec16f3744e46fc90e1d4204e90c4fbd
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/sheaves/stalks.lean
7199ba7708cd256cb6edc279b5867c2015682c8c
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
24,393
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.types import category_theory.limits.preserves.filtered import category_theory.limits.final import topology.sober import tactic.elementwise import algebra.category.Ring /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the composition of the inclusion of categories `(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ` and the functor `F : (opens X)ᵒᵖ ⥤ C`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) @[simp, elementwise] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU } @[simp, reassoc, elementwise] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) variables (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', cases j, cases j_val, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, induction U using opposite.rec, cases U, cases U_val, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end lemma stalk_pushforward_iso_of_open_embedding {f : X ⟶ Y} (hf : open_embedding f) (F : X.presheaf C) (x : X) : is_iso (F.stalk_pushforward _ f x) := begin haveI := functor.initial_of_adjunction (hf.is_open_map.adjunction_nhds x), convert is_iso.of_iso ((functor.final.colimit_iso (hf.is_open_map.functor_nhds x).op ((open_nhds.inclusion (f x)).op ⋙ f _* F) : _).symm ≪≫ colim.map_iso _), swap, { fapply nat_iso.of_components, { intro U, refine F.map_iso (eq_to_iso _), dsimp only [functor.op], exact congr_arg op (subtype.eq $ set.preimage_image_eq (unop U).1.1 hf.inj) }, { intros U V i, erw [← F.map_comp, ← F.map_comp], congr } }, { ext U, rw ← iso.comp_inv_eq, erw colimit.ι_map_assoc, rw [colimit.ι_pre, category.assoc], erw [colimit.ι_map_assoc, colimit.ι_pre, ← F.map_comp_assoc], apply colimit.w ((open_nhds.inclusion (f x)).op ⋙ f _* F) _, dsimp only [functor.op], refine ((hom_of_le _).op : op (unop U) ⟶ _), exact set.image_preimage_subset _ _ }, end end stalk_pushforward section stalk_pullback /-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/ def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ⟶ (pullback_obj f F).stalk x := (stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫ stalk_pushforward _ _ _ x /-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/ def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) : (pullback_obj f F).obj (op U) ⟶ F.stalk (f x) := colimit.desc (Lan.diagram (opens.map f).op F (op U)) { X := F.stalk (f x), ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩, naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } } /-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/ def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : (pullback_obj f F).stalk x ⟶ F.stalk (f x) := colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F) { X := F.stalk (f x), ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩, naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } } /-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/ def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ≅ (pullback_obj f F).stalk x := { hom := stalk_pullback_hom _ _ _ _, inv := stalk_pullback_inv _ _ _ _, hom_inv_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward germ_to_pullback_stalk germ, ext j, induction j using opposite.rec, cases j, simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app, whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc, colimit.ι_pre_assoc], erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id], simpa end, inv_hom_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward, ext U j, induction U using opposite.rec, cases U, cases j, rcases j_right with ⟨⟨⟩⟩, erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc, colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id], simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv, cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app, whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app], erw ←colimit.w _ (@hom_of_le (open_nhds x) _ ⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩ j_hom.unop.le).op, erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), congr, simp only [category.assoc, costructured_arrow.map_mk], delta costructured_arrow.mk, congr, end } end stalk_pullback section stalk_specializes variables {C} /-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/ noncomputable def stalk_specializes (F : X.presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x := begin refine colimit.desc _ ⟨_,λ U, _,_⟩, { exact colimit.ι ((open_nhds.inclusion x).op ⋙ F) (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩) }, { intros U V i, dsimp, rw category.comp_id, let U' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩, let V' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 : _)⟩, exact colimit.w ((open_nhds.inclusion x).op ⋙ F) (show V' ⟶ U', from i.unop).op } end @[simp, reassoc, elementwise] lemma germ_stalk_specializes (F : X.presheaf C) {U : opens X} {y : U} {x : X} (h : x ⤳ y) : F.germ y ≫ F.stalk_specializes h = F.germ ⟨x, specializes_iff_forall_open.mp h _ U.2 y.prop⟩ := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma germ_stalk_specializes' (F : X.presheaf C) {U : opens X} {x y : X} (h : x ⤳ y) (hy : y ∈ U) : F.germ ⟨y, hy⟩ ≫ F.stalk_specializes h = F.germ ⟨x, specializes_iff_forall_open.mp h _ U.2 hy⟩ := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_functor_map {F G : X.presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) : F.stalk_specializes h ≫ (stalk_functor C x).map f = (stalk_functor C y).map f ≫ G.stalk_specializes h := by { ext, delta stalk_functor, simpa [stalk_specializes] } @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) {x y : X} (h : x ⤳ y) : (f _* F).stalk_specializes (f.map_specializes h) ≫ F.stalk_pushforward _ f x = F.stalk_pushforward _ f y ≫ F.stalk_specializes h := by { ext, delta stalk_pushforward, simpa [stalk_specializes] } end stalk_specializes section concrete variables {C} variables [concrete_category.{v} C] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] variables [preserves_filtered_colimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective.{v v} _ (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff.{v v} _ (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G) (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) : function.injective ((stalk_functor C x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U)) (h : ∀ x : U, F.1.germ x s = F.1.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.1.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) (U : opens X) (h : ∀ x : U, function.injective ((stalk_functor C x.val).map f)) : function.injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔ (∀ U : opens X, function.injective (f.app (op U))) := ⟨λ h U, app_injective_of_stalk_functor_map_injective f U (λ x, h x.1), stalk_functor_map_injective_of_app_injective f⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (hinj : ∀ x : U, function.injective ((stalk_functor C x.1).map f)) (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)), f.app (op V) s = G.1.map iVU.op t) : function.surjective (f.app (op U)) := begin intro t, -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← comp_apply, ← f.naturality, comp_apply, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (hinj ⟨z, (iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) z.2)⟩), dsimp only, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], simp_rw [← comp_apply, f.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp], refl } end lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f)) : function.surjective (f.app (op U)) := begin refine app_surjective_of_injective_of_locally_surjective f U (λ x, (h x).1) (λ t x, _), -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.1.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.1.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.1.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁], rw [← comp_apply, f.naturality, comp_apply, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f)) : function.bijective (f.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f U (λ x, (h x).1), app_surjective_of_stalk_functor_map_bijective f U h⟩ lemma app_is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) (U : opens X) [∀ x : U, is_iso ((stalk_functor C x.val).map f)] : is_iso (f.app (op U)) := begin -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices : is_iso ((forget C).map (f.app (op U))), { exactI is_iso_of_reflects_iso (f.app (op U)) (forget C) }, rw is_iso_iff_bijective, apply app_bijective_of_stalk_functor_map_bijective, intro x, apply (is_iso_iff_bijective _).mp, exact functor.map_is_iso (forget C) ((stalk_functor C x.1).map f) end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor C x).map f)] : is_iso f := begin -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices : is_iso ((sheaf.forget C X).map f), { exactI is_iso_of_fully_faithful (sheaf.forget C X) f }, -- We show that all components of `f` are isomorphisms. suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.app U), { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f this, }, intro U, induction U using opposite.rec, apply app_is_iso_of_stalk_functor_map_iso end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f ((sheaf.forget C X).map_is_iso f) }, { intro h, exactI is_iso_of_stalk_functor_map_iso f } end end concrete instance (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra (F.obj $ op U) (F.stalk x) := (F.germ x).to_algebra @[simp] lemma stalk_open_algebra_map {X : Top} (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra_map (F.obj $ op U) (F.stalk x) = F.germ x := rfl end Top.presheaf
1eb44e35a1b6724d3b378f4e1087f7abf59ae5f3
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_650.lean
ae67021fc49836c58f911bcfd3caac02e2b7efc4
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
203
lean
variables p q r : Prop -- BEGIN example (h₁ : p ∧ q → r) (h₂ : p) (h₃ : q) : r := begin apply h₁, -- By implication elimination on `h₁`, it suffices to prove `p ∧ q`. sorry end -- END
cecae6fd6a7a0bfa7666b3f624cd4dd97d6766c3
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/newfrontend/t1.lean
50ecb9dc2e47a9a89b0fa88c27caa60b84f1233c
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
57
lean
variable {α : Type} def f (a : α) : α := a #check f 1
265f9379c080ff2b125a39ea5f0a5ebfbf74fb11
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/prod.lean
887fba718abff34285ab2dc0c29c2ad10f5adf9c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
25,818
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, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.basic import order.partial_sups /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl theorem fst_surjective : function.surjective (fst R M M₂) := λ x, ⟨(x, 0), rfl⟩ theorem snd_surjective : function.surjective (snd R M M₂) := λ x, ⟨(0, x), rfl⟩ /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul, ring_hom.id_apply] } @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id theorem range_inl : range (inl R M M₂) = ker (snd R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.fst, prod.ext rfl h.symm⟩ } end theorem ker_snd : ker (snd R M M₂) = range (inl R M M₂) := eq.symm $ range_inl R M M₂ theorem range_inr : range (inr R M M₂) = ker (fst R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.snd, prod.ext h.symm rfl⟩ } end theorem ker_fst : ker (fst R M M₂) = range (inr R M M₂) := eq.symm $ range_inr R M M₂ end @[simp] theorem coe_inl : (inl R M M₂ : M → M × M₂) = λ x, (x, 0) := rfl theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R M M₂ : M₂ → M × M₂) = prod.mk 0 := rfl theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add], ac_refl }, map_smul' := λ r a, by { dsimp, ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy end submodule namespace linear_equiv /-- Product of modules is commutative up to linear isomorphism. -/ @[simps apply] def prod_comm (R M N : Type*) [semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : (M × N) ≃ₗ[R] (N × M) := { to_fun := prod.swap, map_smul' := λ r ⟨m, n⟩, rfl, ..add_equiv.prod_comm } section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smulₛₗ c _) (e₂.map_smulₛₗ c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →o order_dual (submodule R M) := ⟨λ n, (tunnel' f i n).1, monotone_nat_of_le_succ (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ tunnel f i n := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)) := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ tunnel f i (n+1) ≤ tunnel f i n := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)) := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel end linear_map
8a572eeecc137e17064cfd2166cea89aa2b96f4b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/category/Mon/adjunctions.lean
8d81c9e599cfba4f9163a35036b7678ad527491b
[ "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
2,262
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import algebra.category.Mon.basic import algebra.category.Semigroup.basic import algebra.group.with_one import algebra.free_monoid /-! # Adjunctions regarding the category of monoids This file proves the adjunction between adjoining a unit to a semigroup and the forgetful functor from monoids to semigroups. ## TODO * free-forgetful adjunction for monoids * adjunctions related to commutative monoids -/ universe u open category_theory /-- The functor of adjoining a neutral element `one` to a semigroup. -/ @[to_additive "The functor of adjoining a neutral element `zero` to a semigroup", simps] def adjoin_one : Semigroup.{u} ⥤ Mon.{u} := { obj := λ S, Mon.of (with_one S), map := λ X Y, with_one.map, map_id' := λ X, with_one.map_id, map_comp' := λ X Y Z, with_one.map_comp } @[to_additive has_forget_to_AddSemigroup] instance has_forget_to_Semigroup : has_forget₂ Mon Semigroup := { forget₂ := { obj := λ M, Semigroup.of M, map := λ M N, monoid_hom.to_mul_hom }, } /-- The adjoin_one-forgetful adjunction from `Semigroup` to `Mon`.-/ @[to_additive "The adjoin_one-forgetful adjunction from `AddSemigroup` to `AddMon`"] def adjoin_one_adj : adjoin_one ⊣ forget₂ Mon.{u} Semigroup.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ S M, with_one.lift.symm, hom_equiv_naturality_left_symm' := begin intros S T M f g, ext, simp only [equiv.symm_symm, adjoin_one_map, coe_comp], simp_rw with_one.map, apply with_one.cases_on x, { refl }, { simp } end } /-- The free functor `Type u ⥤ Mon` sending a type `X` to the free monoid on `X`. -/ def free : Type u ⥤ Mon.{u} := { obj := λ α, Mon.of (free_monoid α), map := λ X Y, free_monoid.map, map_id' := by { intros, ext1, refl }, map_comp' := by { intros, ext1, refl } } /-- The free-forgetful adjunction for monoids. -/ def adj : free ⊣ forget Mon.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ X G, free_monoid.lift.symm, hom_equiv_naturality_left_symm' := λ X Y G f g, by { ext1, refl } } instance : is_right_adjoint (forget Mon.{u}) := ⟨_, adj⟩
479e82cdf4b9c951eddd21b7f9b1fc0cad75f03a
f47872278edfa65030d6cd0604480581b09ae4b5
/src/ordered/dimality.lean
de8b6ad8504fc47e14e5a79d85db73fd940129e0
[ "MIT" ]
permissive
ocornoc/geodude
c822c494d9ed5d6dd2efa434cbaa5e0e42c22691
e63c87db67f1686c902e9bcd1863e74e1a29457f
refs/heads/master
1,681,951,483,388
1,620,592,363,000
1,620,595,412,000
287,442,904
0
0
null
null
null
null
UTF-8
Lean
false
false
3,279
lean
import .convex set_theory.cardinal order.well_founded set_theory.cardinal_ordinal open_locale cardinal section universe u parameters {α : Type u} [has_betweenness α] @[reducible] def generates (b : set α) (s : set α) (h : is_affine s) : Prop := affine_hull b = s theorem generates.of_span {s : set α} (h : is_affine s) : generates s s h := h @[reducible] def generators {s : set α} (h : is_affine s) : set (set α) := {b | generates b s h} namespace generators theorem self_gens {s : set α} : ∀ h : is_affine s, s ∈ generators h := generates.of_span theorem is_nonempty {s : set α} (h : is_affine s) : (generators h).nonempty := ⟨s, self_gens h⟩ end generators @[reducible] def is_basis {s : set α} {h : is_affine s} (b : generators h) : Prop := ∀ b' ∈ generators h, #b ≤ #b' @[reducible] def bases {s : set α} (h : is_affine s) : set (@generators s h) := is_basis end protected def {u} bases.univ (α : Type u) [has_betweenness α] : set (generators is_affine.univ) := @bases α _ _ _ section universe u theorem cardinal.le_mk_le_iff_ex_sub_right {α : Type u} {s t : set α} (h : #s ≤ #t) : ∃ s' ⊆ t, #s' = #s := begin rw cardinal.le_mk_iff_exists_subset at h, rcases h with ⟨s', _, _⟩, exact ⟨s', ‹_›, ‹_›⟩ end parameters {α : Type u} [has_betweenness α] namespace bases theorem is_nonempty {s : set α} (h : is_affine s) : (bases h).nonempty := begin have gne : (@set.univ $ generators h).nonempty, { cases generators.is_nonempty h with w h, exact ⟨⟨w, h⟩, trivial⟩ }, let f := λ l r : generators h, #l < #r, rcases well_founded.has_min (inv_image.wf _ cardinal.wf) _ gne with ⟨b, _, hb⟩, refine ⟨b, λ b' hb', _⟩, specialize hb ⟨b', hb'⟩ trivial, change ¬ _ < _ at hb, simp at hb, assumption end instance {s : set α} (h : is_affine s) : nonempty (bases h) := ⟨⟨(is_nonempty h).some, (is_nonempty h).some_mem⟩⟩ def basis_card {s : set α} (h : is_affine s) : cardinal := #(nonempty h).some theorem all_bases_same_card {s : set α} {h : is_affine s} (b : bases h) : #b = basis_card h := begin rcases b with ⟨⟨g, hg⟩, hbg⟩, let b' := (infer_instance : nonempty $ bases h).some, change #g = #b', exact le_antisymm (hbg b'.val b'.val.property) (b'.property g hg) end /- theorem ex_union_basis_of_gen {s : set α} (hs : is_affine s) (g : generators _ hs) : ∃ (s' : set α) (b : bases hs), s' ∪ b = g := begin by_cases hg : is_basis _ _ g, { exact ⟨∅, ⟨g, hg⟩, by simp⟩ }, rw is_basis at hg, push_neg at hg, rcases hg with ⟨b, hbg, ⟨hb : _ ≤ #g.val, hb' : ¬ (#g.val ≤ _)⟩⟩, by_contra h, push_neg at h, specialize h b, end --theorem ex_subgen {s : set α} {hs : is_affine s} {g : generators _ hs} (h : ) theorem ex_basis_sub_gen {s : set α} (hs : is_affine s) (g : generators _ hs) : ∃ b : bases hs, b.val.val ⊆ g.val := begin by_cases hg : is_basis _ _ g, { exact ⟨⟨g, hg⟩, set.subset.rfl⟩ }, rw is_basis at hg, push_neg at hg, rcases hg with ⟨b, hbg, ⟨hb : _ ≤ #g.val, hb' : ¬ (#g.val ≤ _)⟩⟩, rw cardinal.le_mk_iff_exists_subset at hb hb', rcases hb with ⟨w, hw, hw'⟩, push_neg at hb', refine ⟨⟨⟨w, _⟩, _⟩, hw⟩, end -/ end bases end
14f5b466d96e4d936d855ccfe6e26f682f5b6da4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/shapes/constructions/binary_products.lean
db9d17bacbde0814ef634b60d8249d5c264f8fa2
[ "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
1,638
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.limits.shapes.terminal import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products universes v u /-! # Constructing binary product from pullbacks and terminal object. If a category has pullbacks and a terminal object, then it has binary products. TODO: provide the dual result. -/ open category_theory category_theory.category category_theory.limits /-- Any category with pullbacks and terminal object has binary products. -/ -- This is not an instance, as it is not always how one wants to construct binary products! lemma has_binary_products_of_terminal_and_pullbacks (C : Type u) [𝒞 : category.{v} C] [has_terminal C] [has_pullbacks C] : has_binary_products C := { has_limit := λ F, has_limit.mk { cone := { X := pullback (terminal.from (F.obj walking_pair.left)) (terminal.from (F.obj walking_pair.right)), π := discrete.nat_trans (λ x, walking_pair.cases_on x pullback.fst pullback.snd)}, is_limit := { lift := λ c, pullback.lift ((c.π).app walking_pair.left) ((c.π).app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (limit.lift_π _ _) (limit.lift_π _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw limit.lift_π; refl end } } }
875ef5b74733dff8ee048a938beb542bf399c194
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/monoidal_categories/tensor_with_object.lean
0ec31e69cf2d7faa588a5bfa972b232c44184347
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
1,364
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .monoidal_category open tqft.categories open tqft.categories.functor open tqft.categories.products open tqft.categories.natural_transformation namespace tqft.categories.monoidal_category universe variables u v local attribute [ematch] MonoidalStructure.interchange_right_identity definition MonoidalStructure.tensor_on_left { C: Category.{u v} } ( m : MonoidalStructure C ) ( Z: C.Obj ) : Functor.{u v u v} C C := { onObjects := λ X, m.tensorObjects Z X, onMorphisms := λ X Y f, m.tensorMorphisms (C.identity Z) f, identities := ♮, -- This uses lemma TensorProduct_identities functoriality := ♮ -- This uses lemma MonoidalStructure.interchange_right_identity } local attribute [ematch] MonoidalStructure.interchange_left_identity definition MonoidalStructure.tensor_on_right { C: Category.{u v} } ( m : MonoidalStructure C ) ( Z: C.Obj ) : Functor.{u v u v} C C := { onObjects := λ X, m.tensorObjects X Z, onMorphisms := λ X Y f, m.tensorMorphisms f (C.identity Z), identities := ♮, -- This uses lemma TensorProduct_identities functoriality := ♮ -- This uses lemma MonoidalStructure.interchange_left_identity } end tqft.categories.monoidal_category
63985e5743f6b3da86feb3ec2a0c6f56ebbdc36e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/cyclotomic/basic.lean
027d406fad74718e2c4a3e5bda02ac6c1b499c96
[ "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
31,940
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic import number_theory.number_field.basic import algebra.char_p.algebra import field_theory.galois /-! # Cyclotomic extensions Let `A` and `B` be commutative rings with `algebra A B`. For `S : set ℕ+`, we define a class `is_cyclotomic_extension S A B` expressing the fact that `B` is obtained from `A` by adding `n`-th primitive roots of unity, for all `n ∈ S`. ## Main definitions * `is_cyclotomic_extension S A B` : means that `B` is obtained from `A` by adding `n`-th primitive roots of unity, for all `n ∈ S`. * `cyclotomic_field`: given `n : ℕ+` and a field `K`, we define `cyclotomic n K` as the splitting field of `cyclotomic n K`. If `n` is nonzero in `K`, it has the instance `is_cyclotomic_extension {n} K (cyclotomic_field n K)`. * `cyclotomic_ring` : if `A` is a domain with fraction field `K` and `n : ℕ+`, we define `cyclotomic_ring n A K` as the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of `X ^ n - 1`. If `n` is nonzero in `A`, it has the instance `is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`. ## Main results * `is_cyclotomic_extension.trans` : if `is_cyclotomic_extension S A B` and `is_cyclotomic_extension T B C`, then `is_cyclotomic_extension (S ∪ T) A C` if `function.injective (algebra_map B C)`. * `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension (S ∪ T) A B`, then `is_cyclotomic_extension T (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) B`. * `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension T A B` and `S ⊆ T`, then `is_cyclotomic_extension S A (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 })`. * `is_cyclotomic_extension.finite` : if `S` is finite and `is_cyclotomic_extension S A B`, then `B` is a finite `A`-algebra. * `is_cyclotomic_extension.number_field` : a finite cyclotomic extension of a number field is a number field. * `is_cyclotomic_extension.splitting_field_X_pow_sub_one` : if `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `X ^ n - 1`. * `is_cyclotomic_extension.splitting_field_cyclotomic` : if `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `cyclotomic n K`. ## Implementation details Our definition of `is_cyclotomic_extension` is very general, to allow rings of any characteristic and infinite extensions, but it will mainly be used in the case `S = {n}` and for integral domains. All results are in the `is_cyclotomic_extension` namespace. Note that some results, for example `is_cyclotomic_extension.trans`, `is_cyclotomic_extension.finite`, `is_cyclotomic_extension.number_field`, `is_cyclotomic_extension.finite_dimensional`, `is_cyclotomic_extension.is_galois` and `cyclotomic_field.algebra_base` are lemmas, but they can be made local instances. Some of them are included in the `cyclotomic` locale. -/ open polynomial algebra finite_dimensional set open_locale big_operators universes u v w z variables (n : ℕ+) (S T : set ℕ+) (A : Type u) (B : Type v) (K : Type w) (L : Type z) variables [comm_ring A] [comm_ring B] [algebra A B] variables [field K] [field L] [algebra K L] noncomputable theory /-- Given an `A`-algebra `B` and `S : set ℕ+`, we define `is_cyclotomic_extension S A B` requiring that there is a `n`-th primitive root of unity in `B` for all `n ∈ S` and that `B` is generated over `A` by the roots of `X ^ n - 1`. -/ @[mk_iff] class is_cyclotomic_extension : Prop := (exists_prim_root {n : ℕ+} (ha : n ∈ S) : ∃ r : B, is_primitive_root r n) (adjoin_roots : ∀ (x : B), x ∈ adjoin A { b : B | ∃ n : ℕ+, n ∈ S ∧ b ^ (n : ℕ) = 1 }) namespace is_cyclotomic_extension section basic /-- A reformulation of `is_cyclotomic_extension` that uses `⊤`. -/ lemma iff_adjoin_eq_top : is_cyclotomic_extension S A B ↔ (∀ (n : ℕ+), n ∈ S → ∃ r : B, is_primitive_root r n) ∧ (adjoin A { b : B | ∃ n : ℕ+, n ∈ S ∧ b ^ (n : ℕ) = 1 } = ⊤) := ⟨λ h, ⟨λ _, h.exists_prim_root, algebra.eq_top_iff.2 h.adjoin_roots⟩, λ h, ⟨h.1, algebra.eq_top_iff.1 h.2⟩⟩ /-- A reformulation of `is_cyclotomic_extension` in the case `S` is a singleton. -/ lemma iff_singleton : is_cyclotomic_extension {n} A B ↔ (∃ r : B, is_primitive_root r n) ∧ (∀ x, x ∈ adjoin A { b : B | b ^ (n : ℕ) = 1 }) := by simp [is_cyclotomic_extension_iff] /-- If `is_cyclotomic_extension ∅ A B`, then the image of `A` in `B` equals `B`. -/ lemma empty [h : is_cyclotomic_extension ∅ A B] : (⊥ : subalgebra A B) = ⊤ := by simpa [algebra.eq_top_iff, is_cyclotomic_extension_iff] using h /-- If `is_cyclotomic_extension {1} A B`, then the image of `A` in `B` equals `B`. -/ lemma singleton_one [h : is_cyclotomic_extension {1} A B] : (⊥ : subalgebra A B) = ⊤ := algebra.eq_top_iff.2 (λ x, by simpa [adjoin_singleton_one] using ((is_cyclotomic_extension_iff _ _ _).1 h).2 x) variables {A B} /-- If `(⊥ : subalgebra A B) = ⊤`, then `is_cyclotomic_extension ∅ A B`. -/ lemma singleton_zero_of_bot_eq_top (h : (⊥ : subalgebra A B) = ⊤) : is_cyclotomic_extension ∅ A B := begin refine (iff_adjoin_eq_top _ _ _).2 ⟨λ s hs, by simpa using hs, _root_.eq_top_iff.2 (λ x hx, _)⟩, rw [← h] at hx, simpa using hx, end variables (A B) /-- Transitivity of cyclotomic extensions. -/ lemma trans (C : Type w) [comm_ring C] [algebra A C] [algebra B C] [is_scalar_tower A B C] [hS : is_cyclotomic_extension S A B] [hT : is_cyclotomic_extension T B C] (h : function.injective (algebra_map B C)) : is_cyclotomic_extension (S ∪ T) A C := begin refine ⟨λ n hn, _, λ x, _⟩, { cases hn, { obtain ⟨b, hb⟩ := ((is_cyclotomic_extension_iff _ _ _).1 hS).1 hn, refine ⟨algebra_map B C b, _⟩, exact hb.map_of_injective h }, { exact ((is_cyclotomic_extension_iff _ _ _).1 hT).1 hn } }, { refine adjoin_induction (((is_cyclotomic_extension_iff _ _ _).1 hT).2 x) (λ c ⟨n, hn⟩, subset_adjoin ⟨n, or.inr hn.1, hn.2⟩) (λ b, _) (λ x y hx hy, subalgebra.add_mem _ hx hy) (λ x y hx hy, subalgebra.mul_mem _ hx hy), { let f := is_scalar_tower.to_alg_hom A B C, have hb : f b ∈ (adjoin A { b : B | ∃ (a : ℕ+), a ∈ S ∧ b ^ (a : ℕ) = 1 }).map f := ⟨b, ((is_cyclotomic_extension_iff _ _ _).1 hS).2 b, rfl⟩, rw [is_scalar_tower.to_alg_hom_apply, ← adjoin_image] at hb, refine adjoin_mono (λ y hy, _) hb, obtain ⟨b₁, ⟨⟨n, hn⟩, h₁⟩⟩ := hy, exact ⟨n, ⟨mem_union_left T hn.1, by rw [← h₁, ← alg_hom.map_pow, hn.2, alg_hom.map_one]⟩⟩ } } end @[nontriviality] lemma subsingleton_iff [subsingleton B] : is_cyclotomic_extension S A B ↔ S = {} ∨ S = {1} := begin split, { rintro ⟨hprim, -⟩, rw ←subset_singleton_iff_eq, intros t ht, obtain ⟨ζ, hζ⟩ := hprim ht, rw [mem_singleton_iff, ←pnat.coe_eq_one_iff], exact_mod_cast hζ.unique (is_primitive_root.of_subsingleton ζ) }, { rintro (rfl|rfl), { refine ⟨λ _ h, h.elim, λ x, by convert (mem_top : x ∈ ⊤)⟩ }, { rw iff_singleton, refine ⟨⟨0, is_primitive_root.of_subsingleton 0⟩, λ x, by convert (mem_top : x ∈ ⊤)⟩ } } end /-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `S ∪ T`, then `B` is a cyclotomic extension of `adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 } ` given by roots of unity of order in `T`. -/ lemma union_right [h : is_cyclotomic_extension (S ∪ T) A B] : is_cyclotomic_extension T (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) B := begin have : { b : B | ∃ (n : ℕ+), n ∈ S ∪ T ∧ b ^ (n : ℕ) = 1 } = { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 } ∪ { b : B | ∃ (n : ℕ+), n ∈ T ∧ b ^ (n : ℕ) = 1 }, { refine le_antisymm (λ x hx, _) (λ x hx, _), { rcases hx with ⟨n, hn₁ | hn₂, hnpow⟩, { left, exact ⟨n, hn₁, hnpow⟩ }, { right, exact ⟨n, hn₂, hnpow⟩ } }, { rcases hx with ⟨n, hn⟩ | ⟨n, hn⟩, { exact ⟨n, or.inl hn.1, hn.2⟩ }, { exact ⟨n, or.inr hn.1, hn.2⟩ } } }, refine ⟨λ n hn, ((is_cyclotomic_extension_iff _ _ _).1 h).1 (mem_union_right S hn), λ b, _⟩, replace h := ((is_cyclotomic_extension_iff _ _ _).1 h).2 b, rwa [this, adjoin_union_eq_adjoin_adjoin, subalgebra.mem_restrict_scalars] at h end /-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `T` and `S ⊆ T`, then `adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }` is a cyclotomic extension of `B` given by roots of unity of order in `S`. -/ lemma union_left [h : is_cyclotomic_extension T A B] (hS : S ⊆ T) : is_cyclotomic_extension S A (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) := begin refine ⟨λ n hn, _, λ b, _⟩, { obtain ⟨b, hb⟩ := ((is_cyclotomic_extension_iff _ _ _).1 h).1 (hS hn), refine ⟨⟨b, subset_adjoin ⟨n, hn, hb.pow_eq_one⟩⟩, _⟩, rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] }, { convert mem_top, rw [← adjoin_adjoin_coe_preimage, preimage_set_of_eq], norm_cast } end variables {n S} /-- If `∀ s ∈ S, n ∣ s` and `S` is not empty, then `is_cyclotomic_extension S A B` implies `is_cyclotomic_extension (S ∪ {n}) A B`. -/ lemma of_union_of_dvd (h : ∀ s ∈ S, n ∣ s) (hS : S.nonempty) [H : is_cyclotomic_extension S A B] : is_cyclotomic_extension (S ∪ {n}) A B := begin refine (iff_adjoin_eq_top _ _ _).2 ⟨λ s hs, _, _⟩, { rw [mem_union, mem_singleton_iff] at hs, obtain hs|rfl := hs, { exact H.exists_prim_root hs }, { obtain ⟨m, hm⟩ := hS, obtain ⟨x, rfl⟩ := h m hm, obtain ⟨ζ, hζ⟩ := H.exists_prim_root hm, refine ⟨ζ ^ (x : ℕ), _⟩, convert hζ.pow_of_dvd x.ne_zero (dvd_mul_left (x : ℕ) s), simp only [pnat.mul_coe, nat.mul_div_left, pnat.pos] } }, { refine _root_.eq_top_iff.2 _, rw [← ((iff_adjoin_eq_top S A B).1 H).2], refine adjoin_mono (λ x hx, _), simp only [union_singleton, mem_insert_iff, mem_set_of_eq] at ⊢ hx, obtain ⟨m, hm⟩ := hx, exact ⟨m, ⟨or.inr hm.1, hm.2⟩⟩ } end /-- If `∀ s ∈ S, n ∣ s` and `S` is not empty, then `is_cyclotomic_extension S A B` if and only if `is_cyclotomic_extension (S ∪ {n}) A B`. -/ lemma iff_union_of_dvd (h : ∀ s ∈ S, n ∣ s) (hS : S.nonempty) : is_cyclotomic_extension S A B ↔ is_cyclotomic_extension (S ∪ {n}) A B := begin refine ⟨λ H, by exactI of_union_of_dvd A B h hS, λ H, (iff_adjoin_eq_top _ _ _).2 ⟨λ s hs, _, _⟩⟩, { exact H.exists_prim_root (subset_union_left _ _ hs) }, { rw [_root_.eq_top_iff, ← ((iff_adjoin_eq_top _ A B).1 H).2], refine adjoin_mono (λ x hx, _), simp only [union_singleton, mem_insert_iff, mem_set_of_eq] at ⊢ hx, obtain ⟨m, rfl|hm, hxpow⟩ := hx, { obtain ⟨y, hy⟩ := hS, refine ⟨y, ⟨hy, _⟩⟩, obtain ⟨z, rfl⟩ := h y hy, simp only [pnat.mul_coe, pow_mul, hxpow, one_pow] }, { exact ⟨m, ⟨hm, hxpow⟩⟩ } } end variables (n S) /-- `is_cyclotomic_extension S A B` is equivalent to `is_cyclotomic_extension (S ∪ {1}) A B`. -/ lemma iff_union_singleton_one : is_cyclotomic_extension S A B ↔ is_cyclotomic_extension (S ∪ {1}) A B := begin obtain hS|rfl := S.eq_empty_or_nonempty.symm, { exact iff_union_of_dvd _ _ (λ s hs, one_dvd _) hS }, rw [empty_union], refine ⟨λ H, _, λ H, _⟩, { refine (iff_adjoin_eq_top _ _ _).2 ⟨λ s hs, ⟨1, by simp [mem_singleton_iff.1 hs]⟩, _⟩, simp [adjoin_singleton_one, @empty _ _ _ _ _ H] }, { refine (iff_adjoin_eq_top _ _ _).2 ⟨λ s hs, (not_mem_empty s hs).elim, _⟩, simp [@singleton_one A B _ _ _ H] } end variables {A B} /-- If `(⊥ : subalgebra A B) = ⊤`, then `is_cyclotomic_extension {1} A B`. -/ lemma singleton_one_of_bot_eq_top (h : (⊥ : subalgebra A B) = ⊤) : is_cyclotomic_extension {1} A B := begin convert (iff_union_singleton_one _ _ _).1 (singleton_zero_of_bot_eq_top h), simp end /-- If `function.surjective (algebra_map A B)`, then `is_cyclotomic_extension {1} A B`. -/ lemma singleton_one_of_algebra_map_bijective (h : function.surjective (algebra_map A B)) : is_cyclotomic_extension {1} A B := singleton_one_of_bot_eq_top (surjective_algebra_map_iff.1 h).symm variables (A B) /-- Given `(f : B ≃ₐ[A] C)`, if `is_cyclotomic_extension S A B` then `is_cyclotomic_extension S A C`. -/ @[protected] lemma equiv {C : Type*} [comm_ring C] [algebra A C] [h : is_cyclotomic_extension S A B] (f : B ≃ₐ[A] C) : is_cyclotomic_extension S A C := begin letI : algebra B C := f.to_alg_hom.to_ring_hom.to_algebra, haveI : is_cyclotomic_extension {1} B C := singleton_one_of_algebra_map_bijective f.surjective, haveI : is_scalar_tower A B C := is_scalar_tower.of_ring_hom f.to_alg_hom, exact (iff_union_singleton_one _ _ _).2 (trans S {1} A B C f.injective) end @[protected] lemma ne_zero [h : is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : ℕ) : B) := begin obtain ⟨⟨r, hr⟩, -⟩ := (iff_singleton n A B).1 h, exact hr.ne_zero' end @[protected] lemma ne_zero' [is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : ℕ) : A) := begin apply ne_zero.nat_of_ne_zero (algebra_map A B), exact ne_zero n A B, end end basic section fintype lemma finite_of_singleton [is_domain B] [h : is_cyclotomic_extension {n} A B] : module.finite A B := begin classical, rw [module.finite_def, ← top_to_submodule, ← ((iff_adjoin_eq_top _ _ _).1 h).2], refine fg_adjoin_of_finite _ (λ b hb, _), { simp only [mem_singleton_iff, exists_eq_left], have : {b : B | b ^ (n : ℕ) = 1} = (nth_roots n (1 : B)).to_finset := set.ext (λ x, ⟨λ h, by simpa using h, λ h, by simpa using h⟩), rw [this], exact (nth_roots ↑n 1).to_finset.finite_to_set }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hb, refine ⟨X ^ (n : ℕ) - 1, ⟨monic_X_pow_sub_C _ n.pos.ne.symm, by simp [hb]⟩⟩ } end /-- If `S` is finite and `is_cyclotomic_extension S A B`, then `B` is a finite `A`-algebra. -/ @[protected] lemma finite [is_domain B] [h₁ : finite S] [h₂ : is_cyclotomic_extension S A B] : module.finite A B := begin casesI nonempty_fintype S with h, unfreezingI {revert h₂ A B}, refine set.finite.induction_on (set.finite.intro h) (λ A B, _) (λ n S hn hS H A B, _), { introsI _ _ _ _ _, refine module.finite_def.2 ⟨({1} : finset B), _⟩, simp [← top_to_submodule, ← empty, to_submodule_bot] }, { introsI _ _ _ _ h, haveI : is_cyclotomic_extension S A (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) := union_left _ (insert n S) _ _ (subset_insert n S), haveI := H A (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }), haveI : module.finite (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) B, { rw [← union_singleton] at h, letI := @union_right S {n} A B _ _ _ h, exact finite_of_singleton n _ _ }, exact module.finite.trans (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) _ } end /-- A cyclotomic finite extension of a number field is a number field. -/ lemma number_field [h : number_field K] [_root_.finite S] [is_cyclotomic_extension S K L] : number_field L := { to_char_zero := char_zero_of_injective_algebra_map (algebra_map K L).injective, to_finite_dimensional := @module.finite.trans _ K L _ _ _ _ (@algebra_rat L _ (char_zero_of_injective_algebra_map (algebra_map K L).injective)) _ _ h.to_finite_dimensional (finite S K L) } localized "attribute [instance] is_cyclotomic_extension.number_field" in cyclotomic /-- A finite cyclotomic extension of an integral noetherian domain is integral -/ lemma integral [is_domain B] [is_noetherian_ring A] [_root_.finite S] [is_cyclotomic_extension S A B] : algebra.is_integral A B := is_integral_of_noetherian $ is_noetherian_of_fg_of_noetherian' $ (finite S A B).out /-- If `S` is finite and `is_cyclotomic_extension S K A`, then `finite_dimensional K A`. -/ lemma finite_dimensional (C : Type z) [_root_.finite S] [comm_ring C] [algebra K C] [is_domain C] [is_cyclotomic_extension S K C] : finite_dimensional K C := is_cyclotomic_extension.finite S K C localized "attribute [instance] is_cyclotomic_extension.finite_dimensional" in cyclotomic end fintype section variables {A B} lemma adjoin_roots_cyclotomic_eq_adjoin_nth_roots [decidable_eq B] [is_domain B] {ζ : B} {n : ℕ+} (hζ : is_primitive_root ζ n) : adjoin A ↑((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) = adjoin A {b : B | ∃ (a : ℕ+), a ∈ ({n} : set ℕ+) ∧ b ^ (a : ℕ) = 1} := begin simp only [mem_singleton_iff, exists_eq_left, map_cyclotomic], refine le_antisymm (adjoin_mono (λ x hx, _)) (adjoin_le (λ x hx, _)), { simp only [multiset.mem_to_finset, finset.mem_coe, map_cyclotomic, mem_roots (cyclotomic_ne_zero n B)] at hx, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq], rw is_root_of_unity_iff n.pos, exact ⟨n, nat.mem_divisors_self n n.ne_zero, hx⟩ }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx, obtain ⟨i, hin, rfl⟩ := hζ.eq_pow_of_pow_eq_one hx n.pos, refine set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin _) _), rwa [finset.mem_coe, multiset.mem_to_finset, mem_roots $ cyclotomic_ne_zero n B], exact hζ.is_root_cyclotomic n.pos } end lemma adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic {n : ℕ+} [decidable_eq B] [is_domain B] {ζ : B} (hζ : is_primitive_root ζ n) : adjoin A (((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) : set B) = adjoin A ({ζ}) := begin refine le_antisymm (adjoin_le (λ x hx, _)) (adjoin_mono (λ x hx, _)), { suffices hx : x ^ ↑n = 1, obtain ⟨i, hin, rfl⟩ := hζ.eq_pow_of_pow_eq_one hx n.pos, exact set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin $ mem_singleton ζ) _), rw is_root_of_unity_iff n.pos, refine ⟨n, nat.mem_divisors_self n n.ne_zero, _⟩, rwa [finset.mem_coe, multiset.mem_to_finset, map_cyclotomic, mem_roots $ cyclotomic_ne_zero n B] at hx }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx, simpa only [hx, multiset.mem_to_finset, finset.mem_coe, map_cyclotomic, mem_roots (cyclotomic_ne_zero n B)] using hζ.is_root_cyclotomic n.pos } end lemma adjoin_primitive_root_eq_top {n : ℕ+} [is_domain B] [h : is_cyclotomic_extension {n} A B] {ζ : B} (hζ : is_primitive_root ζ n) : adjoin A ({ζ} : set B) = ⊤ := begin classical, rw ←adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic hζ, rw adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ, exact ((iff_adjoin_eq_top {n} A B).mp h).2, end variable (A) lemma _root_.is_primitive_root.adjoin_is_cyclotomic_extension {ζ : B} {n : ℕ+} (h : is_primitive_root ζ n) : is_cyclotomic_extension {n} A (adjoin A ({ζ} : set B)) := { exists_prim_root := λ i hi, begin rw [set.mem_singleton_iff] at hi, refine ⟨⟨ζ, subset_adjoin $ set.mem_singleton ζ⟩, _⟩, rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk, hi], end, adjoin_roots := λ x, begin refine adjoin_induction' (λ b hb, _) (λ a, _) (λ b₁ b₂ hb₁ hb₂, _) (λ b₁ b₂ hb₁ hb₂, _) x, { rw [set.mem_singleton_iff] at hb, refine subset_adjoin _, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq, hb], rw [← subalgebra.coe_eq_one, subalgebra.coe_pow, set_like.coe_mk], exact ((is_primitive_root.iff_def ζ n).1 h).1 }, { exact subalgebra.algebra_map_mem _ _ }, { exact subalgebra.add_mem _ hb₁ hb₂ }, { exact subalgebra.mul_mem _ hb₁ hb₂ } end } end section field variables {n S} /-- A cyclotomic extension splits `X ^ n - 1` if `n ∈ S`.-/ lemma splits_X_pow_sub_one [H : is_cyclotomic_extension S K L] (hS : n ∈ S) : splits (algebra_map K L) (X ^ (n : ℕ) - 1) := begin rw [← splits_id_iff_splits, polynomial.map_sub, polynomial.map_one, polynomial.map_pow, polynomial.map_X], obtain ⟨z, hz⟩ := ((is_cyclotomic_extension_iff _ _ _).1 H).1 hS, exact X_pow_sub_one_splits hz, end /-- A cyclotomic extension splits `cyclotomic n K` if `n ∈ S` and `ne_zero (n : K)`.-/ lemma splits_cyclotomic [is_cyclotomic_extension S K L] (hS : n ∈ S) : splits (algebra_map K L) (cyclotomic n K) := begin refine splits_of_splits_of_dvd _ (X_pow_sub_C_ne_zero n.pos _) (splits_X_pow_sub_one K L hS) _, use (∏ (i : ℕ) in (n : ℕ).proper_divisors, polynomial.cyclotomic i K), rw [(eq_cyclotomic_iff n.pos _).1 rfl, ring_hom.map_one], end variables (n S) section singleton variables [is_cyclotomic_extension {n} K L] /-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `X ^ n - 1`. -/ lemma splitting_field_X_pow_sub_one : is_splitting_field K L (X ^ (n : ℕ) - 1) := { splits := splits_X_pow_sub_one K L (mem_singleton n), adjoin_roots := begin rw [← ((iff_adjoin_eq_top {n} K L).1 infer_instance).2], congr, refine set.ext (λ x, _), simp only [polynomial.map_pow, mem_singleton_iff, multiset.mem_to_finset, exists_eq_left, mem_set_of_eq, polynomial.map_X, polynomial.map_one, finset.mem_coe, polynomial.map_sub], rwa [← ring_hom.map_one C, mem_roots (@X_pow_sub_C_ne_zero L _ _ _ n.pos _), is_root.def, eval_sub, eval_pow, eval_C, eval_X, sub_eq_zero] end } /-- Any two `n`-th cyclotomic extensions are isomorphic. -/ def alg_equiv (L' : Type*) [field L'] [algebra K L'] [is_cyclotomic_extension {n} K L'] : L ≃ₐ[K] L' := let _ := splitting_field_X_pow_sub_one n K L in let _ := splitting_field_X_pow_sub_one n K L' in by exactI (is_splitting_field.alg_equiv L (X ^ (n : ℕ) - 1)).trans (is_splitting_field.alg_equiv L' (X ^ (n : ℕ) - 1)).symm localized "attribute [instance] is_cyclotomic_extension.splitting_field_X_pow_sub_one" in cyclotomic include n lemma is_galois : is_galois K L := begin letI := splitting_field_X_pow_sub_one n K L, exact is_galois.of_separable_splitting_field (X_pow_sub_one_separable_iff.2 ((ne_zero' n K L).1)) end localized "attribute [instance] is_cyclotomic_extension.is_galois" in cyclotomic /-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `cyclotomic n K`. -/ lemma splitting_field_cyclotomic : is_splitting_field K L (cyclotomic n K) := { splits := splits_cyclotomic K L (mem_singleton n), adjoin_roots := begin rw [← ((iff_adjoin_eq_top {n} K L).1 infer_instance).2], letI := classical.dec_eq L, obtain ⟨ζ, hζ⟩ := @is_cyclotomic_extension.exists_prim_root {n} K L _ _ _ _ _ (mem_singleton n), exact adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ end } localized "attribute [instance] is_cyclotomic_extension.splitting_field_cyclotomic" in cyclotomic end singleton end field end is_cyclotomic_extension section cyclotomic_field /-- Given `n : ℕ+` and a field `K`, we define `cyclotomic_field n K` as the splitting field of `cyclotomic n K`. If `n` is nonzero in `K`, it has the instance `is_cyclotomic_extension {n} K (cyclotomic_field n K)`. -/ @[derive [field, algebra K, inhabited]] def cyclotomic_field : Type w := (cyclotomic n K).splitting_field namespace cyclotomic_field instance [char_zero K] : char_zero (cyclotomic_field n K) := char_zero_of_injective_algebra_map ((algebra_map K _).injective) instance is_cyclotomic_extension [ne_zero ((n : ℕ) : K)] : is_cyclotomic_extension {n} K (cyclotomic_field n K) := { exists_prim_root := λ a han, begin rw mem_singleton_iff at han, subst a, obtain ⟨r, hr⟩ := exists_root_of_splits (algebra_map K (cyclotomic_field n K)) (splitting_field.splits _) (degree_cyclotomic_pos n K (n.pos)).ne', refine ⟨r, _⟩, haveI := ne_zero.of_no_zero_smul_divisors K (cyclotomic_field n K) n, rwa [← eval_map, ← is_root.def, map_cyclotomic, is_root_cyclotomic_iff] at hr end, adjoin_roots := begin rw [←algebra.eq_top_iff, ←splitting_field.adjoin_roots, eq_comm], letI := classical.dec_eq (cyclotomic_field n K), obtain ⟨ζ, hζ⟩ := exists_root_of_splits _ (splitting_field.splits (cyclotomic n K)) (degree_cyclotomic_pos n _ n.pos).ne', haveI : ne_zero ((n : ℕ) : (cyclotomic_field n K)) := ne_zero.nat_of_injective (algebra_map K _).injective, rw [eval₂_eq_eval_map, map_cyclotomic, ← is_root.def, is_root_cyclotomic_iff] at hζ, exact is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ, end } end cyclotomic_field end cyclotomic_field section is_domain variables [is_domain A] [algebra A K] [is_fraction_ring A K] section cyclotomic_ring /-- If `K` is the fraction field of `A`, the `A`-algebra structure on `cyclotomic_field n K`. This is not an instance since it causes diamonds when `A = ℤ`. -/ @[nolint unused_arguments] def cyclotomic_field.algebra_base : algebra A (cyclotomic_field n K) := ((algebra_map K (cyclotomic_field n K)).comp (algebra_map A K)).to_algebra local attribute [instance] cyclotomic_field.algebra_base instance cyclotomic_field.no_zero_smul_divisors : no_zero_smul_divisors A (cyclotomic_field n K) := no_zero_smul_divisors.of_algebra_map_injective $ function.injective.comp (no_zero_smul_divisors.algebra_map_injective _ _) $ is_fraction_ring.injective A K /-- If `A` is a domain with fraction field `K` and `n : ℕ+`, we define `cyclotomic_ring n A K` as the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of `X ^ n - 1`. If `n` is nonzero in `A`, it has the instance `is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`. -/ @[derive [comm_ring, is_domain, inhabited]] def cyclotomic_ring : Type w := adjoin A { b : (cyclotomic_field n K) | b ^ (n : ℕ) = 1 } namespace cyclotomic_ring /-- The `A`-algebra structure on `cyclotomic_ring n A K`. This is not an instance since it causes diamonds when `A = ℤ`. -/ def algebra_base : algebra A (cyclotomic_ring n A K) := (adjoin A _).algebra local attribute [instance] cyclotomic_ring.algebra_base instance : no_zero_smul_divisors A (cyclotomic_ring n A K) := (adjoin A _).no_zero_smul_divisors_bot lemma algebra_base_injective : function.injective $ algebra_map A (cyclotomic_ring n A K) := no_zero_smul_divisors.algebra_map_injective _ _ instance : algebra (cyclotomic_ring n A K) (cyclotomic_field n K) := (adjoin A _).to_algebra lemma adjoin_algebra_injective : function.injective $ algebra_map (cyclotomic_ring n A K) (cyclotomic_field n K) := subtype.val_injective instance : no_zero_smul_divisors (cyclotomic_ring n A K) (cyclotomic_field n K) := no_zero_smul_divisors.of_algebra_map_injective (adjoin_algebra_injective n A K) instance : is_scalar_tower A (cyclotomic_ring n A K) (cyclotomic_field n K) := is_scalar_tower.subalgebra' _ _ _ _ instance is_cyclotomic_extension [ne_zero ((n : ℕ) : A)] : is_cyclotomic_extension {n} A (cyclotomic_ring n A K) := { exists_prim_root := λ a han, begin rw mem_singleton_iff at han, subst a, haveI := ne_zero.of_no_zero_smul_divisors A K n, haveI := ne_zero.of_no_zero_smul_divisors A (cyclotomic_field n K) n, obtain ⟨μ, hμ⟩ := (cyclotomic_field.is_cyclotomic_extension n K).exists_prim_root (mem_singleton n), refine ⟨⟨μ, subset_adjoin _⟩, _⟩, { apply (is_root_of_unity_iff n.pos (cyclotomic_field n K)).mpr, refine ⟨n, nat.mem_divisors_self _ n.ne_zero, _⟩, rwa [← is_root_cyclotomic_iff] at hμ }, { rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] } end, adjoin_roots := λ x, begin refine adjoin_induction' (λ y hy, _) (λ a, _) (λ y z hy hz, _) (λ y z hy hz, _) x, { refine subset_adjoin _, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq], rwa [← subalgebra.coe_eq_one, subalgebra.coe_pow, subtype.coe_mk] }, { exact subalgebra.algebra_map_mem _ a }, { exact subalgebra.add_mem _ hy hz }, { exact subalgebra.mul_mem _ hy hz }, end } instance [ne_zero ((n : ℕ) : A)] : is_fraction_ring (cyclotomic_ring n A K) (cyclotomic_field n K) := { map_units := λ ⟨x, hx⟩, begin rw is_unit_iff_ne_zero, apply map_ne_zero_of_mem_non_zero_divisors, apply adjoin_algebra_injective, exact hx end, surj := λ x, begin letI : ne_zero ((n : ℕ) : K) := ne_zero.nat_of_injective (is_fraction_ring.injective A K), refine algebra.adjoin_induction (((is_cyclotomic_extension.iff_singleton n K _).1 (cyclotomic_field.is_cyclotomic_extension n K)).2 x) (λ y hy, _) (λ k, _) _ _, { exact ⟨⟨⟨y, subset_adjoin hy⟩, 1⟩, by simpa⟩ }, { have : is_localization (non_zero_divisors A) K := infer_instance, replace := this.surj, obtain ⟨⟨z, w⟩, hw⟩ := this k, refine ⟨⟨algebra_map A _ z, algebra_map A _ w, map_mem_non_zero_divisors _ (algebra_base_injective n A K) w.2⟩, _⟩, letI : is_scalar_tower A K (cyclotomic_field n K) := is_scalar_tower.of_algebra_map_eq (congr_fun rfl), rw [set_like.coe_mk, ← is_scalar_tower.algebra_map_apply, ← is_scalar_tower.algebra_map_apply, @is_scalar_tower.algebra_map_apply A K _ _ _ _ _ (_root_.cyclotomic_field.algebra n K) _ _ w, ← ring_hom.map_mul, hw, ← is_scalar_tower.algebra_map_apply] }, { rintro y z ⟨a, ha⟩ ⟨b, hb⟩, refine ⟨⟨a.1 * b.2 + b.1 * a.2, a.2 * b.2, mul_mem_non_zero_divisors.2 ⟨a.2.2, b.2.2⟩⟩, _⟩, rw [set_like.coe_mk, ring_hom.map_mul, add_mul, ← mul_assoc, ha, mul_comm ((algebra_map _ _) ↑a.2), ← mul_assoc, hb], simp only [map_add, map_mul] }, { rintro y z ⟨a, ha⟩ ⟨b, hb⟩, refine ⟨⟨a.1 * b.1, a.2 * b.2, mul_mem_non_zero_divisors.2 ⟨a.2.2, b.2.2⟩⟩, _⟩, rw [set_like.coe_mk, ring_hom.map_mul, mul_comm ((algebra_map _ _) ↑a.2), mul_assoc, ← mul_assoc z, hb, ← mul_comm ((algebra_map _ _) ↑a.2), ← mul_assoc, ha], simp only [map_mul] } end, eq_iff_exists := λ x y, ⟨λ h, ⟨1, by rw adjoin_algebra_injective n A K h⟩, λ ⟨c, hc⟩, by rw mul_right_cancel₀ (non_zero_divisors.ne_zero c.prop) hc⟩ } lemma eq_adjoin_primitive_root {μ : (cyclotomic_field n K)} (h : is_primitive_root μ n) : cyclotomic_ring n A K = adjoin A ({μ} : set ((cyclotomic_field n K))) := begin letI := classical.prop_decidable, rw [←is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic h, is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots h], simp [cyclotomic_ring] end end cyclotomic_ring end cyclotomic_ring end is_domain section is_alg_closed variables [is_alg_closed K] /-- Algebraically closed fields are `S`-cyclotomic extensions over themselves if `ne_zero ((a : ℕ) : K))` for all `a ∈ S`. -/ lemma is_alg_closed.is_cyclotomic_extension (h : ∀ a ∈ S, ne_zero ((a : ℕ) : K)) : is_cyclotomic_extension S K K := begin refine ⟨λ a ha, _, algebra.eq_top_iff.mp $ subsingleton.elim _ _ ⟩, obtain ⟨r, hr⟩ := is_alg_closed.exists_aeval_eq_zero K _ (degree_cyclotomic_pos a K a.pos).ne', refine ⟨r, _⟩, haveI := h a ha, rwa [coe_aeval_eq_eval, ← is_root.def, is_root_cyclotomic_iff] at hr, end instance is_alg_closed_of_char_zero.is_cyclotomic_extension [char_zero K] : ∀ S, is_cyclotomic_extension S K K := λ S, is_alg_closed.is_cyclotomic_extension S K (λ a ha, infer_instance) end is_alg_closed
62ef7bd40a209484c4dd4f0114d9f096fe2eb1c5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/homotopies.lean
5bc1fd2472a283946e834fa863e5bbb6a127bc8b
[ "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
8,038
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebra.homology.homotopy import algebraic_topology.dold_kan.notations /-! # Construction of homotopies for the Dold-Kan correspondence TODO (@joelriou) continue adding the various files referenced below (The general strategy of proof of the Dold-Kan correspondence is explained in `equivalence.lean`.) The purpose of the files `homotopies.lean`, `faces.lean`, `projections.lean` and `p_infty.lean` is to construct an idempotent endomorphism `P_infty : K[X] ⟶ K[X]` of the alternating face map complex for each `X : simplicial_object C` when `C` is a preadditive category. In the case `C` is abelian, this `P_infty` shall be the projection on the normalized Moore subcomplex of `K[X]` associated to the decomposition of the complex `K[X]` as a direct sum of this normalized subcomplex and of the degenerate subcomplex. In `p_infty.lean`, this endomorphism `P_infty` shall be obtained by passing to the limit idempotent endomorphisms `P q` for all `(q : ℕ)`. These endomorphisms `P q` are defined by induction. The idea is to start from the identity endomorphism `P 0` of `K[X]` and to ensure by induction that the `q` higher face maps (except $d_0$) vanish on the image of `P q`. Then, in a certain degree `n`, the image of `P q` for a big enough `q` will be contained in the normalized subcomplex. This construction is done in `projections.lean`. It would be easy to define the `P q` degreewise (similarly as it is done in *Simplicial Homotopy Theory* by Goerrs-Jardine p. 149), but then we would have to prove that they are compatible with the differential (i.e. they are chain complex maps), and also that they are homotopic to the identity. These two verifications are quite technical. In order to reduce the number of such technical lemmas, the strategy that is followed here is to define a series of null homotopic maps `Hσ q` (attached to families of maps `hσ`) and use these in order to construct `P q` : the endomorphisms `P q` shall basically be obtained by altering the identity endomorphism by adding null homotopic maps, so that we get for free that they are morphisms of chain complexes and that they are homotopic to the identity. The most technical verifications that are needed about the null homotopic maps `Hσ` are obtained in `faces.lean`. In this file `homotopies.lean`, we define the null homotopic maps `Hσ q : K[X] ⟶ K[X]`, show that they are natural (see `nat_trans_Hσ`) and compatible the application of additive functors (see `map_Hσ`). ## References * [Albrecht Dold, *Homology of Symmetric Products and Other Functors of Complexes*][dold1958] * [Paul G. Goerss, John F. Jardine, *Simplical Homotopy Theory*][goerss-jardine-2009] -/ open category_theory open category_theory.category open category_theory.limits open category_theory.preadditive open category_theory.simplicial_object open homotopy open opposite open_locale simplicial dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] variables {X : simplicial_object C} /-- As we are using chain complexes indexed by `ℕ`, we shall need the relation `c` such `c m n` if and only if `n+1=m`. -/ abbreviation c := complex_shape.down ℕ /-- Helper when we need some `c.rel i j` (i.e. `complex_shape.down ℕ`), e.g. `c_mk n (n+1) rfl` -/ lemma c_mk (i j : ℕ) (h : j+1 = i) : c.rel i j := complex_shape.down_mk i j h /-- This lemma is meant to be used with `null_homotopic_map'_f_of_not_rel_left` -/ lemma cs_down_0_not_rel_left (j : ℕ) : ¬c.rel 0 j := begin intro hj, dsimp at hj, apply nat.not_succ_le_zero j, rw [nat.succ_eq_add_one, hj], end /-- The sequence of maps which gives the null homotopic maps `Hσ` that shall be in the inductive construction of the projections `P q : K[X] ⟶ K[X]` -/ def hσ (q : ℕ) (n : ℕ) : X _[n] ⟶ X _[n+1] := if n<q then 0 else (-1 : ℤ)^(n-q) • X.σ ⟨n-q, nat.sub_lt_succ n q⟩ /-- We can turn `hσ` into a datum that can be passed to `null_homotopic_map'`. -/ def hσ' (q : ℕ) : Π n m, c.rel m n → (K[X].X n ⟶ K[X].X m) := λ n m hnm, (hσ q n) ≫ eq_to_hom (by congr') lemma hσ'_eq_zero {q n m : ℕ} (hnq : n<q) (hnm : c.rel m n) : (hσ' q n m hnm : X _[n] ⟶ X _[m])= 0 := by { simp only [hσ', hσ], split_ifs, exact zero_comp, } lemma hσ'_eq {q n a m : ℕ} (ha : n=a+q) (hnm : c.rel m n) : (hσ' q n m hnm : X _[n] ⟶ X _[m]) = ((-1 : ℤ)^a • X.σ ⟨a, nat.lt_succ_iff.mpr (nat.le.intro (eq.symm ha))⟩) ≫ eq_to_hom (by congr') := begin simp only [hσ', hσ], split_ifs, { exfalso, linarith, }, { have h' := tsub_eq_of_eq_add ha, congr', } end lemma hσ'_eq' {q n a : ℕ} (ha : n=a+q) : (hσ' q n (n+1) rfl : X _[n] ⟶ X _[n+1]) = (-1 : ℤ)^a • X.σ ⟨a, nat.lt_succ_iff.mpr (nat.le.intro (eq.symm ha))⟩ := by rw [hσ'_eq ha rfl, eq_to_hom_refl, comp_id] /-- The null homotopic map $(hσ q) ∘ d + d ∘ (hσ q)$ -/ def Hσ (q : ℕ) : K[X] ⟶ K[X] := null_homotopic_map' (hσ' q) /-- `Hσ` is null homotopic -/ def homotopy_Hσ_to_zero (q : ℕ) : homotopy (Hσ q : K[X] ⟶ K[X]) 0 := null_homotopy' (hσ' q) /-- In degree `0`, the null homotopic map `Hσ` is zero. -/ lemma Hσ_eq_zero (q : ℕ) : (Hσ q : K[X] ⟶ K[X]).f 0 = 0 := begin unfold Hσ, rw null_homotopic_map'_f_of_not_rel_left (c_mk 1 0 rfl) cs_down_0_not_rel_left, cases q, { rw hσ'_eq (show 0=0+0, by refl) (c_mk 1 0 rfl), simp only [pow_zero, fin.mk_zero, one_zsmul, eq_to_hom_refl, category.comp_id], erw chain_complex.of_d, simp only [alternating_face_map_complex.obj_d, fin.sum_univ_two, fin.coe_zero, pow_zero, one_zsmul, fin.coe_one, pow_one, comp_add, neg_smul, one_zsmul, comp_neg, add_neg_eq_zero], erw [δ_comp_σ_self, δ_comp_σ_succ], }, { rw [hσ'_eq_zero (nat.succ_pos q) (c_mk 1 0 rfl), zero_comp], }, end /-- The maps `hσ' q n m hnm` are natural on the simplicial object -/ lemma hσ'_naturality (q : ℕ) (n m : ℕ) (hnm : c.rel m n) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ hσ' q n m hnm = hσ' q n m hnm ≫ f.app (op [m]) := begin have h : n+1 = m := hnm, subst h, simp only [hσ', eq_to_hom_refl, comp_id], unfold hσ, split_ifs, { rw [zero_comp, comp_zero], }, { simp only [zsmul_comp, comp_zsmul], erw f.naturality, refl, }, end /-- For each q, `Hσ q` is a natural transformation. -/ def nat_trans_Hσ (q : ℕ) : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ X, Hσ q, naturality' := λ X Y f, begin unfold Hσ, rw [null_homotopic_map'_comp, comp_null_homotopic_map'], congr, ext n m hnm, simp only [alternating_face_map_complex_map_f, hσ'_naturality], end, } /-- The maps `hσ' q n m hnm` are compatible with the application of additive functors. -/ lemma map_hσ' {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n m : ℕ) (hnm : c.rel m n) : (hσ' q n m hnm : K[((whiskering _ _).obj G).obj X].X n ⟶ _) = G.map (hσ' q n m hnm : K[X].X n ⟶ _) := begin unfold hσ' hσ, split_ifs, { simp only [functor.map_zero, zero_comp], }, { simpa only [eq_to_hom_map, functor.map_comp, functor.map_zsmul], }, end /-- The null homotopic maps `Hσ` are compatible with the application of additive functors. -/ lemma map_Hσ {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n : ℕ) : (Hσ q : K[((whiskering C D).obj G).obj X] ⟶ _).f n = G.map ((Hσ q : K[X] ⟶ _).f n) := begin unfold Hσ, have eq := homological_complex.congr_hom (map_null_homotopic_map' G (hσ' q)) n, simp only [functor.map_homological_complex_map_f, ← map_hσ'] at eq, rw eq, let h := (functor.congr_obj (map_alternating_face_map_complex G) X).symm, congr', end end dold_kan end algebraic_topology
903be65f059d602ff6ff75aa18e31af9d5d40f2a
0d9b0a832bc57849732c5bd008a7a142f7e49656
/src/XSokoban_90_l1_dl.lean
48c3e84a8a59851c91780bd7d5344d04b34d3905
[]
no_license
mirefek/sokoban.lean
bb9414af67894e4d8ce75f8c8d7031df02d371d0
451c92308afb4d3f8e566594b9751286f93b899b
refs/heads/master
1,681,025,245,267
1,618,997,832,000
1,618,997,832,000
359,491,681
10
0
null
null
null
null
UTF-8
Lean
false
false
12,941
lean
-- Deadlocks: var/XSokoban_90_l1/deadlocks -- Levelset: data/Large Test Suite Sets/XSokoban_90.xsb -- Level: 1 import .deadlocks def XSokoban_90_l1 := sokolevel.from_string " ##### # # #$ # ### $## # $ $ # ### # ## # ###### # # ## ##### ..# # $ $ ..# ##### ### #@## ..# # ######### ####### " namespace XSokoban_90_l1 open deadlocks @[reducible] def deadlock_local (dl : boxint) : Prop := deadlock XSokoban_90_l1.avail XSokoban_90_l1.goal dl def deadlocks_local (dls : list boxint) : Prop := dls.pall (λ dl, deadlock_local dl) def generate_local : list (ℕ × ℕ) → list (ℕ × ℕ) → ℕ × ℕ → boxint := boxint.generate_from_list XSokoban_90_l1.avail def dl0 := generate_local [(8,5)] [] (5,2) theorem dl0_dl : deadlock_local dl0 := begin apply new_deadlock, analyze_deadlock, end #check dl0_dl def dl1 := generate_local [(3,5)] [] (5,2) theorem dl1_dl : deadlock_local dl1 := begin apply new_deadlock, analyze_deadlock, end #check dl1_dl def dl2 := generate_local [(14,9)] [] (5,2) theorem dl2_dl : deadlock_local dl2 := begin apply new_deadlock, analyze_deadlock, end #check dl2_dl def dl3 := generate_local [(5,10)] [] (5,2) theorem dl3_dl : deadlock_local dl3 := begin apply new_deadlock, analyze_deadlock, end #check dl3_dl def dl4 := generate_local [(6,5), (7,5)] [] (5,2) theorem dl4_dl : deadlock_local dl4 := begin apply new_deadlock, analyze_deadlock, end #check dl4_dl def dl5 := generate_local [(15,9), (16,9)] [] (5,2) theorem dl5_dl : deadlock_local dl5 := begin apply new_deadlock, analyze_deadlock, end #check dl5_dl def dl6 := generate_local [(5,2)] [] (6,2) theorem dl6_dl : deadlock_local dl6 := begin apply new_deadlock, analyze_deadlock, end #check dl6_dl def dl7 := generate_local [(1,8)] [] (5,2) theorem dl7_dl : deadlock_local dl7 := begin apply new_deadlock, analyze_deadlock, end #check dl7_dl def dl8 := generate_local [(7,2)] [] (5,2) theorem dl8_dl : deadlock_local dl8 := begin apply new_deadlock, analyze_deadlock, end #check dl8_dl def dl9 := generate_local [(5,5), (6,5), (5,6)] [] (5,2) theorem dl9_dl : deadlock_local dl9 := begin apply new_deadlock, analyze_deadlock, end #check dl9_dl def dl10 := generate_local [(5,4), (5,5), (6,5)] [] (5,2) theorem dl10_dl : deadlock_local dl10 := begin apply new_deadlock, analyze_deadlock, end #check dl10_dl def dl11 := generate_local [(5,4), (5,5), (7,5)] [] (3,5) theorem dl11_dl : deadlock_local dl11 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl4_dl, -- (5,5) right deadlocked_step dl10_dl, -- (7,5) left end #check dl11_dl def dl12 := generate_local [(5,6), (5,7)] [] (5,2) theorem dl12_dl : deadlock_local dl12 := begin apply new_deadlock, analyze_deadlock, end #check dl12_dl def dl13 := generate_local [(5,5), (6,5), (5,7)] [] (5,2) theorem dl13_dl : deadlock_local dl13 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl12_dl, -- (5,5) down deadlocked_step dl9_dl, -- (5,7) up end #check dl13_dl def dl14 := generate_local [(5,3), (5,4)] [] (5,2) theorem dl14_dl : deadlock_local dl14 := begin apply new_deadlock, analyze_deadlock, end #check dl14_dl def dl15 := generate_local [(5,4), (7,4), (6,5), (5,6)] [] (5,2) theorem dl15_dl : deadlock_local dl15 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl9_dl, -- (5,4) down deadlocked_step dl4_dl, -- (7,4) down end #check dl15_dl def dl16 := generate_local [(5,5), (7,5), (5,6)] [] (3,5) theorem dl16_dl : deadlock_local dl16 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl4_dl, -- (5,5) right deadlocked_step dl9_dl, -- (7,5) left end #check dl16_dl def dl17 := generate_local [(5,5), (7,5), (5,7)] [] (3,5) theorem dl17_dl : deadlock_local dl17 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl4_dl, -- (5,5) right deadlocked_step dl13_dl, -- (7,5) left deadlocked_step dl16_dl, -- (5,7) up end #check dl17_dl def dl18 := generate_local [(4,5), (7,5), (5,7), (5,8)] [] (5,2) theorem dl18_dl : deadlock_local dl18 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl1_dl, -- (4,5) left deadlocked_step dl0_dl, -- (7,5) right end #check dl18_dl def dl19 := generate_local [(4,5), (7,5), (5,6), (5,8)] [] (5,2) theorem dl19_dl : deadlock_local dl19 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl1_dl, -- (4,5) left deadlocked_step dl0_dl, -- (7,5) right deadlocked_step dl18_dl, -- (5,6) down end #check dl19_dl def dl20 := generate_local [(4,5), (5,5), (5,6)] [] (5,2) theorem dl20_dl : deadlock_local dl20 := begin apply new_deadlock, analyze_deadlock, end #check dl20_dl def dl21 := generate_local [(4,5), (5,5), (5,7)] [] (5,2) theorem dl21_dl : deadlock_local dl21 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl12_dl, -- (5,5) down deadlocked_step dl20_dl, -- (5,7) up end #check dl21_dl def dl22 := generate_local [(2,8), (3,8)] [] (5,2) theorem dl22_dl : deadlock_local dl22 := begin apply new_deadlock, analyze_deadlock, end #check dl22_dl def dl23 := generate_local [(4,5), (2,8), (4,8)] [] (5,2) theorem dl23_dl : deadlock_local dl23 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl1_dl, -- (4,5) left deadlocked_step dl22_dl, -- (4,8) left end #check dl23_dl def dl24 := generate_local [(5,7), (4,8), (5,8)] [] (5,2) theorem dl24_dl : deadlock_local dl24 := begin apply new_deadlock, analyze_deadlock, end #check dl24_dl def dl25 := generate_local [(5,6), (4,8), (5,8)] [] (5,2) theorem dl25_dl : deadlock_local dl25 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl24_dl, -- (5,6) down deadlocked_step dl12_dl, -- (5,8) up end #check dl25_dl def dl26 := generate_local [(5,4), (4,5), (5,5)] [] (5,2) theorem dl26_dl : deadlock_local dl26 := begin apply new_deadlock, analyze_deadlock, end #check dl26_dl def dl27 := generate_local [(4,5), (5,5), (7,5), (5,8)] [] (5,2) theorem dl27_dl : deadlock_local dl27 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl19_dl, -- (5,5) down deadlocked_step dl0_dl, -- (7,5) right end #check dl27_dl def dl28 := generate_local [(4,5), (5,7), (2,8), (5,8)] [] (5,2) theorem dl28_dl : deadlock_local dl28 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl1_dl, -- (4,5) left deadlocked_step dl23_dl, -- (5,8) left end #check dl28_dl def dl29 := generate_local [(4,5), (5,6), (2,8), (5,8)] [] (5,2) theorem dl29_dl : deadlock_local dl29 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl1_dl, -- (4,5) left deadlocked_step dl28_dl, -- (5,6) down deadlocked_step dl12_dl, -- (5,8) up deadlocked_step dl23_dl, -- (5,8) left end #check dl29_dl def dl30 := generate_local [(3,8), (4,8)] [] (5,2) theorem dl30_dl : deadlock_local dl30 := begin apply new_deadlock, analyze_deadlock, end #check dl30_dl def dl31 := generate_local [(14,7)] [] (5,2) theorem dl31_dl : deadlock_local dl31 := begin apply new_deadlock, analyze_deadlock, end #check dl31_dl def dl32 := generate_local [(5,4), (5,5), (2,8), (4,8)] [] (5,2) theorem dl32_dl : deadlock_local dl32 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl23_dl, -- (5,5) left deadlocked_step dl22_dl, -- (4,8) left end #check dl32_dl def dl33 := generate_local [(5,5), (5,6), (2,8), (4,8)] [] (5,2) theorem dl33_dl : deadlock_local dl33 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl23_dl, -- (5,5) left deadlocked_step dl22_dl, -- (4,8) left end #check dl33_dl def dl34 := generate_local [(6,8), (7,8)] [] (5,2) theorem dl34_dl : deadlock_local dl34 := begin apply new_deadlock, analyze_deadlock, end #check dl34_dl def dl35 := generate_local [(7,8), (8,8)] [] (5,2) theorem dl35_dl : deadlock_local dl35 := begin apply new_deadlock, analyze_deadlock, end #check dl35_dl def dl36 := generate_local [(6,8), (8,8)] [] (5,2) theorem dl36_dl : deadlock_local dl36 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl35_dl, -- (6,8) right deadlocked_step dl34_dl, -- (8,8) left end #check dl36_dl def dl37 := generate_local [(5,7), (5,8), (8,8)] [] (5,2) theorem dl37_dl : deadlock_local dl37 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl36_dl, -- (5,8) right end #check dl37_dl def dl38 := generate_local [(5,6), (5,8), (8,8)] [] (5,2) theorem dl38_dl : deadlock_local dl38 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl37_dl, -- (5,6) down deadlocked_step dl36_dl, -- (5,8) right end #check dl38_dl def dl39 := generate_local [(4,5), (5,5), (5,8), (8,8)] [] (5,2) theorem dl39_dl : deadlock_local dl39 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl38_dl, -- (5,5) down end #check dl39_dl def dl40 := generate_local [(5,7), (5,8), (6,8)] [] (5,2) theorem dl40_dl : deadlock_local dl40 := begin apply new_deadlock, analyze_deadlock, end #check dl40_dl def dl41 := generate_local [(5,7), (5,8), (7,8)] [] (5,2) theorem dl41_dl : deadlock_local dl41 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl34_dl, -- (5,8) right deadlocked_step dl40_dl, -- (7,8) left end #check dl41_dl def dl42 := generate_local [(5,6), (5,8), (6,8)] [] (5,2) theorem dl42_dl : deadlock_local dl42 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl40_dl, -- (5,6) down deadlocked_step dl12_dl, -- (5,8) up end #check dl42_dl def dl43 := generate_local [(5,6), (5,8), (7,8)] [] (5,2) theorem dl43_dl : deadlock_local dl43 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl41_dl, -- (5,6) down deadlocked_step dl12_dl, -- (5,8) up deadlocked_step dl34_dl, -- (5,8) right deadlocked_step dl42_dl, -- (7,8) left end #check dl43_dl def dl44 := generate_local [(5,6), (5,8), (8,8)] [] (14,7) theorem dl44_dl : deadlock_local dl44 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl12_dl, -- (5,8) up deadlocked_step dl43_dl, -- (8,8) left end #check dl44_dl def dl45 := generate_local [(5,6), (5,8), (9,8)] [] (14,7) theorem dl45_dl : deadlock_local dl45 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl44_dl, -- (9,8) left end #check dl45_dl def dl46 := generate_local [(5,6), (5,8), (10,8)] [] (14,7) theorem dl46_dl : deadlock_local dl46 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl45_dl, -- (10,8) left end #check dl46_dl def dl47 := generate_local [(5,6), (5,8), (11,8)] [] (14,7) theorem dl47_dl : deadlock_local dl47 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl46_dl, -- (11,8) left end #check dl47_dl def dl48 := generate_local [(5,6), (5,8), (12,8)] [] (14,7) theorem dl48_dl : deadlock_local dl48 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl47_dl, -- (12,8) left end #check dl48_dl def dl49 := generate_local [(5,6), (5,8), (13,8)] [] (14,7) theorem dl49_dl : deadlock_local dl49 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl48_dl, -- (13,8) left end #check dl49_dl def dl50 := generate_local [(5,6), (5,8), (14,8)] [] (14,7) theorem dl50_dl : deadlock_local dl50 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl31_dl, -- (14,8) up deadlocked_step dl2_dl, -- (14,8) down deadlocked_step dl49_dl, -- (14,8) left end #check dl50_dl def dl51 := generate_local [(5,5), (5,6), (2,8), (5,8)] [] (5,2) theorem dl51_dl : deadlock_local dl51 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl29_dl, -- (5,5) left deadlocked_step dl12_dl, -- (5,8) up deadlocked_step dl33_dl, -- (5,8) left end #check dl51_dl def dl52 := generate_local [(5,7), (3,8), (5,8)] [] (5,2) theorem dl52_dl : deadlock_local dl52 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl24_dl, -- (3,8) right deadlocked_step dl30_dl, -- (5,8) left end #check dl52_dl def dl53 := generate_local [(5,6), (3,8), (5,8)] [] (5,2) theorem dl53_dl : deadlock_local dl53 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl52_dl, -- (5,6) down deadlocked_step dl25_dl, -- (3,8) right deadlocked_step dl12_dl, -- (5,8) up deadlocked_step dl30_dl, -- (5,8) left end #check dl53_dl def dl54 := generate_local [(5,4), (7,4), (6,5), (5,7)] [] (5,2) theorem dl54_dl : deadlock_local dl54 := begin apply new_deadlock, analyze_deadlock, deadlocked_step dl13_dl, -- (5,4) down deadlocked_step dl4_dl, -- (7,4) down end #check dl54_dl def dl55 := generate_local [(15,7), (16,7)] [] (5,2) theorem dl55_dl : deadlock_local dl55 := begin apply new_deadlock, analyze_deadlock, end #check dl55_dl end XSokoban_90_l1
0f1323b2ac8f54724330f9f1f47906c184664eac
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/elab1.lean
1649dc47a627cef995aa1cacd47ecef6a5034a84
[ "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
381
lean
definition foo.subst := @eq.subst definition boo.subst := @eq.subst definition foo.add := @add definition boo.add := @add set_option pp.all true open foo boo #print raw subst -- subst is overloaded #print raw add -- add is overloaded #check @subst #check @@subst open eq #check subst constants a b : nat constant H1 : a = b constant H2 : a + b > 0 #check eq.subst H1 H2
9dc58d896b9e39112a1dbcaa677cc3dce97d9505
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/expander.lean
ee021238dda7b62f45e0eafdde78ea7c139589fd
[ "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,617
lean
import init.lean.expander open Lean open Lean.Parser open Lean.Expander def prof {α : Type} (msg : String) (p : IO α) : IO α := let msg₁ := "Time for '" ++ msg ++ "':" in let msg₂ := "Memory usage for '" ++ msg ++ "':" in allocprof msg₂ (timeit msg₁ p) def node : SyntaxNodeKind := ⟨`node⟩ def leaf : SyntaxNodeKind := ⟨`leaf⟩ def node.arity := 4 def mkStx : ℕ → Syntax | 0 := Syntax.mkNode leaf [] | (n+1) := Syntax.mkNode node $ (List.replicate node.arity Syntax.missing).map (λ _, mkStx n) def cfg : FrontendConfig := {filename := "foo", fileMap := FileMap.fromString "", input := ""} def test (transformers : List (Name × transformer)) (stx : Syntax) : IO Unit := match expand stx {cfg with transformers := RBMap.fromList transformers _} with | Except.ok _ := pure () | Except.error e := throw e.toString def testNoOp := test [] def testNoExp := test [(`node, λ stx, noExpansion)] def testSimple := test [(`node, λ stx, match stx.asNode with | some n := pure $ Syntax.mkNode ⟨`node2⟩ n.args | none := pure Syntax.missing)] -- direct transformation, no hygiene system partial def toNode2 : Syntax → Syntax | (Syntax.rawNode ⟨kind, as, scopes⟩) := Syntax.rawNode ⟨⟨`node2⟩, as.map toNode2, scopes⟩ | other := other def testToNode2 (stx : Syntax) : IO Syntax := pure $ toNode2 stx def main (xs : List String) : IO Unit := do let stx := mkStx 11, --xs.head.toNat, prof "testNoOp" $ testNoOp stx, prof "testNoExp" $ testNoExp stx, prof "testSimple" $ testSimple stx, prof "testToNode2" $ testToNode2 stx, pure ()
1cf8fc5ef72abaeb6c1e769007fbf03f5358224b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/schreier.lean
bf5b797a3e06ad389c95b9d4a8da84ad883c3fda
[ "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,702
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import data.finset.pointwise import group_theory.complement import group_theory.finiteness import group_theory.index import tactic.group /-! # Schreier's Lemma In this file we prove Schreier's lemma. ## Main results - `closure_mul_image_eq` : **Schreier's Lemma**: If `R : set G` is a right_transversal of `H : subgroup G` with `1 ∈ R`, and if `G` is generated by `S : set G`, then `H` is generated by the `set` `(R * S).image (λ g, g * (to_fun hR g)⁻¹)`. - `fg_of_index_ne_zero` : **Schreier's Lemma**: A finite index subgroup of a finitely generated group is finitely generated. -/ open_locale pointwise namespace subgroup open mem_right_transversals variables {G : Type*} [group G] {H : subgroup G} {R S : set G} lemma closure_mul_image_mul_eq_top (hR : R ∈ right_transversals (H : set G)) (hR1 : (1 : G) ∈ R) (hS : closure S = ⊤) : (closure ((R * S).image (λ g, g * (to_fun hR g)⁻¹)) : set G) * R = ⊤ := begin let f : G → R := λ g, to_fun hR g, let U : set G := (R * S).image (λ g, g * (f g)⁻¹), change (closure U : set G) * R = ⊤, refine top_le_iff.mp (λ g hg, _), apply closure_induction_right (eq_top_iff.mp hS (mem_top g)), { exact ⟨1, 1, (closure U).one_mem, hR1, one_mul 1⟩ }, { rintros - s hs ⟨u, r, hu, hr, rfl⟩, rw show u * r * s = u * ((r * s) * (f (r * s))⁻¹) * f (r * s), by group, refine set.mul_mem_mul ((closure U).mul_mem hu _) (f (r * s)).coe_prop, exact subset_closure ⟨r * s, set.mul_mem_mul hr hs, rfl⟩ }, { rintros - s hs ⟨u, r, hu, hr, rfl⟩, rw show u * r * s⁻¹ = u * (f (r * s⁻¹) * s * r⁻¹)⁻¹ * f (r * s⁻¹), by group, refine set.mul_mem_mul ((closure U).mul_mem hu ((closure U).inv_mem _)) (f (r * s⁻¹)).2, refine subset_closure ⟨f (r * s⁻¹) * s, set.mul_mem_mul (f (r * s⁻¹)).2 hs, _⟩, rw [mul_right_inj, inv_inj, ←subtype.coe_mk r hr, ←subtype.ext_iff, subtype.coe_mk], apply (mem_right_transversals_iff_exists_unique_mul_inv_mem.mp hR (f (r * s⁻¹) * s)).unique (mul_inv_to_fun_mem hR (f (r * s⁻¹) * s)), rw [mul_assoc, ←inv_inv s, ←mul_inv_rev, inv_inv], exact to_fun_mul_inv_mem hR (r * s⁻¹) }, end /-- **Schreier's Lemma**: If `R : set G` is a right_transversal of `H : subgroup G` with `1 ∈ R`, and if `G` is generated by `S : set G`, then `H` is generated by the `set` `(R * S).image (λ g, g * (to_fun hR g)⁻¹)`. -/ lemma closure_mul_image_eq (hR : R ∈ right_transversals (H : set G)) (hR1 : (1 : G) ∈ R) (hS : closure S = ⊤) : closure ((R * S).image (λ g, g * (to_fun hR g)⁻¹)) = H := begin have hU : closure ((R * S).image (λ g, g * (to_fun hR g)⁻¹)) ≤ H, { rw closure_le, rintros - ⟨g, -, rfl⟩, exact mul_inv_to_fun_mem hR g }, refine le_antisymm hU (λ h hh, _), obtain ⟨g, r, hg, hr, rfl⟩ := show h ∈ _, from eq_top_iff.mp (closure_mul_image_mul_eq_top hR hR1 hS) (mem_top h), suffices : (⟨r, hr⟩ : R) = (⟨1, hR1⟩ : R), { rwa [show r = 1, from subtype.ext_iff.mp this, mul_one] }, apply (mem_right_transversals_iff_exists_unique_mul_inv_mem.mp hR r).unique, { rw [subtype.coe_mk, mul_inv_self], exact H.one_mem }, { rw [subtype.coe_mk, inv_one, mul_one], exact (H.mul_mem_cancel_left (hU hg)).mp hh }, end /-- **Schreier's Lemma**: If `R : set G` is a right_transversal of `H : subgroup G` with `1 ∈ R`, and if `G` is generated by `S : set G`, then `H` is generated by the `set` `(R * S).image (λ g, g * (to_fun hR g)⁻¹)`. -/ lemma closure_mul_image_eq_top (hR : R ∈ right_transversals (H : set G)) (hR1 : (1 : G) ∈ R) (hS : closure S = ⊤) : closure ((R * S).image (λ g, ⟨g * (to_fun hR g)⁻¹, mul_inv_to_fun_mem hR g⟩) : set H) = ⊤ := begin rw [eq_top_iff, ←map_subtype_le_map_subtype, monoid_hom.map_closure, set.image_image], exact (map_subtype_le ⊤).trans (ge_of_eq (closure_mul_image_eq hR hR1 hS)), end /-- **Schreier's Lemma**: If `R : finset G` is a right_transversal of `H : subgroup G` with `1 ∈ R`, and if `G` is generated by `S : finset G`, then `H` is generated by the `finset` `(R * S).image (λ g, g * (to_fun hR g)⁻¹)`. -/ lemma closure_mul_image_eq_top' [decidable_eq G] {R S : finset G} (hR : (R : set G) ∈ right_transversals (H : set G)) (hR1 : (1 : G) ∈ R) (hS : closure (S : set G) = ⊤) : closure ((((R * S).image (λ g, ⟨_, mul_inv_to_fun_mem hR g⟩)) : finset H) : set H) = ⊤ := begin rw [finset.coe_image, finset.coe_mul], exact closure_mul_image_eq_top hR hR1 hS, end lemma exists_finset_card_le_mul (hH : H.index ≠ 0) {S : finset G} (hS : closure (S : set G) = ⊤) : ∃ T : finset H, T.card ≤ H.index * S.card ∧ closure (T : set H) = ⊤ := begin haveI : decidable_eq G := classical.dec_eq G, obtain ⟨R₀, hR : R₀ ∈ right_transversals (H : set G), hR1⟩ := exists_right_transversal (1 : G), haveI : fintype (G ⧸ H) := fintype_of_index_ne_zero hH, haveI : fintype R₀ := fintype.of_equiv _ (mem_right_transversals.to_equiv hR), let R : finset G := set.to_finset R₀, replace hR : (R : set G) ∈ right_transversals (H : set G) := by rwa set.coe_to_finset, replace hR1 : (1 : G) ∈ R := by rwa set.mem_to_finset, refine ⟨_, _, closure_mul_image_eq_top' hR hR1 hS⟩, calc _ ≤ (R * S).card : finset.card_image_le ... ≤ (R ×ˢ S).card : finset.card_image_le ... = R.card * S.card : R.card_product S ... = H.index * S.card : congr_arg (* S.card) _, calc R.card = fintype.card R : (fintype.card_coe R).symm ... = _ : (fintype.card_congr (mem_right_transversals.to_equiv hR)).symm ... = fintype.card (G ⧸ H) : quotient_group.card_quotient_right_rel H ... = H.index : H.index_eq_card.symm, end /-- **Schreier's Lemma**: A finite index subgroup of a finitely generated group is finitely generated. -/ lemma fg_of_index_ne_zero [hG : group.fg G] (hH : H.index ≠ 0) : group.fg H := begin obtain ⟨S, hS⟩ := hG.1, obtain ⟨T, -, hT⟩ := exists_finset_card_le_mul hH hS, exact ⟨⟨T, hT⟩⟩, end lemma rank_le_index_mul_rank [hG : group.fg G] {H : subgroup G} (hH : H.index ≠ 0) : @group.rank H _ (fg_of_index_ne_zero hH) ≤ H.index * group.rank G := begin haveI := fg_of_index_ne_zero hH, obtain ⟨S, hS₀, hS⟩ := group.rank_spec G, obtain ⟨T, hT₀, hT⟩ := exists_finset_card_le_mul hH hS, calc group.rank H ≤ T.card : group.rank_le H hT ... ≤ H.index * S.card : hT₀ ... = H.index * group.rank G : congr_arg ((*) H.index) hS₀, end end subgroup